Vonder Vonder - 9 months ago 63
MySQL Question

Count number of rows in Mysql using PHP7

I have upgraded php on my server from version 5 to 7 and I found out that mysql functions are depreciated and now I should use mysqli. I updated the following code (mysqli instead of mysql) that I used to print number of rows in a given table, but it doesn't work as it used to. Any help greatly appreciated.

$link = mysql_connect("xxx", "xxx", "xxx");
mysql_select_db("xxx", $link);

$result = mysql_query("SELECT * FROM blackandwhite", $link);
$num_rows = mysql_num_rows($result);

echo "$num_rows Rows\n"; This works in PHP5

Updated code PHP7:

$link = mysqli_connect("xxx", "xxx", "xxx");
mysqli_select_db("xxx", $link);

$result = mysqli_query("SELECT * FROM blackandwhite", $link);
$num_rows = mysqli_num_rows($result);

echo "$num_rows Rows\n"; This doesnt work anymore.

Answer Source

The mysqli_ functions actually accept the link as the first argument, as it is non-optional like it is with the normal mysql_ functions.

This should work as you expect:

$link = mysqli_connect("xxx", "xxx", "xxx");
mysqli_select_db($link, "xxx");

$result = mysqli_query($link, "SELECT * FROM blackandwhite");
$num_rows = mysqli_num_rows($result);

echo "$num_rows Rows\n";