user906379
user906379

Reputation: 107

Can't get SQL Update to work using PHP

I'm trying to get php to update a MySQL table using UPDATE statement but it simply won't work. Here's the code I wrote:

$add = "1";

$counter=mysql_query("SELECT * FROM frases WHERE id = '".$id."'");

while ($ntcounter=mysql_fetch_array($counter)) {    
    mysql_query("UPDATE frases SET count = '".$ntcounter[count]+$add."' WHERE id = '".$id);
}

As you can see, I am basically trying to update the SQL record to keep track of how many times a specific content ID was visited.

Thanks!

Upvotes: 0

Views: 669

Answers (3)

Michael
Michael

Reputation: 763

You don't really need two queries. You should just be able to update like this

mysql_query("UPDATE frases SET `count` = `count` + 1 WHERE id = ".$id);

Upvotes: 1

Derek
Derek

Reputation: 23238

You didn't close the single quote at the end of the update statement:

mysql_query("UPDATE frases SET count = '".$ntcounter[count]+$add."' WHERE id = '".$id."'")

Upvotes: 1

Julien Lafont
Julien Lafont

Reputation: 7877

Use an alias in your SQL query (It is not mandatory, but it makes the query much more readable.)

SELECT * as count FROM frases WHERE id = '".$id."'"

And you can now access to your variable

$ntcounter['count']

So the result :

$add = "1";

$id = (int)$id
$counter = mysql_query("SELECT * as count FROM frases WHERE id = '".$id."'");

while ($ntcounter = mysql_fetch_assoc($counter)) {    
    mysql_query("UPDATE frases SET count = '".($ntcounter['count']+$add)."' WHERE id = '".$id);
}

Upvotes: 2

Related Questions