Jump to content

Recommended Posts

Programmers,

Sql and Php Prepared Statements.
How do you yourself would check whether the SQL managed to update a row or not if you were using mysqli and prepared statements ?

1).

	mysqli_stmt_execute()
	

 

2).

	mysqli_stmt_affected_rows()
	

On which one of the above lines would you add the IF condition to ?

 

 

Link to comment
https://forums.phpfreaks.com/topic/316240-got-to-confirm-db-record-update/
Share on other sites

Web Gurus,

Here are the codes I drew-up many months ago.

Glancing over them, can you spot any that is unnecessarily going through the IF condition ? (Is pointless). If so, then which one and why it is pointless over there ?

Do not worry, on my website I will not use 'root' as user.

1.

	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 = 'admin@magi.com'; //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);
	

2.

	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 = 'admin@magi.com'; //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);
	

 

3.

	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 = 'admin@magi.com'; //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);
	

 

4.

	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 = 'admin@magi.com'; //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);
	

I know you do not like this part on any of the above on their ELSEs:

	echo 'Mysqli Error: ' .mysqli_error();
echo '<br>';
echo 'Mysqli Error No: ' .mysqli_errno();
	

Bear in mind, these samples are DEV mode.

I prefer you show me in shortest & minimalist way to write EXCEPTION handling stuff that everyone keeps talking about. Tutorials explain something but leave out explaining other necessary things and confuse me. Let us see how well simplified you can teach.

 

Thanks!

Edited by TheStudent2023

You really don't need if statement or try/catch blocks and that is something a human pointed me out on another forum. I believe he's also on this forum as well.

For example I have this function(method in OOP)

        $sql = 'SELECT * FROM gallery WHERE page =:page AND category =:category ORDER BY id DESC, date_added DESC LIMIT :perPage OFFSET :blogOffset';
        $stmt = $this->pdo->prepare($sql); // Prepare the query:
        $stmt->execute(['page' => $page, 'perPage' => $perPage, 'category' => $category, 'blogOffset' => $offset]); // Execute the query with the supplied data:
        return $stmt->fetchAll(PDO::FETCH_ASSOC);

No try/catch block, if statement as any errors are caught by exception.

Something to read up on is this

// Register the exception handler method
set_exception_handler([$errorHandler, 'handleException']);

here's a good link on it https://www.php.net/manual/en/function.set-exception-handler.php

For debugging
 

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

and a good link in using PDO as in my opinion it is easier to implement and more versatile - https://phpdelusions.net/pdo
 

Even the website writes "

Although there are several error handling modes in PDO, the only proper one is PDO::ERRMODE_EXCEPTION. So, one ought to always set it this way, either by adding this line after creation of PDO instance,

$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

or as a connection option, as demonstrated in the example above. And this is all you need for the basic error reporting"

Edited by Strider64
  • Like 1

You are starting to resemble a forum user who makes it a very annoying habit to post samples of code to find out what people think of his thinking and which one is better.  Someone I blocked a long time ago.

If you have a problem then show the problem code and tell us what is not happening and whatever error message you are getting.  Why would you post old code that worked for you a long time ago (or did it not work and you kept it anway?) and ask about it?

22 hours ago, Strider64 said:

You really don't need if statement or try/catch blocks and that is something a human pointed me out on another forum. I believe he's also on this forum as well.

For example I have this function(method in OOP)

        $sql = 'SELECT * FROM gallery WHERE page =:page AND category =:category ORDER BY id DESC, date_added DESC LIMIT :perPage OFFSET :blogOffset';
        $stmt = $this->pdo->prepare($sql); // Prepare the query:
        $stmt->execute(['page' => $page, 'perPage' => $perPage, 'category' => $category, 'blogOffset' => $offset]); // Execute the query with the supplied data:
        return $stmt->fetchAll(PDO::FETCH_ASSOC);

No try/catch block, if statement as any errors are caught by exception.

Something to read up on is this

// Register the exception handler method
set_exception_handler([$errorHandler, 'handleException']);

here's a good link on it https://www.php.net/manual/en/function.set-exception-handler.php

For debugging
 

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

and a good link in using PDO as in my opinion it is easier to implement and more versatile - https://phpdelusions.net/pdo
 

Even the website writes "

Although there are several error handling modes in PDO, the only proper one is PDO::ERRMODE_EXCEPTION. So, one ought to always set it this way, either by adding this line after creation of PDO instance,

$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

or as a connection option, as demonstrated in the example above. And this is all you need for the basic error reporting"

"a human ...". You talk as if you not human. Are you CharGPT ? Lol!

@mac_gyver told me not include this:

ini_set('display_startup_errors', 1);

But did not reply when I asked him to elaborate why I should not add it.

https://forums.phpfreaks.com/topic/316225-pagination-1-mysqli_stmtm_store_result-query/#comment-1607916

Edited by TheStudent2023

  

22 hours ago, ginerjm said:

You are starting to resemble a forum user who makes it a very annoying habit to post samples of code to find out what people think of his thinking and which one is better.  Someone I blocked a long time ago.

If you have a problem then show the problem code and tell us what is not happening and whatever error message you are getting.  Why would you post old code that worked for you a long time ago (or did it not work and you kept it anway?) and ask about it?

@ginerjm

Yeah, it was me who you probably blocked about 2yrs ago. Told me not to tag you too.

On many other forums you were helpful at first but at the end were downright rude, short tempered. going ballistic now and then. Most of the replies you gave on my threads were RTFM. At the end I started hating you for your tantrums but never told you so because I am middle aged and no kiddo. No other user behaved like a short circuit, like you did. And you probably got Requinix to ban me here. Talking about 2yrs back when I was using another Username.

3-4yrs back, Requinix also banned me from here.  That time, was also using another Username. He banned me because Benanamen went around forums asking mods to ban me simply because I asked the same questions on many forums (10-20)  to see what programmers from different walks of life answered. i liked getting different flavoured answers. At the end, most programmers did not care that I asked the same questions on many forums and were still willing to help and answering my questions. I guess they are matured people. And, Benanamen was getting jealous & frustrated to that. That programmers were still answering my threads. At the end, he skulkingly resorted to pester mods to ban me. I got banned from most forums due to so-called "cross posting". No thanks to HIM.

Kicken was always on my good books. Always polite, even though I always pestered or harassed him tagging him now and then to put attention to my posts. Still do. Barand answered me now and then too in the past. I had forgotten about him too. Occasinally he answers me this time round.

Mac_gyver, I could never get his attentions 2yrs back and failing this time too. He always answers my threads where I ask for feed-back. But never responds to threads where I show code & errors. he acts mostly like a code feed-back giver.

Requinix was helpful 2yrs back. Responded to my threads most of the time. And 3-4yrs back, he was very helpful.

So originally, I signed up to this forum about 4yrs back. A yr later or so, Requinix banned me. Then, 2yrs ago, I returned back with another Username. And Requinix banned me again.

Then, I only concentrated on webdevelopers.com forum for the past 2yrs since I was banned from the other forums, no thanks to Benanamen and maybe also you. Since webdevelopers.com is no longer in operation for a month now and I need  answers. I returned back to this forum with another username and also returned back to sitepoints.com with another username. Missed this forum and sitepoints.com for 2yrs. So, I returned back to both a month ago. Mod Gandalf over there always recognises me, no matter how many different usernames I use when returning back to them. In the past 2yrs, returned back to them 2-4 times with different Usernames and each time got caught. Banned me each time. Probably traces my mac address. He had a hard time banning me this time (when I returned there a month ago or so. Returned the same time I returned back here). Because when he banned my username, I then logged into the forum using gmail and opened threads and got all my answers. He had a hard time to ban me when I do not login using a username but login using gmail. For some reason, they fixed this loophole and for a wk now I am unable to open threads there.

But, while I was away from this forum and all others, including sitepoint.com, for 2yrs and was active at webdevelopers.com forum, I forgot about good old Kicken. When I returned back to this forum after 2yrs and he started responding to my threads, I remembered him again. I am no longer at webdevelopers.com because I think that forum is either sold or down. But you would know better because you were there too. Over there, you was a bit haughty with me but not downright rude like you were 2yrs back over here or at some other forum.

But, I get the feeling, if Benanamen catches up with me again then he will or maybe you will try putting Kicken off from answering my posts and probably would get Requinix or mac_gyver ban me again. I know I am risking a ban by confessing I am a banned person here. Actually, I am currently at another forum too but I am not naming them here. I used to get good responses there for about 6 mnths approx now but now that forum has gone quiet. Not sure, if you were over there or not. But, I do remember you were at webdevelopers.com. Good old Mod NogDog, I always used to tag and pester, more than I pester Kicken here. And he always was helpful. At the end, he gave less responses. Probably got tired of me tagging him nearly everyday. But he was not rude, though. I guess he is a matured person like Kicken here.

Anyway, this time, after I returned about 2 yrs later. I find you very calm and patient and responsive, even though not that helpful as some of the others and was beginning to like you. Whether I still continue to like you or no, will be based on your attitude, behaviour. If you start giving no proper response other than writing RTFM, then you will get on my bad books. If this Username stops operating from tonight, then it means Requinix or Mac_gyver banned me again. But, I can always return back with a different username, email and mach address. And I am good at disguising my writing style. But, I hope I won't get banned. Mac_gyver might fee frustrated that, he spent time & effort giving feed-back to someone he or Requinix banned 2yrs back or 4yrs back. I got banned twice before. Not sure who banned me the first time. Mac_Gyver or Requinix. Not sure which of them banned me the 2nd time too. But it was either of them on both occassions.

Now, you have a serious question. Why am I getting you fine folks to review some old code. Well, you see, I learn many different ways of coding to achieve the same purpose. And then experiment which gives better results. Like faster responses. I write a piece of code, then derive more out of it writing many versions in different ways. Then experiment, play, fiddle, test, etc with them. Procrastinate. At the end, I harass the pros to choose which version to stick to and give their reasons why they chose that version over the others. Like I am doing now in my op. It is my habit to do so.

Oh btw, this is my habit. I open threads. See who responses. Start liking them. And then whenever I open more threads on other days, I expect the same pros to respond. When i get no response, I start tagging them. Sometimes, I open threads and do not wait but start tagging them, if I see they not complaining. You started complaining 2yrs back and so bit by bit I stopped tagging you to stay on your good books. As for RTFM, I do not know how to read the manual syntaxes. That is why manual no use to me unless there are code examples that I managed to understand. Now, if you teach me how to read & understand the manual's function syntaxes then I should be able to stick to the manual from now on. Your choice.

PS - Do you remember uniqueideaman username ? That was my original username on many forums back in 2017. I think it got banned on all forums (approx 10, no thanks to that Benanamen) around 2020 probably. That uniqueideaman was afamous username.All users in all forums liked me back then. No one really complained but Benanamen. resulting in my ban. Frankly, I can't remember which usernames I used ion this forum apart from the current one and uniqueideaman. Try goggling for uniqueideaman username and see what you get.

So yes, I started learning php in feb 2017 and still am at procedural programming and mysqli and prepared statements. Even though promied programmers on many forums over the yrs, I will migrate to pdo, I still have not. I just hate the syntax. All that ":::" stuff. Does not sink into my head. As forpdodelusions. com. Read it few yrs back, probably 2-5yrs. Read it again about 3mnths ago. But I easily forget what I learnt on it. Hence, stick to what I can remember and that is mysqli_ and prepared statements and procedural programming. Attempted learning oop twice. A yr ago. And probably 3yrs ago. But I just do not understand what is an "object". Confuses me. Someone explained here what it is and I grasped little bit, this time. But, I am not gonna get into oop in php. Once my current projects are complete, I will jump to Python which I hear is easier to learn as they teach it to 12-13yr olds in UK & USA. So, should seem easy to a nearly late 40's guy. Guessing you in your late 20's or early 30's, if not late teens.

So what have I been doing with php for the past 6yrs ? Google for uniqueideaman username and findout. Basically, been busy to learn how to build html forms and submit data to db and query db and present results in pagination format. Build membership/account pages like reg, login, logout, search page, etc. That is all.

Anyway, Ginerjm, thanks for all your time, effort & helps.

49 minutes ago, TheStudent2023 said:

3-4yrs back, Requinix also banned me from here.

Thanks for admitting you're phpsane because I couldn't prove it.

If you remember why you were blocked then you should be able to avoid repeating those circumstances. Walk carefully because you're on very thin ice.

@requinix

 

Can you delete your post because it is obstructing me from editing my previous post. I had typos on my previous post. Edited it, added some more sentences and now it says I cannot edit the post. Post not getting edited/updated.

Or, best you delete my previous post and I will post new the edit.

Edited by TheStudent2023
Guest
This topic is now closed to further replies.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.