Klapsius
Klapsius

Reputation: 3359

sql server update when WHERE exist

I have sql + php query and i need inform user when update fail exmpl:

$sql = "UPDATE db SET
date = GetDate(),
...
...
...

WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2' 
";
sqlsrv_query( $con, $sql);

And now if php variables values not 100% match values in db update fails but users cant see that. He can check records and try again. I would like inform him when query update nothing.

Upvotes: 2

Views: 91

Answers (2)

Andomar
Andomar

Reputation: 238176

Like GOB commented, you can use the PHP sqlsrv_rows_affected function to retrieve the number of affected rows. For example:

$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_rows_affected( $stmt );
if ($row_count === false)
   echo "Error in retrieving row count.";
else
   echo $row_count;

Upvotes: 1

rack_nilesh
rack_nilesh

Reputation: 553

Before directly executing update query,check whether condition in update query exists or not. This can be done by selecting count of that condition.

Try below code:

$sql = "select count(*) as count from db WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2' ";
while($row = mysqli_fetch_array($sql))
{
    $count = $row['count'];
}

if($count == 0)
{
   echo 'update will fail';
}
else
{
$sql = "UPDATE db SET
date = GetDate(),
...
...
...

WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2' 
";
}

Upvotes: 1

Related Questions