简体   繁体   中英

Update single field in base64 in whole table with PDO

I have a mySQL DB defined with one table that has lots of fields.

Is there an all in one PDO statement I could execute to do the following :

I want to base64_encode one field (field called cstat) in every single record in the DB.

Any help would be much appreciated.

UPDATE :

Thanks to TheEwook getting me on the right track and some further searching I finally solved it like this (I have a unique autoincrement field called record_id) :

  $sth = $pdo->query("SELECT * FROM myTable");
  $sth->setFetchMode(PDO::FETCH_ASSOC);

    while($row = $sth->fetch()) {

        $cstat = base64_encode($row['cstat']);

        $sql="UPDATE myTable SET cstat = :cstat WHERE record_id = :record_id";
        $stmt = $pdo->prepare($sql);                                 
        $stmt->bindParam(':cstat', $cstat, PDO::PARAM_STR);
        $stmt->bindParam(':record_id', $row['record_id'], PDO::PARAM_INT);
        $stmt->execute();

    }

A simple update query will suffice

$sth = $dbh->prepare('UPDATE myTable SET cstat = TO_BASE64(cstat)');
$sth->execute();

Or if you are using a mySQL version prior to 5.6.1

$sth = $dbh->query("SELECT * FROM myTable");
$sth->setFetchMode(PDO::FETCH_ASSOC);

while($row = $sth->fetch()) {
    $cstat = base64_encode($row['cstat']);
    $sth2 = $dbh->prepare('UPDATE myTable SET cstat = ?');
    $sth2->execute(array($cstat));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM