1

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;
?>
4
  • insert replae/insert ... on duplicate key update Commented Aug 10, 2013 at 16:18
  • What data type has rating_set? Commented Aug 10, 2013 at 16:22
  • rating_set most probably is the fault here because you try to match it by current time, im pretty sure inserted time differs from current time so you never getting a match. Commented Aug 10, 2013 at 16:23
  • Are you trying to do this: $query = "UPDATE rating SET rating = '$rating', rating_set=NOW() WHERE track_id = '$id' AND user_id = '$user'"; Commented Aug 10, 2013 at 16:29

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

you are not forced to, if you use all of them
how can I then save the time when the query has been updated?
@KernElliott: You should use NOW() to set the data, but you put it in the where clause to filter the data you want to update.
0

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.

2 Comments

how can I then save the time when the query has been updated?
In your original update query you are only updating 'rating' field. You are not updating 'rating_set', instead you are using it in 'where' clause. you should write your update query like..... "UPDATE rating SET rating = '$rating', rating_set = NOW() WHERE track_id = '$id' AND user_id = '$user'"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.