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
You didn't mentioned the phone number field, so I assumed is phone_number
:
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
if (isset($_REQUEST['data'])){
$data = json_decode($_REQUEST['data']);
if($data->phonenumber){
$stmt = $db->prepare("SELECT `id` FROM `test` where `id`=:phone_number");
$stmt->execute(array(':phone_number' => $data->phonenumber));
$row_count = $stmt->rowCount();
if($row_count && ($data->phonenumber != '')){
$stmt = $db->prepare("UPDATE `test` SET `longitude`=:longitude, `latitude`=:latitude, `timestamp`=:timestamp WHERE `id`=:phone_number");
$stmt->execute(array(':longitude' => $data->longitude,':latitude' => $data->latitude,':timestamp' => $data->timestamp,':phone_number' => $data->phonenumber));
}
}
}
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();
}