Weird issue with a php if statement
Question by FunkyMonk91
I want to use this page to determine if the user has either updated a newsletter or created a new one. It connects to the database no problem and will update, but I can not get it to insert a fresh one as it gives me this error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ” at line 1
If I remove the if statement and just force it to insert a new record it will work with no issues.
Any advice would be greatly appreciated, thank you.
<?php
$server = "localhost";
$username = "user";
$password = "****";
$database = "test";
$con = mysql_connect($server, $username, $password);
$title = $_POST["title"];
$body = $_POST["body"];
$transaction = "Record Added";
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
if(isset($_POST["id"]))
{
$sql = "INSERT INTO newsletter (date, title, body)
VALUES('1990-12-12', '$title', '$body')";
}
else
{
$id = $_POST["id"];
$transaction = "Record Updated";
$sql = "UPDATE newsletter SET title='".$title."', body='".$body."' WHERE newsletterId =".$id;
}
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo $transaction;
mysql_close($con);
?>
Answer by jeroen
Your logic seems flawed, if an ID is posted you try to insert and when no ID is posted you try to update:
if(isset($_POST["id"]))
{
$id = $_POST["id"];
$transaction = "Record Updated";
$sql = "UPDATE newsletter SET title='".$title."', body='".$body."' WHERE newsletterId =".$id;
}
else
{
$sql = "INSERT INTO newsletter (date, title, body)
VALUES('1990-12-12', '$title', '$body')";
}
That is where your error comes from, your $id
is empty.
Apart from that you should look into sql injection. Switching to prepared statements is the best way to go.
Answer by Starx
Quotes your query properly
$sql = "UPDATE newsletter SET title='".$title."', body='".$body."' WHERE newsletterId ='$id'";