开发者

mysql_fetch_array problem

i am trying to do a guestbook in php but i am having some problems with mysql_fet开发者_开发百科ch_array function. I don't understand why. I try to debug by putting die("Error ".mysql_error()) but nothing prints out. I guarantee that all my variables are correctly initialized. Here is my code :

<?php

 $nbmessagesPP = 10;
 mysql_connect(HOST, USER,PASSWORD) or die( "Unable to connect to database");
 mysql_select_db(DBNAME) or die ("Unable to select database!"); 

 .......

 if(isset($_GET['page'])){
    $page = $_GET['page'];
  } else {
    $page = 1;
  }
  $first_msg = ($page - 1) * $nb_of_Page;
  $query = 'Select * from livredor ORDER BY id DESC LIMIT '.$first_msg.', '.$nbmessagesPP;
  $rep = mysql_query($query) or exit("Error in query".mysql_error());

  $v = true;
  while($v){
      $v = ($data = mysql_fetch_array($rep) or die ("Error fetching the data : ".mysql_error()));
      echo "<p>id -> ".$data['id']."</p>";    
      echo "<p>pseudo ->".$data['pseudo']."</p>";
      echo "<p>messages ->".$data['message']."</p>";
      echo "<hr/>";
  } 
  mysql_close();
?> 

Can someone help me ;)


Your code doesn't deal with errors or the last row correctly. When $v is false, it still goes on to print some data. It would be better rewritten as:

while (($data = mysql_fetch_array($rep))) {    
  echo   
  ... 
}

That forces the evaluation of the fetch before moving on to the printing.


The problem is that you're trying to access elements of the result that don't exist. mysql_fetch_array returns a regular array, with integer indices. What you want is mysql_fetch_assoc, which returns an associative array.

Edit: You also have the problem Chris describes, not dealing with the last row correctly.


Generally, if you're receiving an error saying "supplied argument is not a valid MySQL result resource" it means that your MySQL query has failed, therefor not returning a valid result resource.

Try to echo out $query before sending it through mysql_query(), then try placing the echo'd query into phpMyAdmin and see if it returns any results.


Ok i have found the problem. The problem was that in another page i had a mysql_connection and in that page i was creating a new one. I just catch the return value of mysql_connect function and then close it with mysql_close function at the end. Like this :

  <?php
     $link = mysql_connect(HOST, USER,PASSWORD) or die( "Unable to connect to database");
     mysql_select_db(DBNAME) or die ("Unable to select database!"); 
     .....

     while($data = mysql_fetch_array($rep)) {//i do something here}

     mysql_close($link);    
 ?>

Thanks for your answers folks :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜