0

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.

1
  • 1
    "doesn't work" is not a meaningful description of what happened. Did you check for errors? What do you mean by a "positive result"? try else { print mysqli_error($cxn); } Commented Aug 24, 2013 at 22:39

2 Answers 2

2

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';
}
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.