Update Records SYNTAX ERROR - php

I'm attempting to make a form for a charity that allows staff members to view and update victim records that are stored in the SQL Database via the website. I have managed to display the records and create a form that allows the alteration of the records, however when I enter variables I receive a SYNTAX error.
$updateSQL="UPDATE Victims SET victimFName=".$victimFN." WHERE victimId=".$id."";
$exeupdateSQL= mysql_query($updateSQL) or die (mysql_error());
echo "The Record has been updated";
I receive the 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 'WHERE victimId=' at line 1'
I then researched SQL Injections and changed the code:
$updateSQL="UPDATE Victims SET victimFName=".mysql_real_escape_string($_POST['victimFName']).";
WHERE victimId=".mysql_real_escape_string($_POST['victimId'])."";
exeupdateSQL= mysql_query($updateSQL) or die (mysql_error());
echo "The Record has been updated";
This still didnt work.
I have attempted to replace my variables $VictimFN and $id by entering data into the SQL query and the code works, updating the record. Such as:
$updateSQL="UPDATE Victims SET victimFName='Mary Smith' WHERE victimId='1'";
$exeupdateSQL= mysql_query($updateSQL) or die (mysql_error());
echo "The Record has been updated";
I am fairly new to programming and was wondering how I could fix this as the issue is to do with my variables.
Thanks to your help I have established the problem with the code and have now fixed it to:
$updateSQL="UPDATE Victims SET victimFName='".mysql_real_escape_string($_POST['victimFName'])."' WHERE victimId='".mysql_real_escape_string($_POST['victimId'])."'";
$exeupdateSQL=mysql_query($updateSQL) or die (mysql_error());
echo "The Record has been updated";
echo "<br><a href=ViewVictimRequest.php>View Updated Record</a>";
There are now no errors, however the records state they are updated when they are not. Is there anyway to fix this?
Thank you in advance for your response and sorry for the inconvenience!

The correct way is:
$updateSQL="UPDATE Victims SET victimFName='".mysql_real_escape_string($_POST['victimFName'])."' WHERE victimId='".mysql_real_escape_string($_POST['victimId'])."'";
Your $_POST values are string, thus you need to enclose them in single quotes '. Also remove the semi-colon ; before WHERE, it's breaking the string.
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

You have an errant semi-colon and missing quotes. Here's a cleaner version of your query:
$updateSQL="UPDATE Victims SET victimFName='".mysql_real_escape_string($_POST['victimFName'])."'
WHERE victimId=".mysql_real_escape_string($_POST['victimId']);
Or
$fname = mysql_real_escape_string($_POST['victimFName']);
$id = mysql_real_escape_string($_POST['victimId']);
$updateSQL="UPDATE Victims SET victimFName='{$fname}' WHERE victimId={$id}";

Related

Getting this error message when trying to UPDATE MySQL table

Notice: Undefined variable: table_name in /Applications/MAMP/htdocs/welcometowarwick/scripts/php/insert_imagery.php on line 106
Error: UPDATE SET business_description='', image1='profiles/sadsadas/', image2='profiles/sadsadas/', image3='profiles/sadsadas/', image4='profiles/sadsadas/', image5='profiles/sadsadas/' WHERE id='307' LIMIT 1
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 'SET business_description='', image1='profiles/sadsadas/', image2='pr' at line 1
Here is the UPDATE code
$updatesql = sprintf("UPDATE $table_name SET
business_description='$business_description',
image1='$insert_upload1',
image2='$insert_upload2',
image3='$insert_upload3',
image4='$insert_upload4',
image5='$insert_upload5'
WHERE id='$user_id' LIMIT 1");
if (mysqli_query($link, $updatesql)) {
header('Location: ../../register/complete.php');
} else {
echo "Error: " . $updatesql . "<br>" . mysqli_error($link);
}
mysqli_close($link);
Can anyone see what the error with the syntax is?
This is too long for a comment, therefore I am submitting the following.
The syntax error is clear:
right syntax to use near 'SET it starts at SET, so this tells me that:
$table_name is either not defined, or it contains a character that MySQL doesn't agree with. Possibly a space, a hyphen; who knows. Only you know that and how $table_name is defined, or whether it's defined at all.
Plus, as I stated in comments; you're using sprintf but there is no syntax to support that. You can just get rid of it, far as I'm concerned.
It is also unclear which MySQL API you are using to connect with, so make sure you are indeed using mysqli_ to connect with and not mysql_ or PDO.
Those different MySQL APIs do not intermix with each other.
If you have any questions, please do not hesitate to place a comment underneath my answer.
You may also want to make use of mysqli_real_escape_string() in order to escape your data. There might be characters in there that MySQL will also want to buck about.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
this query can't get the table name so it happens try to first echo $updatesql and check the query get table name

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

srno is being successfully fetched from a textbox
<?php
$srno = $_POST['srno'];
mysql_connect("localhost","root","");
mysql_select_db("visit");
$sql ="UPDATE visitor SET Exit='".$ab."' WHERE srno=$srno";
mysql_query($sql) or die ("Error: ".mysql_error());
?>
If $srno is a string you're missing quotes around it
$ab is not defined
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You are also wide open to SQL injections
To further elaborate on John (Conde's) answer, exit is a MySQL reserved word:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Either rename it to something else, or wrap it in backticks:
$sql ="UPDATE visitor SET `Exit`='".$ab."' WHERE srno=$srno";
^ ^ backticks
or (if $srno is a string, as John stated in his answer)
$sql ="UPDATE visitor SET `Exit`='".$ab."' WHERE srno='$srno'";
You have used mysql_error() on mysql_query() which should have signaled the syntax error, something you have not shared completely in your question, only as the question's title which does not show us the complete error message, however I am certain it is something to the effect of
...MySQL server version for the right syntax near 'Exit...
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
which will signal an Undefined variable... warning for $ab.

Mysql syntax error in php query not showing up in browser

Let's say that I have an error in a php/mysql query :
$query = "SELECT * ROM users WHERE _id = :user_id";
Here, FROM is missing an "F".
When I launch this php file in localhost, my browser is not reacting, it should display something like that:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
But it doesn't, only blank page...
How do I enable this option?
EDIT: I'm using PDO.
If you use mysql_* functions you have to do something like: mysql_query($sql) or die(mysql_error());
If you use mysqli_*: mysqli_query($sql) or die(mysqli_error());
If you use PDO: $stmt->execute() or die(print_r($stmt->errorInfo)); //$stmt is instance of PDOStatemen
If you still use mysql_* I strongly recommend to stop using (sql injection I mean).
First use mysql_error() function in your code in case if query is not executed
successfully. something like this :
if(!mysql_query($query)){
echo mysql_error();
}
Secondly, check in your php.ini whether error_reporting is on or off.
Then check on the browser for the error.

Sql query problem

I have the below sql query that will update the the values from a form to the database
$sql=
"update leads set
category='$Category',
type='$stype',
contactName='$ContactName',
email='$Email',
phone='$Phone',
altphone='$PhoneAlt', mobile='$Mobile',
fax='$Fax',
address='$Address',
city='$City',
country='$Country',
DateEdited='$today',
printed='$Printed',
remarks='$Remarks'
where id='$id'";
$result=mysql_query($sql) or die(mysql_error());
echo '<h1>Successfully Updated!!.</h1>';
when i submit I dont get any errors and the success message is displayed but the database isnt updated . When i echo the $sql, all the values are set properly. and when i ech the $result i get the value 1.
can someone please tell me what am i doing wrong here??
Have you tried running the echo of $sql directly using some DB tool? It may provide a more informative error. Alternatively, if that works you may have an issue where the transaction isn't being committed. Often a connection is set to automatically commit transactions, but that may not be the case here. Try adding a commit.
And have you ever heard of SQL injection attacks?
If you have a query that is not giving the expected result or receiving an error, and the problem isn't obvious, you should generally take a look at the final query just before it's run. Try using this right before running the query:
echo $sql;
exit;
Viewing the actual query often makes it obvious what the problem is, especially when the query includes variables. If the problem still isn't obvious, you can paste the query as is into a query browser to get feedback directly from the database engine.
Interestingly, using parametrized queries, you won't get to see the parameter values, as the parameters get replaced by MySQL, not PHP, however, you'll still get to see the entire prepared query.
Also, you can see the number of affected rows from your UPDATE statement with the mysql_affected_rows() function. You could put this immediately after the query is run:
echo ("Updated records:", mysql_affected_rows());
Spaces are often forgotten when concatenating queries.
$sql = "SELECT * FROM ducks";
$sql .= "WHERE duck = 'goose'";
When echoing the above query, we see:
SELECT * FROM ducksWHERE duck <> 'goose'
I'm guessing that the WHERE clause in your UPDATE statement isn't matching an "id = '$id'".
Also, is the id column really a string? You've put single quotes around the value. MySQL will cast the string to an integer if needed, but if it's an integer, save the database some work and remove the single quotes.
try to echo $sql and run it directly in any database console, may be there is no record with id = $id
SQL Injection can be the answer. Not an intentional attack (at this moment), but if your parameters have some unexpected information like quotes or other reserved characters you can have strange results. So, try to run this SQL directly in your database administration utility.
Try doing this
"""update leads set
category="$Category",
type="$stype", etc...; """
See if that works

Error in MySQL update command. (in php)

Good Morning everyone,
I am using an update command in php to update data in mysql. This is my code:
$sql=mysql_query("UPDATE blpublication SET JournalName = '$_POST[journal]', AcceptanceDate = '$_POST[acceptancedate]', PublishedDate = '$_POST[publisheddate]', Comment = '$_POST[comment]'
WHERE JobNo = '$_POST[jobno]'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "record Updated";
It does updates the field but, it gives me the following error. And i can not figure it out why am i getting 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 '1' at line 1"
Can you help me in this
Best
Zeeshan
Can you tell us what the exactly output of $sql is? By the way, BIG security hole there. You should always escape query inputs namely:
$journal = mysql_real_escape_string($_POST['journal']);
$acceptance_date = mysql_real_escape_string($_POST['acceptancedate']);
$publish_date = mysql_real_escape_string($_POST['publisheddate']);
$comment = mysql_real_escape_string($_POST['comment']);
$job_no = intval($_POST['jobno']); // assuming jobNo is a number
$sql = <<<END
UPDATE blpublication
SET JournalName = '$journal',
AcceptanceDate = '$acceptance_date',
PublishedDate = '$publish_date',
Comment = '$comment'
WHERE JobNo = $jobno
END;
mysql_query($sql);
if (mysql_error()) {
die("Error executing query '$sql': " . mysql_error());
}
echo "record Updated";
I would sanitize your input first. This could lead to some very nasty errors such as what you are experincing and malicious attacks. Look up SQL Injection.
I think the problem is that you're running mysql_query twice. The first time it works and returns 1 (true), which you assign to $sql. Then you call mysql_query again, passing $sql (which equals 1). Of course "1" is not a valid SQL query, so you get the syntax error.
I wholeheartedly agree that you must sanitize those inputs!
Similar to the following post, i believe when you have any object or array syntax, you need to put in braces.
SET JournalName = '${_POST[journal]}'
edit: and yes, as others pointed out you are risking sql injection.
First of all, your code is prone to SQL injection, escape your POST values:
$journal = mysql_real_escape_string($_POST['journal']);
And to actually debug your query, we need the query itself. Add an echo() statement before the actual execution of the query and post the result, the POST values possibly contain some unexpected value.
Your general UPDATE syntax looks ok, except for the obvious injection possibilities, but you need to output $sql. One of your variables probably has a quote in it or some other issue like that....
Looking at the SQL UPDATE statement in your code, one thing leaps out at me. The table name is blpublication, are you maybe missing a 't', i.e. tblpublication?
Also you should really sanitise your input, otherwise you're going to be a victim of a SQL injection attack.
Try concatenating the $_POST values. Im not sure if including them without quoting the key is possible?
$sql= mysql_real_escape_string("UPDATE blpublication SET JournalName = '".$_POST['journal']."', AcceptanceDate = '".$_POST['acceptancedate']."', PublishedDate = '".$_POST['publisheddate']."', Comment = '".$_POST['comment']."'
WHERE JobNo = '".$_POST['jobno']."'");
$result = mysql_query($sql);
Note: mysql_* commands are depreciated. You should switch over to mysqli_*.

Categories