cgm225 Posted December 7, 2007 Share Posted December 7, 2007 I was looking on the web for a simple MySQL class example and found the one below (link included in the code). I feel like I understand it all with the exception of the if / else statements in the FetchArray and FetchNum functions. Could someone help me understand these statements, possibly with an example of how the class could be used under both circumstances? Regardless, thank you all for your help in advance! <?php // Taken and modified from:: http://www.talkphp.com/showthread.php?t=1459 class mysql { private $connection; protected $result; protected $sql; public function Connect($host, $name, $pass, $db) { $this->connection = mysql_connect($host,$name,$pass); mysql_select_db($db, $this->connection); return true; } public function Close(){ mysql_close($this->connection); return true; } public function FetchArray($query){ /* I added this if / else statement, to this method and the one below This will allow you to either pass it directly a SQL statement, or a resource object Ex: $sql = "SELECT * FROM Table WHERE 1=1"; $get = $DB->FetchArray($sql); -- OR -- $sql = "SELECT * FORM Table WHERE 1=1"; $get = $DB->Query($sql); while($r = $DB->FetchArray($get)) { ... } */ if(is_resource($query)) { $rows = mysql_fetch_array($query); } else { $rows = mysql_fetch_array($this->Query($query)); } return $rows; } public function FetchNum($query){ if(is_resource($query)) { $num = mysql_num_rows($query); } else { $num = mysql_num_rows($this->Query($query)); } return $num; } public function Query($sql){ $this->sql = $sql; $this->result = mysql_query($this->sql) or die(mysql_error()); return $this->result; } } ?> Quote Link to comment Share on other sites More sharing options...
emehrkay Posted December 7, 2007 Share Posted December 7, 2007 when you run a query $q = "SELECT * FROM table"; $r = mysql_query($q); what $r is set to is a resource. So you can hand those two methdos a query or a resource $mysql = new mysql(); $num_rows = $mysql->FetchNum("SELECT * FROM table"); //is the same as $mysql = new mysql(); $res = $mysql->Query("SELECT * FROM table"); $num_rows = $mysql->FetchNum($res); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.