php - How can I return a no records found message if results are empty?
Get the solution ↓↓↓Solution:
This will do
$i=0;
while ($show = mysqli_fetch_array($returnquery)) {
echo "variable is set to $show[code]";
$i++;
}
if ( $i==0) echo "variable is not set";
//Or as pointed out in the comments a more "correct" solution would be
if($prodquery->num_rows === 0)
{
echo 'No results';
} else {
while ($show = mysqli_fetch_array($returnquery)) {
echo "variable is set to $show[code]";
}
}
Answer
Solution:
Use to count what has returned.
$returnquery = mysqli_query($con,"select coupon_id, code, discount from
oc_coupon where coupon_id = '$code' ");
$row_cnt = mysqli_num_rows($returnquery);
if($row_cnt > 0) {
while ($show = mysqli_fetch_array($returnquery)) {
echo "variable is set to $show['code']"; // quote the identifier
}
} else {
echo "variable is not set";
}
Warning!
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
Answer
Solution:
while ($show = mysqli_fetch_array($returnquery)) {
if(mysqli_num_rows($show)) {
echo "variable is set to $show[code]";
} else {
echo "variable is not set";
}
}
Answer
Solution:
Aside from any other issues, let me just briefly explain your main logic error.
this only shows the code but not the error message if blank
This is because you're usingif(isset($show))
to display the error message in a section of code that is not reachable ifisset($show)
evaluates to true.
When you have iterated all your query results, or if there are no results to iterate, thenmysqli_fetch_array($returnquery)
will returnnull
. When that happens, it no longer satisfies the continuation condition for your while loop (null evaluates to false), so the contents of the loop will not be executed, and your code will continue after the loop.
There are various ways to fix it. One way is to set a variable in the while loop and check it afterward to see if any results were shown.
while ($show = mysqli_fetch_array($returnquery)) {
echo "variable is set to $show[code]";
$has_results = true;
}
if (!isset($has_results)) {
echo "variable is not set";
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: uncaught mysqli_sql_exception
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.