Kasper Niemann
Kasper Niemann

Reputation: 11

MySQL won't update if content is changed

I got a PHP and MySQL problem, when I update the headline I got no problem. But when updating while having changed the content it won't update at all.

Any idea to what's going wrong.

$query = mysql_query("UPDATE about SET headline='$headline' WHERE content='$content'") 
or die(mysql_error());

$query = mysql_query("SELECT * FROM about ORDER BY id DESC");
while ($row = mysql_fetch_assoc($query))
{
   $id = $row['id'];
   $headline = $row['headline'];
   $content = $row['content'];

   header("location: ../");
}

I'm coding in PHP and using and MySQL server.

I would prefer a solution that only calls the database once when updating.

Upvotes: 1

Views: 303

Answers (1)

Marcus Adams
Marcus Adams

Reputation: 53850

When using an UPDATE statement, the WHERE clause is used to specify the record(s) to update. In the following case, where you've modified both the headline and content:

UPDATE about SET headline='$headline' WHERE content='$content'

The above query attempts to update the headline field where the content field equals the new content. There won't be any rows where the existing content matches the new content.

You'd have to do something similar to:

UPDATE about SET headline='$headline', content='$new_content' WHERE content='$old_content'

However, you should generally be selecting a record by an identifier, not a content field.

UPDATE about SET headline='$headline', content='$new_content' WHERE id = $id

If you update using a field like content, you may accidentally update all rows that have the same content, instead of just the row that you're trying to update. Using a unique identifier allows you to update only the specified row.

You could store the identifier in the session (on the server side).

Upvotes: 3

Related Questions