1

i have a select query. another short if-form checks if this select query returns something or not.

so i have:

$query = "SELECT `a` FROM `b` WHERE c='$c'";
$test = ($query = mysql_query($query)) ? $mysql_num_rows($query) : 0;

so i would like to convert into mysqli but the following code seems to be wrong ($db = mysqli):

$query = "SELECT `a` FROM `b` WHERE c='$c'";
$test = ($query = $db->query($query)) ? $db->num_rows($query) : 0;

when using:

$test = ($query = mysqli_query($query)) ? mysqli_num_rows($query) : 0;

it will echo the error message:

Warning: mysqli_query() expects at least 2 parameters, 1 given...

so if there is someone who would be that friendly and could give me an advise to solve this i really would appreciate. thanks a lot.

bonny
  • 3,147
  • 11
  • 41
  • 61

2 Answers2

1

mysqli in procedural mode doesn't default to using the last-established connection like the mysql library does. You have to explicitly include the connection each time:

$test = ($query = mysqli_query($conn, $query)) ? mysqli_num_rows($query) : 0;
                               ^^^^^^

As well, for num_rows, it's mysqli_stmt_num_rows($result)

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • using this echos: Warning: mysqli_query() expects parameter 1 to be mysqli, null given // $db = new mysqli("localhost", "my_user", "my_password", "world"); – bonny Apr 21 '12 at 23:08
  • well, yeah, you have to pass in whatever var you're using for the mysqli connection handle... That'd be whatever was returned from mysqli_connect() – Marc B Apr 21 '12 at 23:09
  • sorry, i'm having understanding problems. what does that exactly mean? thanks. – bonny Apr 21 '12 at 23:13
  • okay as i get it, this errormessage will say that $db is not given. but, $db is $db = new mysqli("localhost", "my_user", "my_password", "world") – bonny Apr 21 '12 at 23:36
  • hmm... i forgot to say that this happens in a function so that i had to set global $db. thanks a lot for helping. – bonny Apr 21 '12 at 23:49
  • "mysqli in procedural mode doesn't default to using the last-established connection like the mysql library does." It's a pain but an obligation. – Nadjib Mami Dec 05 '12 at 15:44
0

If you're using the procedural style (i.e. mysqli_query instead of OO approach), then you should add the $link var to your parameters of the mysqli_query

the_red_baron
  • 868
  • 7
  • 14