if Row1 = Value 1, Update other rows

后端 未结 2 802
野趣味
野趣味 2021-01-28 12:53

I have a little php script that goes to mySql database.

I want to look, before i insert a new record in the database, if the number (value1) equals a record in the datab

2条回答
  •  清酒与你
    2021-01-28 13:12

    Why go through the trouble of counting the rows found for a particular phone number? Just check for $data->phone_number !== null and then execute an update query blindly

    $stmt = $pdo->prepare('UPDATE table SET longitude = :longitude, latitude = :latitude, timestamp = :timestap WHERE id = :id');
    if ($stmt->execute(array(':longitude' => $data->longitude,':latitude' => $data->latitude,':timestamp' => $data->timestamp,':id' => $data->phone_number)))
    {
        echo 'Updated';
    }
    else
    {
        echo 'Couldn\'t update';
    }
    

    Or better yet: set $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); and update within a try-catch block, so you can check why the update query failed and respond accordingly. If your db engine supports it, you can use $pdo->rollBack(); when an update has occurred when it shouldn't, too:

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    try
    {
        $stmt = $pdo->prepare('UPDATE table SET longitude = :longitude, latitude = :latitude, timestamp = :timestap WHERE id = :id');
        $stmt->execute(array(':longitude' => $data->longitude,':latitude' => $data->latitude,':timestamp' => $data->timestamp,':id' => $data->phone_number));
    }
    catch(PDOException $e)
    {
        $pdo->rollBack();//undo any changes
        echo $e->getMessage();
    }
    

提交回复
热议问题