/    Sign up×
Community /Pin to ProfileBookmark

Which INSERT INTO Should I Stick To ?

Hi,

These 3 ways of coding works.
Which one you recommend and why ?
I would prefer if you rank these 3 where best on top.
Note that, I am checking in 3 different ways if INSERTION into Mysql DB was successful or not. Spoiled for choice whcih one to use. Wish to use the one where no room for issues will arise.

1.

[code]
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.

$sql = “INSERT into users (username,email) VALUES (?,?)”;

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

if(mysqli_stmt_execute($stmt))
{
echo ‘INSERTING 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);

[/code]

2.

[code]

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.

$sql = “INSERT into users (username,email) VALUES (?,?)”;

if($stmt = mysqli_prepare($conn,$sql))
{
mysqli_stmt_bind_param($stmt,”ss”,$input_1,$input_2);
mysqli_stmt_execute($stmt);
echo ‘INSERTING 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);

[/code]

3.

[code]

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.

$sql = “INSERT into users (username,email) VALUES (?,?)”;

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

if(mysqli_stmt_affected_rows($stmt))
{
echo ‘INSERTING 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);

[/code]

to post a comment
PHP

7 Comments(s)

Copy linkTweet thisAlerts:
@novice2022authorAug 12.2022 — @sempervivum

Do you mind contributing on this thread as I waiting for an answer to finish my project ?

And on this one too:

https://forum.webdeveloper.com/d/400394-why-php-got-too-many-differnt-syntaxes-as-if-different-languages/7
Copy linkTweet thisAlerts:
@novice2022authorAug 12.2022 — @nogdog

How you do the checkings yourself ? Show me. I know it is in oop. But still.

And which one should I stick to out of the 3 from the procedural style in my op ?
Copy linkTweet thisAlerts:
@SempervivumAug 13.2022 — @novice2022#1645898

I do not mind, however there are limitations:
  • - PHP in general and database access in detail are not my strongest suits.

  • - When dealing with database access I prefer PDO.
  • Copy linkTweet thisAlerts:
    @NogDogAug 13.2022 — I'd use PDO and exception-handling. Then you just need one try { ... } block for all your database-related code, instead of a bunch of if() statements. You can probably do that with mysqli, but I don't happen to know what is required to have it throw exceptions on errors (and no real interest in figuring it out).
    [code=php]
    try {
    $pdo = new PDO($dsn, $user, $pass);
    // make all PDO errors be exceptions:
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // bunch of code here doing PDO database stuff
    // . . .
    }
    catch(PDOException $e) {
    // do whatever you want to do when a PDO command encounters an error, e.g:
    fatal_error($e, 'Sorry, there was a database error.');
    }
    catch(Exception $e) {
    // do whatever you want when something else throws an exception, e.g.:
    fatal_error($e, 'Sorry, there was an unexpected error.');
    }

    function fatal_error(Exception $e, string $msg) {
    error_log("Exception in {$e->getFile()}[{$e->getLine()}]: {$e->getMessage()}");
    die("<div class='oops'>
    <h1>Oops!<h1>
    <p>$msg</p>
    <p>Data has been logged for our developers to analyze.</p>
    </div>");
    }
    [/code]

    Today's lesson is: Don't Repeat Yourself (keep it DRY). If you're doing the same sort of thing over and over, figure out how to condense it into a single function you can call (like my example fatal_error() function), or rethink how you are writing/organizing things (e.g. using a try/catch block in this example). You end up with code that is easier to read, making it easier to debug and/or modify.

    Of course, that sort of means you need to learn programming, and not just memorize syntax. 🤷‍♂️
    Copy linkTweet thisAlerts:
    @novice2022authorAug 14.2022 — @Sempervivum#1645915

    I keep forgetting this as you told me twice before over the 1.5yrs.

    Sorry.
    Copy linkTweet thisAlerts:
    @novice2022authorAug 14.2022 — @NogDog#1645925

    Thanks.

    Thing is to keep DRY, I usually re-use or cycle an array. But then code gets messy and then I put project on hold and start over (been doing this for 2yrs now) to make things look less messy and that means it makes me repeat lines. Started over about 4 times now. But each time code gets messy and long somehow.

    But still. I will try DRY again to see if I can come-up with less code workaround. Try just one last time.
    Copy linkTweet thisAlerts:
    @novice2022authorAug 14.2022 — @NogDog

    I guess you want me to ignore the code here:

    https://forum.webdeveloper.com/d/400394-why-php-got-too-many-differnt-syntaxes-as-if-different-languages/3

    But go for the one here to keep it DRY:

    https://forum.webdeveloper.com/d/400394-why-php-got-too-many-differnt-syntaxes-as-if-different-languages/7

    Yes ?

    Better to answer there after closing this thread.

    Thanks
    ×

    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 7.21,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ,
    analytics: Fullres
    });

    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: Anonymous,
    tipped: article
    amount: 1000 SATS,

    tipper: Anonymous,
    tipped: article
    amount: 1000 SATS,

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