简体   繁体   中英

PDO - check if row was updated?

Other people have asked this question, but mine is a little more specific.

I have this query:

$sql = "UPDATE table SET option=? WHERE number=?";
$q = $conn->prepare($sql);
$q->execute(array($option, $number));
$q->setFetchMode(PDO::FETCH_BOTH);

echo $q->rowCount();

If the WHERE number already exists and the SET option is same, $q->rowCount() equals 0

If the WHERE number doesnt exist and the row does not update, $q->rowCount() equals 0

How can I distinguish between these non-updates?

On recent PHP versions, it's controlled by the PDO::MYSQL_ATTR_FOUND_ROWS attribute. When set to true , according to the doc , the effect is:

 Return the number of found (matched) rows, not the number of changed rows.

You can try using REPLACE which work's like insert but if the row already exists its first deleted and then inserted. This has overwork from mysql side

Will be better check before if exists? I use a common function for this in my miniclass for manage PDO, but i dont know if is the best solution because make one query more...

function checkExistsInDatabase($id, $table, $where = null){

    // Connect
    $Database = Database::connect();

    // Query
    $sql = "SELECT id 
            FROM $table
            WHERE id = :id $where
            LIMIT 1";
    $params = array(
                ':id' => array(
                    'value' => $id,
                    'type' => 'int'
                )
              );
    $q = $Database->query($sql, $params);

    // Ha encontrado algo?
    $resultados = $Database->fetchArray($q);
    if(count($resultados) === 1){
        return true;
    }else{
        return false;
    }

}

Add this:

$db = new PDO($dsn, $username, $password, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));

to the first "try {" part of your databasefunctions.php file

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