/    Sign up×
Community /Pin to ProfileBookmark

How To Check For Mysql Row Updates Using Prepared Statements ?

Hiya,

This questions is on Sql and Php Prepared Statements.
How would you check whether the SQL managed to update a row or not ? Which one of the following lines would you add the IF condition to ?

1.
““mysqli_stmt_execute()““

2.
““ mysqli_stmt_affected_rows()““

Here are my experiment findings.
A).

““mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

$conn = mysqli_connect(“localhost”,”root”,””,”buzz”); //mysqli_connect(“server”,”user”,”password”,”db”);

$input_1 = ‘magi’; //username.
$input_2 = ‘[email protected]’; //email.
$input_3 = ‘0’; //id.

$sql = “UPDATE users SET username=?,email=? WHERE id=?”;

$stmt = mysqli_prepare($conn,$sql);
mysqli_stmt_bind_param($stmt,”sss”,$input_1,$input_2,$input_3);
mysqli_stmt_execute($stmt);
echo ‘UPDATED SUCESSFULLY: ‘ .mysqli_stmt_affected_rows($stmt);

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

B.

““mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

$conn = mysqli_connect(“localhost”,”root”,””,”buzz”); //mysqli_connect(“server”,”user”,”password”,”db”);

$input_1 = ‘magi’; //username.
$input_2 = ‘[email protected]’; //email.
$input_3 = ‘0’; //id.

$sql = “UPDATE users SET username=?,email=? WHERE id=?”;

if($stmt = mysqli_prepare($conn,$sql))
{
mysqli_stmt_bind_param($stmt,”sss”,$input_1,$input_2,$input_3);
mysqli_stmt_execute($stmt);
echo ‘UPDATED SUCESSFULLY: ‘ .mysqli_stmt_affected_rows($stmt);
}
else
{
echo ‘Mysqli Error: ‘ .mysqli_error();
echo ‘<br>’;
echo ‘Mysqli Error No: ‘ .mysqli_errno();
}

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

C.

““mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

$conn = mysqli_connect(“localhost”,”root”,””,”buzz”); //mysqli_connect(“server”,”user”,”password”,”db”);

$input_1 = ‘magi’; //username.
$input_2 = ‘[email protected]’; //email.
$input_3 = ‘0’; //id.

$sql = “UPDATE users SET username=?,email=? WHERE id=?”;

if($stmt = mysqli_prepare($conn,$sql))
{
mysqli_stmt_bind_param($stmt,”sss”,$input_1,$input_2,$input_3);

if(mysqli_stmt_execute($stmt))
{
echo ‘UPDATED SUCESSFULLY: ‘ .mysqli_stmt_affected_rows($stmt);
}
else
{
echo ‘Mysqli Error: ‘ .mysqli_error();
echo ‘<br>’;
echo ‘Mysqli Error No: ‘ .mysqli_errno();
echo ‘<br>’;
die(‘Failed to INSERT!’);
}
}
else
{
echo ‘Mysqli Error: ‘ .mysqli_error();
echo ‘<br>’;
echo ‘Mysqli Error No: ‘ .mysqli_errno();
}

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

D.

““mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

$conn = mysqli_connect(“localhost”,”root”,””,”buzz”); //mysqli_connect(“server”,”user”,”password”,”db”);

$input_1 = ‘magi’; //username.
$input_2 = ‘[email protected]’; //email.
$input_3 = ‘0’; //id.

$sql = “UPDATE users SET username=?,email=? WHERE id=?”;

if($stmt = mysqli_prepare($conn,$sql))
{
mysqli_stmt_bind_param($stmt,”sss”,$input_1,$input_2,$input_3);
mysqli_stmt_execute($stmt);

if(mysqli_stmt_affected_rows($stmt))
{
echo ‘UPDATED SUCESSFULLY: ‘ .mysqli_stmt_affected_rows($stmt);
}
else
{
echo ‘Mysqli Error: ‘ .mysqli_error();
echo ‘<br>’;
echo ‘Mysqli Error No: ‘ .mysqli_errno();
echo ‘<br>’;
die(‘Failed to INSERT!’);
}
}
else
{
echo ‘Mysqli Error: ‘ .mysqli_error();
echo ‘<br>’;
echo ‘Mysqli Error No: ‘ .mysqli_errno();
}

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

““

They all work fine. Still, does not mean they are proper way of coding. So need your inputs!
Checking above, are there any that are unnecessarily going through the IF condition ? (Is pointless). If so, then why ?

Thank you for your aids!

to post a comment
PHP

17 Comments(s)

Copy linkTweet thisAlerts:
@ginerjmFeb 06.2023 — I would test the execution of the first statement in your post and wouldn't have bothered to write all of the tests you are wont to write all the time. That's the way things are done all the time.
Copy linkTweet thisAlerts:
@novice2022authorFeb 06.2023 — @ginerjm#1650442

Sorry. Which one 1) or A) you talking about ? How would you check without the IF condition ?
Copy linkTweet thisAlerts:
@NogDogFeb 06.2023 — As they are 2 different types of errors (bad query versus valid query that affects 0 rows), they should be separately checked. I strongly suggest catching the "bad query" type of problem as an exception. That way, you don't have to wrap every mysqli_*() you make within an if block.
[code=php]
// turn on mysqli exceptions:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$conn = mysqli_connect("localhost","root","","buzz");
// other stuff...then...
// do the query, then right after it:
if(mysqli_stmt_affected_rows($stmt) == 0) {
// No actual coding/mysql error, just probably no match found for the user ID,
// so maybe just display an error to the user about that?
}
// more other stuff...
} catch (mysqli_sql_exception $e) {
error_log('MySQLi exception: ' . $e->__toString());
// whatever else you want to do if there is a DB error

} catch (Exception $e) {
error_log('General exception: ' . $e->__toString());
// whatever else you want to do if some other exception is thrown
}
[/code]
Copy linkTweet thisAlerts:
@novice2022authorFeb 06.2023 — @NogDog#1650444

Very good idea! Thanks!

But I never really did manage to learn the messy suntax of the try-catchall stuff as I half understand it not.

You know of any good layman tutorial that goes into good indepth ? The manual is not a proper one for laymen.
Copy linkTweet thisAlerts:
@NogDogFeb 06.2023 — > @novice2022#1650447 You know of any good layman tutorial...

Nope.

> @novice2022#1650447 the messy suntax of the try-catchall stuff

Actually, I consider it a way to clean up my code, making it less messy. With it, you can change this pseudo code...
[code=text]
do something
if(oops) {
handle that error
} else {
do the next thing
if(another oops) {
handle this error
} else {
do yet another thing
if(yet another error) {
handle yet another error
}
}
}
[/code]

...to...
[code=text]
enable exceptions
try {
do something
do the next thing
do yet another thing
} catch(Exception $e) {
log exception info of interest
display alert to user that something went wrong
}
[/code]
Copy linkTweet thisAlerts:
@novice2022authorFeb 06.2023 — @NogDog

If this following line shows: 0

Then, does not that mean no records got updated ?

echo 'UPDATED SUCESSFULLY: ' .mysqli_stmt_affected_rows($stmt);

And if it shows 1, then does not it means 1 row got updated ?

Look at my A) code above and answer.

I ask because someone told me the following and confused me:

**"if 0 rows got affected, it means update WAS successful!"**

Thanks!
Copy linkTweet thisAlerts:
@novice2022authorFeb 06.2023 — @sempervivum

Care to chime in ?

I think all the codes shown above in my op are not perfect. Especially, C) I suspect is not right and D is downright wrong way of coding.

And so fixed it to the following. I need your opinion on it now.**

````mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

$conn = mysqli_connect("localhost","root","","buzz"); //mysqli_connect("server","user","password","db");

$input_1 = 'magi'; //username.
$input_2 = '[email protected]'; //email.
$input_3 = '0';

$sql = "UPDATE users SET username=?,email=? WHERE id=?";

if($stmt = mysqli_prepare($conn,$sql))
{
mysqli_stmt_bind_param($stmt,"sss",$input_1,$input_2,$input_3);
mysqli_stmt_execute($stmt);

if(mysqli_stmt_affected_rows($stmt)>0)
{
echo 'UPDATED SUCESSFULLY: ' .mysqli_stmt_affected_rows($stmt);
}
else
{
echo 'Mysqli Error: ' .mysqli_error();
echo '<br>';
echo 'Mysqli Error No: ' .mysqli_errno();
echo '<br>';
die('Failed to UPDATE!');
}
}
else
{
echo 'Mysqli Error: ' .mysqli_error();
echo '<br>';
echo 'Mysqli Error No: ' .mysqli_errno();
}

mysqli_stmt_close($stmt);
mysqli_close($conn);
Copy linkTweet thisAlerts:
@NogDogFeb 06.2023 — > @novice2022#1650450 if 0 rows got affected, it means update WAS successful!

There are 2 different sorts of "success" being talked about here. There is whether or not the query was processed by the database and returned a result without any errors. Then there is the question of whether or not it actually did what you expected it to do: update a row in the database. If the mysqli_stmt_execute() does not throw an error nor return false, then the first part of the equation was a success: the application talked to the database and the database processed the query without an error.

If mysqli_stmt_affected_rows() returns 0 but you expected it to update 1 row, then there is a different sort of "error" -- maybe a logic error, maybe a failure to validate user input, or something else that caused your code to send a query to the database which was _valid_, but for which it could find no matching row in the database to update. (Depending on what you are doing, a value greater than 1 might also be an "error" in this vein.)
Copy linkTweet thisAlerts:
@novice2022authorFeb 10.2023 — @NogDog#1650453

Thanks NogDog, I understand things better tonight! Cheers!

Sorry for late response as do not always manage to sit infront of pc everyday.

I used to wrongfully assume that if zero rows got affected then there must be error somewhere. Forgot to take into account that there could be no matches in the rows. Now that is clear.

But still, after reading your answer, a few questions have arisen in my mind. Kindly, clear my confusions.

First of all, let me see if I understood you correctly or not. After reading your answers, I drew-up the following.

Q1.

Glancing at following code, can you see if I understood you ok or not ?

Code E).


mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

$conn = mysqli_connect("localhost","root","","buzz"); //mysqli_connect("server","user","password","db");

$input_1 = 'mogambo'; //username.
$input_2 = '[email protected]'; //email.
$input_3 = '0'; //id.

$sql = "UPDATE users SET username=?,email=? WHERE id=?";

if(!$stmt = mysqli_prepare($conn,$sql))
{
echo 'Mysqli Error: ' .mysqli_stmt_error();
echo '<br>';
echo 'Mysqli Error No: ' .mysqli_stmt_errno();
}
else
{
mysqli_stmt_bind_param($stmt,"sss",$input_1,$input_2,$input_3);

if(!mysqli_stmt_execute($stmt))
{
echo 'No Row was UPDATED as SQL syntax Error!';
echo 'Mysqli Statement Error: ' .mysqli_error();
echo '<br>';
echo 'Mysqli Statement Error No: ' .mysqli_errno();
}

if(mysqli_stmt_affected_rows($stmt)==-1) //This means only one thing: SQL syntax error.
{
echo 'No Row UPDATE as SQL syntax Error!';
echo 'Mysqli Statement Error: ' .mysqli_error();
echo '<br>';
echo 'Mysqli Statement Error No: ' .mysqli_errno();
}
elseif(mysqli_stmt_affected_rows($stmt)==0)
{
echo 'No Row UPDATE as no Row MATCH!: ' .mysqli_stmt_affected_rows($stmt);
}
else
{
echo 'UPDATED SUCESSFULLY number of ROWS: ' .mysqli_stmt_affected_rows($stmt);
}
}


mysqli_stmt_close($stmt);
mysqli_close($conn);
Copy linkTweet thisAlerts:
@novice2022authorFeb 10.2023 — @NogDog

Q2.

Is it true that on the above code E), I should never write both of these following IFs but either one ? If so, then which one I should stick to and why that one over the other and what is wrong with the other ? I mean, what weakness it would output if nothing really wrong with the code ?

Code E:

1

if(!mysqli_stmt_execute($stmt))
{
echo 'No Row was UPDATED as SQL syntax Error!';
echo 'Mysqli Statement Error: ' .mysqli_error();
echo '<br>';
echo 'Mysqli Statement Error No: ' .mysqli_errno();
}


2.

if(mysqli_stmt_affected_rows($stmt)==-1) //This means only one thing: SQL syntax error.
{
echo 'No Row UPDATE as SQL syntax Error!';
echo 'Mysqli Statement Error: ' .mysqli_error();
echo '<br>';
echo 'Mysqli Statement Error No: ' .mysqli_errno();
}


The code is from:

https://forum.webdeveloper.com/d/402887-how-to-check-for-mysql-row-updates-using-prepared-statements/10
Copy linkTweet thisAlerts:
@novice2022authorFeb 10.2023 — @sempervivum

What is your opinion ?
Copy linkTweet thisAlerts:
@annerobertFeb 13.2023 — We have the best affordable hand bags for you. You can gift these [url=https://ohmyhandbags.com/product-category/hand-bags/]replica handbags[/url] for your friend and anybody. This hand bags is quite friendly to ware.
Copy linkTweet thisAlerts:
@ginerjmFeb 13.2023 — Such an idiot. And the word is "wear".
Copy linkTweet thisAlerts:
@ginerjmFeb 13.2023 — My last post doesn't make any sense since someone removed the offending post from the person I was denigrating.

Should have dropped mine as well.
Copy linkTweet thisAlerts:
@novice2022authorFeb 13.2023 — @NogDog

Do you mind answering my previous question as I am very curious to know the answer ?

Where is that tutorial where you learnt about the try-catchall-stuff ? I actually need a layman's guide in procedural style. I do not understand oop lines. That is why I can never learn on this try-catchall cos they always have tutorials in oop writing oop lines which I do not understand always quit and try avoiding that subject when it gets broughtup by any programmer. CONFESSION: That was the mystery behind why I ignore try-catchall code given to me by programmers for 5yrs or so now.
Copy linkTweet thisAlerts:
@tanvirabcitFeb 14.2023 — With that said. I would, personally, never charge for a newsletter especially if I am going to promote products or services that would generate affiliate commissions for myself. You might be better off creating a membership section of your website. [Slot Hoki ]( https://www.soft-go.com/

)
Copy linkTweet thisAlerts:
@sophiaellaFeb 21.2023 — Thanks for this best post. I am working on my [Painting Services in Dubai](https://ssbcontracting.com/services/painting-contracting/). We are transforming you homes with best painting skills and amazing prices ranges.
×

Success!

Help @novice2022 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 4.23,
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: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

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