Page 1 of 1

[SOLVED] Mysqli ?

Posted: Tue May 09, 2006 3:26 pm
by baggypants303
Hey guys,

I'm trying to use an associative array to set vars fetched from a mysql db..For some reason I keep getting:

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\wamp\www\SAT\question.php on line 32
No rows found!0

The table does have one entry, so it shouldn't be null or empty...When I use the while loop to fetch the array in the db.php file it works...but when I try in questions.php (while require(db.php)) it doesn't work.....? why?

Here is my database connection php file:

Code: Select all

<?php 

// set server access variables 
$host = "XXXXXXXXXXX"; 
$user = "XXXXXXXXXXX"; 
$pass = "XXXXXXXXXXX"; 
$db = "XXXXXXXXXX"; 

// open connection 
$connection = mysqli_connect($host, $user, $pass, $db) or die ("Unable to connect!"); 

// create query 
$query = "SELECT * FROM questions"; 

// execute query 
$result = mysqli_query($connection, $query) or die ("Error in query: $query. ".mysqli_error()); 

// free result set memory 
mysqli_free_result($result); 

// close connection 
mysqli_close($connection); 

?>
Here is the loop (code fragment) i'm using in question.php to set the associative array:

Code: Select all

/* Default Constructor
	 *
	 */
    public function __construct() {
		// see if any rows were returned 
		if (mysqli_num_rows($result) > 0) { 
		    while($row = mysqli_fetch_assoc($result)) { 
		       $id = $row['id']; 
		    } 
		} 
		else { 
		    // no 
		    // print status message 
		    echo "No rows found!"; 
		} 
	}
Help appreciated, thanks!

Posted: Tue May 09, 2006 3:35 pm
by RobertGonzalez
If $result is in the class, you need to scope it. I think you need to use global $result, otherwise the method will think that $result is a variable used only within the scope of the function. The way your example shows, $result is not set and is therefore null.

Posted: Tue May 09, 2006 5:27 pm
by $phpNut
Yeah, you'll need to globalise the variable. so the function can get to it.

Posted: Tue May 09, 2006 6:00 pm
by RobertGonzalez
To kinda nudge you in the right direction...

Code: Select all

<?php
/* Default Constructor
 *
 */
public function __construct() {
	global $result;
	// see if any rows were returned
	if (mysqli_num_rows($result) > 0) {
		while($row = mysqli_fetch_assoc($result)) {
			$id = $row['id'];
		}
	}
	else {
		// no print status message
		echo "No rows found!";
	}
} 
?>
On a side note, I don't think I would use $result as a global var, seeing as you are more than likely going to be using the variable result in a lot of other instances. Just my opinion.

Posted: Tue May 09, 2006 6:51 pm
by baggypants303
ok.

I put the query and result in the Question class..solved the problem, thanks.