Checking if a record exists in a database.
Posted: Sat Aug 26, 2006 5:34 pm
Ok. I have this long piece of code I've been writing, viewable at viewtopic.php?p=302566.
In there, there is a portion where I am submitting data from a form with the fields "id", "link", "linkimage", "title", "content."
Then, I am calling a function that should check to see if a row in the database exists with that ID. IF the row exists, update it with the new information. If it does NOT exist, create a row with that information. This is what I have:
No matter what, though, it's going to UPDATE, which works with existing data, but obviously won't create new data.
What am I doing wrong?
SM
In there, there is a portion where I am submitting data from a form with the fields "id", "link", "linkimage", "title", "content."
Then, I am calling a function that should check to see if a row in the database exists with that ID. IF the row exists, update it with the new information. If it does NOT exist, create a row with that information. This is what I have:
Code: Select all
openDatabaseScreevo();
$id = mysql_real_escape_string($_POST["id"]);
$title = mysql_real_escape_string($_POST["title"]);
$link = mysql_real_escape_string($_POST["link"]);
$linkimage = mysql_real_escape_string($_POST["linkimage"]);
$content = mysql_real_escape_string($_POST['content']);
$result = mysql_query("SELECT id AS 'id2' FROM pages WHERE id = '$id'");
if (mysql_num_rows($result) == 0) { // If the ID number doesnt exist, make a new one
$result2 = mysql_query("INSERT INTO pages set id='$id', title='$title', content='$content',link='$link', linkimage='$linkimage'");
if (!$result2) {
echo "FAILED! <br>";
echo mysql_error();
} else {
echo 'You have successfully created page number ' . $id . ' called ' . $title . '. To update more, please go back.';
mysql_close();
}
} else { // if it does, update it.
$result2 = mysql_query("UPDATE pages SET content = '$content', title = '$title', link = '$link', linkimage = '$linkimage' WHERE id = '$id'");
if (!$result2) {
echo 'FAILED!';
echo mysql_error();
} else {
echo 'You have successfully updated page number ' . $id . ' called ' . $title . '. To update more, please go back.';
mysql_close();
}
}
}What am I doing wrong?
SM