Re: mysqli_query and mysqli_fetch_array
| From: | Jim Lucas | Date: | Fri, 09 Jan 2009 05:12:26 +0000 |
| Subject: | Re: mysqli_query and mysqli_fetch_array | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-285800@lists.php.net to get a copy of this message | ||
AESB wrote:
Hope you are all happy and doing well! I've chosen a piece of chunk of code from a movie browser script known as mysqli_query and mysqli-fetch-array for testing. It's possble a reason preventing it's execution. See any bugs in the following I'm using APACHE 2.2, PHP 5.2.6 and MySQL 5.1 <?php // ***** browse_movies.php ***** // Connect to MySQL and select the database: $dbc = mysqli_connect('localhost', 'xxxx', 'xxxxxxxx','movies') or die ('Could not connect to MySQL: ' . mysqli_connect_error()); // Define the query: $q = "SELECT first_name, last_name FROM directors"; // Run the query: $r = mysqli_query($dbc, $q)or die("Error: ".mysqli_error($dbc)); // Display all of the records: while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { echo "{$row['first_name']} <i>{$row['last_name']}</i><br />\n"; } // Clean up: mysqli_free_result ($r); mysqli_close($dbc); ?>I see a few problems. Try this as a replacement and see what you get. It is all the code you gave, just re factored a little. <?php // ***** browse_movies.php ***** // Connect to MySQL and select the database: $host = 'localhost'; $user = 'xxxx'; $pass = 'xxxxxxxx'; $db = 'movies'; $dbc = new mysqli($host, $user, $pass, $db); # returns this: http://us.php.net/manual/en/class.mysqli.php # You need to make sure that the db connection was successful. # Your code assumed the connection always worked. if ( mysqli_connect_errno() ) { die('Connection Error: ' . mysqli_connect_error()); } // Define the query: $q = "SELECT first_name, last_name FROM directors"; // Run the query: # You need to make sure that the SELECT query was successful. # Your code assumed that you would always get a result, hence it would never fail... if ( $results = $dbc->query($q) ) { # returns this: http://us.php.net/manual/en/class.mysqli-result.php # Check to make sure you actually got something back. if ( $results->num_rows ) { // Display all of the records: while ( $row = $results->fetch_assoc() ) { echo "{$row['first_name']} <i>{$row['last_name']}</i><br />\n"; } } else { echo 'No movies to browse.'; } $results->close(); } else { die("Query Error: ".$dbc->error . " Q={$q}"); } $dbc->close(); ?> I have never used mysqli_* before, so I'm not sure if this is going to do what I think it is, but it should start you down the road to recovery... :) -- Jim Lucas "Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them." Twelfth Night, Act II, Scene V by William Shakespeare