/    Sign up×
Community /Pin to ProfileBookmark

Where To Add “IF” To Check If Data Fetching Success Or Not ?

Folks,

I need to get the code to echo “Sorry! Something went wrong!” if for some reason fetching data from db was unsuccessful.
Here are some ways I am doing it. 3 samples.
NOTE the IFs on each sample. That is where the 3 samples differ.
Tell me which one I should stick to and why that one over the others.
I ranked them according to favourite ….
What is your ranking if all 3 would work and is fine ?

1.

[code]
<?php

$server = ‘localhost’;
$user = ‘root’;
$password = ”;
$database = ‘bruteforce’;

$conn = mysqli_connect(“$server”,”$user”,”$password”,”$database”);

$keywords = ‘keyword’;

$query = ‘SELECT COUNT(id) from links WHERE keywords = ?’;
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,’s’,$keywords);
mysqli_stmt_execute($stmt);
if($result = mysqli_stmt_bind_result($stmt,$row_count))
{
mysqli_stmt_fetch($stmt);
echo ‘Result Found: ‘ .$row_count; echo ‘<br>’;
}
else
{
echo ‘Sorry! Something went wrong!’; echo ‘<br>’;
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
?>
[/code]

2.

[code]
<?php

$server = ‘localhost’;
$user = ‘root’;
$password = ”;
$database = ‘bruteforce’;

$conn = mysqli_connect(“$server”,”$user”,”$password”,”$database”);

$keywords = ‘keyword’;

$query = ‘SELECT COUNT(id) from links WHERE keywords = ?’;
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,’s’,$keywords);
if(mysqli_stmt_execute($stmt))
{
$result = mysqli_stmt_bind_result($stmt,$row_count);
mysqli_stmt_fetch($stmt);
echo ‘Result Found: ‘ .$row_count; echo ‘<br>’;
}
else
{
echo ‘Sorry! Something went wrong!’; echo ‘<br>’;
}

mysqli_stmt_close($stmt);
mysqli_close($conn);
}

?>
[/code]

3.

[code]
<?php

$server = ‘localhost’;
$user = ‘root’;
$password = ”;
$database = ‘bruteforce’;

$conn = mysqli_connect(“$server”,”$user”,”$password”,”$database”);

$keywords = ‘keyword’;

$query = ‘SELECT COUNT(id) from links WHERE keywords = ?’;
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,’s’,$keywords);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_bind_result($stmt,$row_count);
if(mysqli_stmt_fetch($stmt))
{
echo ‘Result Found: ‘ .$row_count; echo ‘<br>’;
}
else
{
echo ‘Sorry! Something went wrong!’; echo ‘<br>’;
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}

?>
[/code]

to post a comment
PHP

15 Comments(s)

Copy linkTweet thisAlerts:
@developer_webauthorApr 25.2021 — Folks,

The above post was regarding echoing a single row from mysql db tbl.

This post is about echoing multiple records from db, using the WHILE loop.

Both these posts are regarding using mysqli_stmt_bind_result() and procedural style programming.

I need to show website visitor that something went wrong should him making queries to my database fails technically. Want to get the php code to echo "Sorry! Something went wrong!" if for some reason data fetching failed.

Following are some ways I am trying to accomplish this. 3 samples. They result in neverending loops thus crashing my browser. (NOTE the IFs on each sample. That is where the 3 samples differ).

I ranked them according to favourite .... How to fix this to bare minimum to achieve my purpose ? Would appreciate codes samples. I know how to achieve this with mysqli_stmt_get_result() but need to learn with the mysqli_stmt_bind_result() in procedural style programming. Not into oop yet. Nor pdo.

1.
<i>
</i>&lt;?php

//LOOPS NEVERENDING

$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';

$conn = mysqli_connect("$server","$user","$password","$database");

$keywords = 'keyword';

$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$keywords);
if(mysqli_stmt_execute($stmt))
{
while($result = mysqli_stmt_bind_result($stmt,$id,$domain))
{
mysqli_stmt_fetch($stmt);
<br/>
<i> </i> echo 'Id: ' .$id; echo '&lt;br&gt;';
<i> </i> echo 'Domain: ' .$domain; echo '&lt;br&gt;';
<i> </i>
<i> </i> if(!$result)
<i> </i> {
<i> </i> echo 'Sorry! Something went wrong. Try again later.';
<i> </i> }
<i> </i> }
<i> </i>}
<i> </i>mysqli_stmt_close($stmt);
<i> </i>mysqli_close($conn);
}

?&gt;


2.
<i>
</i>&lt;?php

//LOOPS NEVERENDING

$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';

$conn = mysqli_connect("$server","$user","$password","$database");

$keywords = 'keyword';

$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$keywords);
mysqli_stmt_execute($stmt);
<br/>
<i> </i>while(mysqli_stmt_bind_result($stmt,$id,$domain))
<i> </i>{
<i> </i> if(mysqli_stmt_fetch($stmt)) //If 'Rows Fetching' were successful.
<i> </i> {
<i> </i> echo 'Id: ' .$id; echo '&lt;br&gt;';
<i> </i> echo 'Domain: ' .$domain; echo '&lt;br&gt;';
<i> </i> }
<i> </i> else //If 'Rows Fetching' failed.
<i> </i> {
<i> </i> echo 'Sorry! Something went wrong. Try again later.';
<i> </i> }
<i> </i>}
<i> </i>mysqli_stmt_close($stmt);
<i> </i>mysqli_close($conn);
}

?&gt;




3.
<i>
</i>&lt;?php

//LOOPS NEVERENDING

$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';

$conn = mysqli_connect("$server","$user","$password","$database");

$keywords = 'keyword';

$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$keywords);
if(mysqli_stmt_execute($stmt)) //If 'Query Execution' was successful.
{
while(mysqli_stmt_bind_result($stmt,$id,$domain))
{
mysqli_stmt_fetch($stmt);
<br/>
<i> </i> echo 'Id: ' .$id; echo '&lt;br&gt;';
<i> </i> echo 'Domain: ' .$domain; echo '&lt;br&gt;';
<i> </i> }
<i> </i>}
<i> </i>else //If 'Query Execution' failed.
<i> </i>{
<i> </i> echo 'Sorry! Something went wrong. Try again later.';
<i> </i>}
<i> </i>mysqli_stmt_close($stmt);
<i> </i>mysqli_close($conn);
}

?&gt;



Now you are welcome to show me how it should have been done!

Don't forget to answer my previous post before replying to this one.

Thanks.

**EDIT: Ignore this post. I have learnt that I never should loop in mysqli_stmt_bind_result() as it will always result TRUE. Should loop mysqli_stmt_fetch().**
Copy linkTweet thisAlerts:
@developer_webauthorApr 26.2021 — Folks,

This is my 3rd post in this thread.

Ignore my 2nd post as I have found the answer to it:

https://stackoverflow.com/questions/67252495/on-which-line-to-check-if-data-fetching-successful-or-not-when-using-mysqli-stmt

But DO REPLY to my original post. IMPORTANT.

Thanks!
Copy linkTweet thisAlerts:
@developer_webauthorMay 01.2021 — Folks,

You won't get overwhelmed to reply to this thread if you answer one post after the other serially.
Copy linkTweet thisAlerts:
@developer_webauthorMay 03.2021 — @inkt,

No one knows php prepared statements enough to answer ?

https://www.webdeveloper.com/d/393880-where-to-add-if-to-check-if-data-fetching-success-or-not
Copy linkTweet thisAlerts:
@developer_webauthorMay 04.2021 — @kiwis80

Do you know php prepared statements enough to answer ?

https://www.webdeveloper.com/d/393880-where-to-add-if-to-check-if-data-fetching-success-or-not
Copy linkTweet thisAlerts:
@NogDogMay 05.2021 — You only do the bind result once -- you don't want to loop on it. (It's just saying what variables to assign results to when you do the fetch.)

I might try to organize things more like this -- okay, it wouldn't be at all like this because I'd use PDO and it would be much cleaner.
[code=php]
$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt, $query)) {
mysqli_stmt_bind_param($stmt, 's', $keywords);
if(mysqli_stmt_execute($stmt)) {
if(mysqli_stmt_num_rows($stmt) == 0) {
echo "No matching results found.";
}
else {
mysqli_stmt_bind_result($stmt, $id, $domain);
while (mysqli_stmt_fetch($stmt)) {
echo "ID: $id<br>Domain: $domain<br>";
}
}
}
else {
db_error($conn);
}

}
else {
db_error($conn);
}

function db_error(mysqli $conn) {
error_log("DB ERROR:n" . mysqli_error($conn));
echo "<p class='error>Sorry! Something went wrong and has been logged. Try again later.</p>";
}
[/code]
Copy linkTweet thisAlerts:
@developer_webauthorMay 08.2021 — @NogDog#1631224

I actually prefer your code over mine because it has more checkpoints to see if anything goes wrong.

But guess what ? Your code echoes:

**No matching results found.**

I should not get this echoed because I am searching for the keyword 'keyword' in the column 'keywords' and that word exists in a row.

Here is your code. I just added the mysqli_error_reporting. That is all. Even without my addition, I still get echoed the same.
<i>
</i>&lt;?php
//NOGDOG CODE

$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';

if(!$conn = mysqli_connect("$server","$user","$password","$database"))
{
echo 'Connection Error: ' .mysqli_connect_error($conn); echo '&lt;br&gt;';
echo 'Connection Error Number: ' .mysqli_connect_errno($conn); echo '&lt;br&gt;';
}

$keywords = "keyword";
$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$keywords);
if(mysqli_stmt_execute($stmt))
{
if(mysqli_stmt_num_rows($stmt) == 0)
{
echo "No matching results found.";
}
else
{
mysqli_stmt_bind_result($stmt,$id,$domain);
while(mysqli_stmt_fetch($stmt))
{
echo "ID: $id&lt;br&gt;Domain: $domain&lt;br&gt;";
}
}
}
else
{
db_error($conn);
}
}
else
{
db_error($conn);
}

function db_error(mysqli $conn)
{
error_log("DB ERROR:n" . mysqli_error($conn));
echo "&lt;p class='error&gt;Sorry! Something went wrong and has been logged. Try again later.&lt;/p&gt;";
}

?&gt;


Now look at my old code that I wanted your help on. It works. It echoes the following when I do a keyword search for 'keyword' on the 'keywords' column in the 'links' table.

I get echoed ...

**Domain: google.com

Id: 10

Domain: yahoo.com

102**

<i>
</i>&lt;?php

$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';

if(!$conn = mysqli_connect("$server","$user","$password","$database"))
{
echo 'Connection Error: ' .mysqli_connect_error($conn); echo '&lt;br&gt;';
echo 'Connection Error Number: ' .mysqli_connect_errno($conn); echo '&lt;br&gt;';
}

$keywords = 'keyword';

$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$keywords);
mysqli_stmt_execute($stmt);
if(!$result = mysqli_stmt_bind_result($stmt,$id,$domain))
{
die('mysqli_stmt_bind_result() Failed!');
}
else
{
while($fetch_result = mysqli_stmt_fetch($stmt))
{
echo 'Id: ' .$id; echo '&lt;br&gt;';
echo 'Domain: ' .$domain; echo '&lt;br&gt;';
echo '&lt;br&gt;';
}

<i> </i> if($fetch_result === FALSE)
<i> </i> {
<i> </i> die('mysqli_stmt_fetch()!');
<i> </i> }
<i> </i>}
<i> </i>mysqli_stmt_close($stmt);
<i> </i>mysqli_close($conn);
}

echo __LINE__; echo '&lt;br&gt;';

?&gt;


What is wrong with your code ?

Both codes are dealing with the same table, same column and are searching for the same keyword. So, why is your code echoing no results found while my code echoes the found result ?
Copy linkTweet thisAlerts:
@developer_webauthorMay 08.2021 — @NogDog,

Read my previous post before reading this one or you won;t understand what I am talking about.

I think I spotted the error on your code.

Look at this:
<i>
</i>if(mysqli_stmt_execute($stmt))
{
if(mysqli_stmt_num_rows($stmt) == 0)
{
echo "No matching results found.";
}
else
{
mysqli_stmt_bind_result($stmt,$id,$domain);
while(mysqli_stmt_fetch($stmt))
{
echo "ID: $id&lt;br&gt;Domain: $domain&lt;br&gt;";
}
}


You did the row counting before the rows fetching. Am I right ?

I fixed your code now to following. See if it is ok or not.
<i>
</i>&lt;?php
//NOGDOG CODE EDITED by adding mysqli error reporting

$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';

if(!$conn = mysqli_connect("$server","$user","$password","$database"))
{
echo 'Connection Error: ' .mysqli_connect_error($conn); echo '&lt;br&gt;';
echo 'Connection Error Number: ' .mysqli_connect_errno($conn); echo '&lt;br&gt;';
}

$keywords = "keyword";
$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$query))
{
db_error($conn);
}
else
{
mysqli_stmt_bind_param($stmt,'s',$keywords);
if(!mysqli_stmt_execute($stmt))
{
db_error($conn);
}
else
{
mysqli_stmt_bind_result($stmt,$id,$domain);
while($fetch_result = mysqli_stmt_fetch($stmt))
{
echo 'Id: ' .$id; echo '&lt;br&gt;';
echo 'Domain: ' .$domain; echo '&lt;br&gt;';
echo '&lt;br&gt;';
}
//OPTION 1
if(mysqli_stmt_num_rows($stmt) == 0)
{
echo "No matching results found.";
}
//OPTION 2
if($fetch_result === FALSE)
{
die('mysqli_stmt_fetch()!');
}
}
}

function db_error(mysqli $conn)
{
error_log("DB ERROR:n" . mysqli_error($conn));
echo "&lt;p class='error&gt;Sorry! Something went wrong and has been logged. Try again later.&lt;/p&gt;";
}

?&gt;


Note the:

**//OPTION 1

//OPTION 2**


First option is from your code.

Second option is from my old code. Actually, that option was from stackoverflow.com.

https://stackoverflow.com/questions/67252495/on-which-line-to-check-if-data-fetching-successful-or-not-when-using-mysqli-stmt/67252635?noredirect=1#comment118902415_67252635

Which option should I stick to NogDog ?
Copy linkTweet thisAlerts:
@NogDogMay 08.2021 — Looks like you have to call [mysqli_stmt_bind_result()](https://www.php.net/manual/en/mysqli-stmt.bind-result.php) between the execute and the execute and the num_rows check. From https://www.php.net/manual/en/mysqli-stmt.num-rows.php:
> This function will only work after mysqli_stmt_store_result() is called to buffer the entire result set in the statement handle.

Yet another mysqli ugliness and reason I'm glad I always use the PDO extension.
Copy linkTweet thisAlerts:
@developer_webauthorMay 11.2021 — @NogDog#1631413

This link you gave explains nothing about mysqli_stmt_bind_result() has to be between mysqli_stmt_execute() and mysqli_stmt_execute() (I assume you meant: mysqli_stmt_fetch()).

Anyway, check my code again on my previous post where I fixed your code, as I did exactly that. I put mysqli_stmt_bind_result() between mysqli_stmt_execute() and mysqli_stmt_fetch().

EDIT: I realise now you were talking about mysqli_stmt_store().

You saying it should be like this ....
<i>
</i>&lt;?php
//NOGDOG CODE EDITED

$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';

if(!$conn = mysqli_connect("$server","$user","$password","$database"))
{
echo 'Connection Error: ' .mysqli_connect_error($conn); echo '&lt;br&gt;';
echo 'Connection Error Number: ' .mysqli_connect_errno($conn); echo '&lt;br&gt;';
}

$keywords = "keyword";
$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$query))
{
db_error($conn);
}
else
{
mysqli_stmt_bind_param($stmt,'s',$keywords);
if(!mysqli_stmt_execute($stmt))
{
db_error($conn);
}
else
{
mysqli_stmt_bind_result($stmt,$id,$domain);
while($fetch_result = mysqli_stmt_fetch($stmt))
{
echo 'Id: ' .$id; echo '&lt;br&gt;';
echo 'Domain: ' .$domain; echo '&lt;br&gt;';
echo '&lt;br&gt;';
}

<i> </i>
<i> </i> if(!mysqli_stmt_store_result($stmt)))
<i> </i> {
<i> </i> echo "Memory is leaking!";
<i> </i> }
<i> </i> if(mysqli_stmt_num_rows($stmt) == 0)
<i> </i> {
<i> </i> echo "No matching results found.";
<i> </i> }
<i> </i>}
}

function db_error(mysqli $conn)
{
error_log("DB ERROR:n" . mysqli_error($conn));
echo "&lt;p class='error&gt;Sorry! Something went wrong and has been logged. Try again later.&lt;/p&gt;";
}

?&gt;
Copy linkTweet thisAlerts:
@NogDogMay 11.2021 — I know, you refuse to learn how to use PDO...but, this is _so_ much cleaner:
[code=php]
<?php

$dsn = 'mysql:dbname=brute;host=localhost';
$user = 'root';
$password = '';
// test input
$keywords = "keyword";

try {
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$query = 'SELECT id, domain from links WHERE keywords = :keywords';
$stmt = $pdo->prepare($query);
$stmt->execute(array(':keywords' => $keywords));
$rows = 0;
while($row = $stmt->fetch()) {
$rows++;
echo "<dl><dt>Id:<dt><dd>{$row['id']}</dd><dt>Domain:</dt><dd>{$row['domain']}<dd><dl>n";
}
if($rows == 0) {
echo "No matching results found.";
}
}
catch(PDOException $e) {
error_log("DB ERROR:n".$e->getMessage());
die("<p class='error'>Sorry, there was a database error. Details have been logged.</p>");
}
catch(Exception $e) {
error_log("ERROR:n".$e->getMessage());
die("<p class='error'>Sorry, there was an unexpected error. Details have been logged.</p>");
}

[/code]
Copy linkTweet thisAlerts:
@developer_webauthorMay 18.2021 — @NogDog#1631505

You have a good memory when you remember that I refuse to learn pdo. Not only you but 10 other forums have figured out like you too in the past. Now I just stick to this forum for about 2yrs now as have been banned from others for cross posting same threads on more than one forum. Even cross posted here. Find this forum more patient. Especially mods. Lots of times expected ban here (during my harassments to folks like you to respond to my threads )but to my surprise I didn't get it. :)

Attempted pdo twice since 2016 and I just cant remember pdo syntax. For some reason I remember the messy mysqli syntax with too many () but PDO's "::" really gets to me. Irritates me. That is what puts me off. Don't understand why I have to memorise when to put "::" where. Seems like unnecessarily have to remember this symbol at certain places for nothing and waste my brain storage. The sight of "::" makes me lose my temper. Lol!
Copy linkTweet thisAlerts:
@developer_webauthorMay 18.2021 — Folks,

I was told at stackoverflow.com not to use the if() on mysqli_stmt_get_result() and mysqli_fetch_array.

Not sure about mysli_stmt_fetch().
Copy linkTweet thisAlerts:
@NogDogMay 18.2021 — The :: operator indicates that the thing on the right is a member of the class on the left. If you can't be bothered to learn OOP in PHP, then you'll never really understand why/when you'd use it (e.g. as opposed to using the -&gt; operator when you want to refer to a member of an object (a specific instance of a class)). If you are unwilling/unable to learn object-oriented programming, then you'll simply never understand large chunks of the PHP language, and will never be able to learn something like Java or Ruby which are object-oriented from the ground up. (The saying in Ruby is that "everything is an object.")
Copy linkTweet thisAlerts:
@developer_webauthorMay 21.2021 — @NogDog#1631767

I did begin at oop. They started on class right at the beginning. But then my learning came to a halt about 2 mnths ago, after a day or two oop learning as I had to work on my existing procedural assignments.

I will try getting back onto oop once my current procedural assignments are finished.

I thought "::" had only to do with pdo. Didn't know it was oop.

I look forward to Python. Nothing else. One php is a struggle for me. made a mistake choosing it over Python. Only chose it cos it was mature than the newcomer Python. I knew Python was modern, better structured, was designed for teens and the like. They teach python on America and England to teens cos they say it is easier to learn than other langs. I knew all this back in 2015 about Python being simpler to learn but I still chose php. With Python you can program web, desktop softwares (like C,C++,C#, Java, Cobol, Basic, Liberty Basic, Fortran, etc.) and (Here's the KILLER) **Mobile Apps**!

But still, I picked Php!

**Fool!**
×

Success!

Help @developer_web spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 10 SATS,
)...