Friday, December 31, 2010

php mySQL - mysql_query();

Following the previous sample code, this one gets the data from the table and display them. I have edited the error handling parts. But again, there is something that bothers me about this code.

<?php
$user="root";
$password="passpass";
$database="myfirstdatabase";

$link = mysql_connect('localhost',$user,$password);
if (!$link){
  die('Could not connect: ' . mysql_error());
}
echo "connected to server<br />";

if (!mysql_select_db($database)){
    die('Could not select database: ' . mysql_error());
}
echo "connected to database<br />";
$query="SELECT * FROM contacts";
$result=mysql_query($query);
$num=mysql_numrows($result);

mysql_close($link);
echo "disconnected <br />";

echo "<b><center>Database Output</center></b><br><br>";
$i=0;
while ($i < $num){
  $first=mysql_result($result,$i,"first");
  $last=mysql_result($result,$i,"last");
  $phone=mysql_result($result,$i,"phone");
  $mobile=mysql_result($result,$i,"mobile");
  $fax=mysql_result($result,$i,"fax");
  $email=mysql_result($result,$i,"email");
  $web=mysql_result($result,$i,"web");

  echo "<b>$first $last</b><br />
  Phone: $phone<br />
  Mobile: $mobile<br />
  Fax: $fax<br />
  E-mail: $email<br />
  Web: $web<br /><hr /><br />";

  $i++;
}
?>


What is in $result?
$result=mysql_query($query);

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
(from: http://php.net/manual/en/function.mysql-query.php)

So, it is a resource.
What is a resource?

A resource is a special variable, holding a reference to an external resource.
(from: http://www.php.net/manual/en/language.types.resource.php)

I see..
It is just referencing to the table in the database, right?
Then, howcome it can still get to the data even after the connecton to database is deiconnected by mysql_close($link); ?

Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.
(from: http://www.php.net/manual/en/language.types.resource.php)

ummm...
I guess, it means...
The table file is left open even the connection to the table is disconnected, and the file won't be closed until the resource has no more reference to it.

But I think I perfer to have mysql_close($link); after it is done processing. Later, I need to find out the standard way of handling
.

No comments:

Post a Comment