Kern Elliott
Kern Elliott

Reputation: 1659

Can't update then insert in SQL

I am trying to write PHP code to update a value once it exist, and if it doesn't then insert it. Part of this function works which is the insert part however the update doesn't seem to work my code is below:

<?php
$id = $_GET['Track'];
$user = $_GET['User'];
$rating = $_GET['Rating'];
include("connect.php");
$query = "UPDATE `rating` SET `rating` = '$rating' WHERE track_id = '$id' AND user_id = '$user' AND rating_set=NOW()";
$sth = $dbc->query($query);
$rows = $sth->rowCount();  

if ($rows == 0) {
$query = "INSERT INTO rating values ('$id','$rating','$user',NOW())";
$results = $dbc->query($query); 
$rows = $results->rowCount(); 
}

/* output in necessary format */

header('Content-type: application/json; charset=utf-8');
echo $_GET['onJSONPLoad'];
echo "(" . json_encode($rows) . ")";


$dbc = null;
?>

Upvotes: 1

Views: 125

Answers (2)

juergen d
juergen d

Reputation: 204756

Your update query can't work.

You are only updating data where rating_set is exactly NOW(). That will most likely not fit on any data record. You probably only want to use the date part.

Upvotes: 2

pinkal vansia
pinkal vansia

Reputation: 10300

you are using NOW() in update query, which gives current time. Which will never be same!!! try removing '....AND rating_set=NOW()' from your update query.

Upvotes: 0

Related Questions