简体   繁体   中英

php if sql query returns valid result

I'm sure this is a simple fix, I want to run a code block if an sql query comes back with a positive result. something like:

if($query = mysqli_query($cxn,"[query]"))
{
Code to be executed if the query returns a positive result
}

I have tried this format but doesn't work. I'm sure I have done this before but I'm running in to a wall here.

Hope you can help.

As stated in php.net/manual/mysqli.query.php , mysqli_query will:

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

You should for you next question specify what you mean by positive result . But this code will see if there was an error, if the query returned an empty set, and so on... (I have not tried to run the code)

$result = mysqli_query($cxn,"[query]");
if ($result === FALSE) {
    echo "There was an error";
}
else if ($result === TRUE) {
    echo "The query was successful (a query that didn't return anything)";
}
else if (mysqli_num_rows($result) == 0) {
    echo "The result is empty"
}
else {
    echo '$result contains data';
}

So you mean if the query doesn't fail? then:

$query = mysqli_query($cxn, "[query]");
if($query !== false) {
  // Code to be executed if the query returns a positive result
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM