user3196424
user3196424

Reputation: 537

Update multiple rows Mysql Php

Been trying to figure this out for too long, here is my code

else if(isset($_POST['mytrigger1']))
{
$title1 = ($_POST['titleHOME']);
$title2 = ($_POST['titleLEARN']);
$title3 = ($_POST['titleVTOUR']);
$title4 = ($_POST['titleTRIVIA']);
$title5 = ($_POST['titleALBUMS']);
$title6 = ($_POST['titleFAQS']);

$stmt = $mysqli->prepare("UPDATE  page_title set PAGETITLE = 'title1' where PAGENAME='HOME',PAGETITLE = 'title2' where PAGENAME='LEARN'");
$stmt->execute();

}

I want to update multiple rows with multiple where clauses.

Upvotes: 0

Views: 286

Answers (1)

mpyw
mpyw

Reputation: 5754

At the setout, you should call

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

This enables you don't have to check any return values, just put try { ... } catch { ... } blocks. And do not repeat preparing same statements, reuse it.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {

    $mysqli = new mysqli(...);

    if (...) {

       ...

    } else if (isset($_POST['mytrigger1'])) {

        $stmt = $mysqli->prepare("UPDATE page_title set PAGETITLE = ? where PAGENAME = ?");
        foreach ($_POST as $k => $v) {
            if (!is_string($v) || strpos($k, 'title') !== 0) {
                continue;
            }
            $stmt->bind_param('ss', $v, substr($k, 5));
            $stmt->execute();
        }

    }

    ....

} catch (mysqli_sql_exception $e) {

    echo $e->getMessge();

}

Upvotes: 3

Related Questions