Link to home
Start Free TrialLog in
Avatar of universalmonster
universalmonster

asked on

php if num_rows

Hi All,

I'm going crazy with an IF statement.

This is my working code
if ($result3 = $conn->query($sql3)) { 
while($row3 = $result3->fetch_assoc()) { 
echo $row3["photopath"]; 
} 
}

Open in new window

and i'm trying to say
if ($row3 ->num_rows === 0) {
echo 'ProfilePics/Like.png'; }
else
<RUN WORKING CODE ABOVE>

Open in new window


Any help would be greatly appreciated.

Cheers,

Pete
Avatar of Karthik Ramachandran
Karthik Ramachandran

What exactly you are trying to achieve? Is there an error in this code?
Avatar of Julian Hansen
Based on your post I am assuming this comes first
if ($row3 ->num_rows === 0) {
echo 'ProfilePics/Like.png'; }
else

Open in new window

In which case Where is $row3 being set?
You're using the wrong item to try to get 'num_rows'.  It should be like this.  Note that if the number of rows is 0, doing $result3->fetch_assoc() won't work.
$number_rows = $result3->num_rows;

Open in new window

How to use the MySQL database, showing MySQL, MySQLi and PDO extensions.  Code examples are included.
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
ASKER CERTIFIED SOLUTION
Avatar of William Nettmann
William Nettmann
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
HI,

You need to change the variable names and conditions as follows,

if ($result3 = $conn->query($sql3)) { 

	if ($result3->num_rows === 0) {
		echo 'ProfilePics/Like.png'; 
		exit;
	}else{
		while($row3 = $result3->fetch_assoc()) { 
			echo $row3["photopath"]; 
		} 
	}

}

Open in new window

The problem with testing $result3->num_rows for zero is that this assumes two things, to wit, that $result3 is an object, and that it was created by a query that succeeded.  A better strategy might be to test the results of the query before using data that might or might not have been created by a successful or failing query.  It's all in the article, with code samples.