PHP SQL syntax error MYSQL UPDATE [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
So for a long time this code worked but now all of the sudden i get 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 ''j_users' SET patient = '', year = '', gender = '', age = '', height = 'Select a' at line 1
HELP!
define('DB_NAME', 'DATABASE');
define('DB_USER', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value = htmlspecialchars($_POST['patient']);
$value4 = htmlspecialchars($_POST['year']);
$value5 = htmlspecialchars($_POST['gender']);
$value6 = htmlspecialchars($_POST['age']);
$value7 = htmlspecialchars($_POST['height']) . '.' . htmlspecialchars($_POST['height_inch']);
$value8 = htmlspecialchars($_POST['weight']);
$value9 = htmlspecialchars($_POST['foot_length']);
$value10 = htmlspecialchars($_POST['sheight']) . '.' . htmlspecialchars($_POST['sheight1']);
$value11 = htmlspecialchars($_POST['Amputation']);
$value13 = htmlspecialchars($_POST['Side']);
$value16 = htmlspecialchars($_POST['Flesh']);
$value18 = htmlspecialchars($_POST['Activity']);
$value21 = htmlspecialchars($_POST['practitioner']);
$value22 = htmlspecialchars($_POST['phone']);
$value23 = htmlspecialchars($_POST['email']);
$value24 = htmlspecialchars($_POST['Account']);
$value25 = htmlspecialchars($_POST['companyname']);
$value26 = htmlspecialchars($_POST['streetaddress']);
$value27 = htmlspecialchars($_POST['city']);
$value28 = htmlspecialchars($_POST['state']);
$value29 = htmlspecialchars($_POST['zip']);
$value30 = htmlspecialchars($_POST['companyname2']);
$value31 = htmlspecialchars($_POST['streetadress2']);
$value32 = htmlspecialchars($_POST['city2']);
$value33 = htmlspecialchars($_POST['state2']);
$value34 = htmlspecialchars($_POST['zip2']);
$value35 = htmlspecialchars($_POST['foot']);
$value39 = htmlspecialchars($_POST['purchaseorder']);
$value40 = htmlspecialchars($_POST['radio']);
$value41 = htmlspecialchars($_POST['lightflesh2']);
$value42 = htmlspecialchars($_POST['darkfleah2']);
$value43 = htmlspecialchars($_POST['foamcalf']);
$value44 = htmlspecialchars($_POST['additional']);
$value45 = htmlspecialchars($_POST['Sock1']);
$value46 = htmlspecialchars($_POST['Sock2']);
$value47 = htmlspecialchars($_POST['Sock3']);
$value48 = htmlspecialchars($_POST['day']);
//$sql = "INSERT INTO order_form (patient, newamputee, yearamputee, year, gender, age, height, weight, foot_length, sheight, ak, bk, left1, right1, bilateral, light_flesh, dark_flesh, k2, k3, k4, k4_extrme, practitioner, email, Account, companyname, streetaddress, city, state, zip, companyname2, streetaddress2, city2, state2, zip2, UltraStride, ActiveStride, NaturalStride, K2_ComfortStride, purchaseorder, radio, lightflesh2, darkfleah2, foamcalf, additional, Sock1, Sock2, Sock3, ground, thirdday, twoday, nextday) VALUES ('$value', '$value2', '$value3', '$value4', '$value5', '$value6', '$value7', '$value8', '$value9', '$value10', '$value11', '$value12', '$value13', '$value14', '$value15', '$value16', '$value17', '$value18', '$value19', '$value20', '$value21', '$value22', '$value23', '$value24', '$value25', '$value26', '$value27', '$value28', '$value29', '$value30', '$value31', '$value32', '$value33', '$value34', '$value35', '$value36', '$value37', '$value38', '$value39', '$value40', '$value41', '$value42', '$value43', '$value44', '$value45', '$value46', '$value47', '$value48', '$value49', '$value50', '$value51')";
$update = "UPDATE 'j_users'
SET patient = '$value', year = '$value4', gender = '$value5', age = '$value6', height = '$value7', weight = '$value8', foot_length = '$value9', sheight = '$value10', Amputation = '$value11', Side = '$value13', Flesh = '$value16', Activity = '$value18', practitioner='$value21', phone='$value22', email='$value23', Account = '$value24', companyname = '$value25', streetadress='$value26', city='$value27', state='$value28', zip='$value29', companyname2='$value30', streetadress2='$value31', city2='$value32', state2='$value33', zip2='$value34', foot='$value35', purchaseorder='$value39', radio='$value40', lightflesh2='$value41', darkfleah2='$value42', foamcalf='$value43', foamcalf='$value44', Sock1='$value45', Sock2='$value45', Sock3='$value46', day='$value47'
WHERE user_login = '" . $user . "'";
if (!$update) {
die('Invalid query: ' . mysql_error());
}
mysql_query($update, $link);
if (!mysql_query($update)) {
die('Error: ' . mysql_error()) ;
mysql_close();
}

The immediate cause of the error, as pointed out by Uueerdo in the comment is the incorrect symbol (single-quote instead of a backtick) in the quoting of the name of the table - which in this case does not need to be quoted at all as it is fixed and contains no special characters.
There are other issues in the code which we will leave alone for now as they do not immediately affect the issue, but I will update the answer if OP is interested in other things that would be good to fix.
UPDATE - things to fix:
As pointed out by Drew and Uueerdo in the comments, migrate from the deprecated mysql_ interface to mysqli_ or PDO.
The values entered by the user should be escaped with mysql_real_escape_string() (with the current interface), mysqli_escape_string() or via PDO parameter holders (?) depending on the interface, but not with htmlspecialchars(). If HTML escaping is needed, it should be done immediately before the HTML is to be displayed, not at the time it is stored in the database.
Note that most of your input names match the database column names. Thus you might be better off fetching the fields from the database via SHOW FIELDS once into a hard-coded array, editing it to exclude the irrelevant ones (another option to fetch it dynamically and fix up the array once it is fetched), and adding some logic to deal with the exceptions like height and height_inches as you iterate through the array and generate your query in a loop. The code thus becomes more flexible and easier to maintain.
Create some wrapper interface for your database access rather than directly accessing MySQL API. This way should a need arise to change the interface (e.g. mysql_ to mysqli) it is a matter of fixing a few calls in just one module rather than a major code change. You are also able to add things like query logging, automatic query EXPLAIN in trace mode, performance timing, and whatever else you might think of with regard to your queries, rather easy.

Related

Cannot insert lines into database

I have a basic database that consists of three tables :
Product(idP,name,price,quantity,stock_Minimal,stock_maximal)
Order(ref,date)
Order_Line(idP,ref,quatity)
the product table contains a catalogue of all the product available, the order table contains a list of all the orders references and their respective dates,and finally the order_line table contains informations about whats been ordered in every command
here is the code that I use to insert an order into the order table and its lines to Order_Line table:
<?php
if (isset($_POST['ref'])) {
$ref = $_POST['ref'];
$date = $_POST['date'];
$choosed_product = $_POST['choosed_product'];
$quantity = $_POST['quantity'];
$cn = mysqli_connect("localhost", "root", "");
mysqli_select_db($cn, "vente_db");
$res = mysqli_query($cn, "select * from commande where ref=" . $ref);
$cn->close();
if ($res != null) {
$cn->query("insert into Order_Line values (" . $choosed_product . ",$ref,$quantity)");
} else {
$co = mysqli_connect("localhost", "root", "");
mysqli_select_db($co, "vente_db");
mysqli_query($co, "insert into Commande
values('$ref',''$date'')");
mysqli_query($co, "insert into Order_Line values
(" . $choosed_product . ",$ref,$quantity)");
}
}
?>
But when I check the databse I don't find the inserted lines,can you please help me figure out the problem in my code
[edit]:I know that my code is vulnerable to sql injections, but this is just for a school project and we're not required to secure the database against hackers.
There are a lot of issues with this code. Your code is very much vulnerable to SQL Injection Attacks! I have commented everything inside the code:
Put connection string in the first line for making it available to use.
Add the DB selector to the connection.
Give an alternate message if connection fails.
Make sure you sanitize the data.
Optional: Make sure you backtick the column names and add single quotes for values.
This is not needed here. $cn->close();
Make sure you use the same implementation. Either OOP or Procedural.
You don't need another connection. $co = mysqli_connect("localhost", "root", ""); mysqli_select_db($co, "vente_db"); Use the previous connection.
You have an error in the SQL Syntax with double single quotes.
Add single quotes for the values.
Corrected Code:
<?php
if (isset($_POST['ref'])) {
// Put connection string in the first line for making it available to use.
// Add the DB selector to the connection.
// Give an alternate message if connection fails.
$cn = mysqli_connect("localhost", "root", "", "vente_db") or die("Cannot Connect. " . mysqli_connect_error());
// Make sure you sanitize the data.
$ref = mysqli_real_escape_string($cn, $_POST['ref']);
$date = mysqli_real_escape_string($cn, $_POST['date']);
$choosed_product = mysqli_real_escape_string($cn, $_POST['choosed_product']);
$quantity = mysqli_real_escape_string($cn, $_POST['quantity']);
// Optional: Make sure you backtick the column names and add single quotes for values.
$res = mysqli_query($cn, "select * from `commande` where `ref`='" . $ref . "'");
// This is not needed here.
// $cn->close();
if ($res != null) {
// Make sure you use the same implementation. Either OOP or Procedural.
mysqli_query($cn, "insert into `Order_Line` values ('" . $choosed_product . "', '$ref', '$quantity')");
} else {
// You don't need another connection.
// $co = mysqli_connect("localhost", "root", "");
// mysqli_select_db($co, "vente_db");
// Use the previous connection.
// You have an error in the SQL Syntax with double single quotes.
mysqli_query($cn, "insert into `Commande` values('$ref', '$date')");
// Add single quotes for the values.
mysqli_query($cn, "insert into `Order_Line` values ('" . $choosed_product . "', '$ref', '$quantity')");
}
}
?>
This should probably work. If not, at least it would tell you why it failed.

Unable to INSERT data into MySQL through HTML form using PHP [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
Here is my Form:
<html>
<head>
<title>Stats</title>
</head>
<body>
<h2>Member Information Form</h2>
<form action="submit_mbr_nfo.php" method="post">
Member ID <input type ="text" name= "mbrid"/><br>
Member Name <input type="text" name="mbrnm"/><br>
Actual Name <input type="text" name="atlnm"/><br>
<input type="submit" value="Save"/>
</form>
</body>
</html>
Here is my PHP file:
<?php
//Define database properties in global variables
define('DB_NAME', 'STATS');
define('DB_USER', 'root');
define('DB_PASSWORD', 'Test');
define('DB_HOST', 'localhost');
//store connection props in var
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
//check connection
if (!$link) {
die ('Could not connect to the Database: ' . mysql_error());
}
//map $_POST to vars
$mbr_id = mysql_real_escape_string($link, $_POST['mbrid']);
$mbr_nm = mysql_real_escape_string($link, $_POST['mbrnm']);
$atl_nm = mysql_real_escape_string($link, $_POST['atlnm']);
$sql = 'INSERT INTO MBR_NFO '.'(MBR_ID,MBR_NM,ATL_NM) '.'VALUES ('$mbr_id', '$mbr_nm','$atl_nm')';
mysql_select_db('STATS');
$exe_query = mysql_query( $sql, $link);
?>
And here is my php error log:
PHP Parse error: syntax error, unexpected '$mbr_id' (T_VARIABLE) in /Applications/MAMP/htdocs/stats/submit_mbr_nfo.php on line 21
I am very new and learning PHP and HTML, i tried several online solutions but nothing has worked so far. I am able to insert into DB if I don't use $_POST, i.e., manually typing in the values in php code, but that's not the goal, the goal is to use Form to populate MySQL DB. Any help is appreciated, thank you.
Try following query
$sql = "INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES ('$mbr_id', '$mbr_nm','$atl_nm')";
You are having issues with string concatenation and quotes. Try following query:
$sql = "INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES('$mbr_id', '$mbr_nm','$atl_nm')";
if you set primary key and auto increment on database for member id
so it very easy.you are not write mbr_id in query
$query="INSERT INTO MBR_NFO (MBR_NM,ATL_NM) VALUES( '$mbr_nm','$atl_nm')";
it's simple way
if you want not set primary key and autoincrement and try this code
$query ="INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM). VALUES('$mbr_id', '$mbr_nm','$atl_nm')";
You should use prepared statements (see below) instead of manually concateting the query string. But, since you’re new to PHP, let us first fix your code. The line
$sql = 'INSERT INTO MBR_NFO '.'(MBR_ID,MBR_NM,ATL_NM) '.'VALUES ('$mbr_id', '$mbr_nm','$atl_nm')';
has a couple of flaws. In PHP, string concatenation is done via the dot . operator, which you have used only partly. In order to construct the query string $sql, you have to add a couple of dots:
$sql = 'INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES (' . $mbr_id . ', ' . $mbr_nm . ',' . $atl_nm . ')';
While this is valid PHP syntax, it is still no valid SQL. If your user input is $mbr_id = 42, $mbr_nm = 'amit', $atl_nm = 'Amit Kumar', then after concatenation, $sql looks like
INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES (1, amit, Amit Kumar)
and is missing quotes around the strings amit and Amit Kumar. At best, this makes your query invalid; at worst, it makes your query prone to injection attacks. Therefore, build your query using
$sql = 'INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES ("' . $mbr_id . '", "' . $mbr_nm . '","' . $atl_nm . '")';
or, because in PHP, variables in strings that are quoted with double quotes – e.g. "my name is $name", but not 'my name is $name' – are evaluated:
$sql = "INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES ('$mbr_id', '$mbr_nm,'$atl_nm')";
By far the best practise, however, is using prepared statements and parameterized queries:
$con = new PDO('mysql:host=localhost;dbname=STATS', 'root', 'Test');
$stmt = $con->prepare('INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES (:mbr_id, :mbr_nm, :atl_nm)');
$stmt->bindValue(':id', $mbr_id);
$stmt->bindValue(':mbr_nm', $mbr_nm);
$stmt->bindValue(':atl_nm', $atl_nm);
$stmt->execute();

SQL Update code issue/PHP injection

I am having an issue with my SQL Update script.
It prints "Motto Changed" but doesn't update the row. My code is all correct according to many tutorials. Please Help
$sql="UPDATE loadout SET motto='".$_POST['motto']."' WHERE steamid='".$steamid."'";
UPDATE AGAIN:
<?php
require "../requires/php/steam.php";
$dbhost = '**';
$dbname = 'battlefield';
$dbuser = 'battlefield';
$dbpass = '**';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
$authserver = bcsub( SteamID(), '76561197960265728' ) & 1;
$authid = ( bcsub( SteamID(), '76561197960265728' ) - $authserver ) / 2;
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
mysql_select_db($dbname, $con);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "Motto Changed";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo"Motto changed on {$n} row(s)";
mysql_close($con)
?>
Never interpolate $_POST variables directly into SQL strings. You can't trust $_POST variables, they may easily contain characters that modify your SQL syntax, and that's what causes SQL injection vulnerabilties.
The weird thing is that you create an escaped version as $motto and then you never use it (as per comment from #Arth).
Always escape strings that you interpolate into SQL, even if you think they are "safe." For example, your $steamid contains only literal text that you control, plus a couple of integers. That should be safe, but what if some other developer changes the format of a steamid next year? If you escape it, you can't go wrong.
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
Of course, the best practice is to use query parameters. You are using PHP's deprecated mysql extension, which doesn't support query parameters. But I understand if you're not ready to rewrite a lot of code to switch to PDO. When you are, follow examples in How can I prevent SQL-injection in PHP?
Another issue: if you want to know if the UPDATE affected rows, don't assume it did just because the UPDATE didn't return an error. It's not an error if your condition in your WHERE clause simply matched zero rows. It's also not an error if the UPDATE matched a row, but the motto already contained the string you tried to set.
After the UPDATE, check the number of affected rows:
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo "Motto changed on {$n} row(s)";

MySQL not saving sentence after an '

This one has got me stumped. When I try to save something to the database that contains an apostrophe ('), it will save the sence up until then and after that it does not not. For example;
Say I am trying to save this: Report details Tim Cook's changes at Apple, for better or worse »
It saves: Report details Tim Cook
It saves to the database fine but only everything before the '
My code:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Any help as to why it might not be saving properly? I have tried mysql_real_escape_string but (if I am using it correctly) that does not seem to work.
Side note: What is the best way to secure the form above from attacks?
Update It is also doing it for " as well.
You need to call mysql_real_escape_string() after connecting to your database:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Change
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
to
$query = "INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')";
echo $query;
mysql_query($query);
And check out the actual query you are sending, easy to spot the problems then :)

PHP attempt to update a MySQL database doesn't update anything

I have my code below to update a my MySQL database, it's running but is not updating the database when I check rcords using phpmyadmin. plae hlp me.
$database = "carzilla";
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$manufacturerTable = $_POST[vehicleManufacturer];
$numberToSearch = $_POST[vehicleIdNo];
$engineType = $_POST[engineType];
$engineCC = $_POST[engineCC];
$year = $_POST[year];
$numberofDoors = $_POST[numberofDoors];
$tireSize = $_POST[tireSize];
$chasisNumber = $_POST[chasisNumber];
$vehicleMake = $_POST[vehicleMake];
$price=$_POST[price];
mysql_select_db("$database", $con);
$sql = mysql_query("UPDATE $manufacturerTable SET username='vehicleMake',
engineType='$engineType', engineCC='$engineCC', year='$year', chasisNo='$chasisNumber', numberOfDoors='$numberofDoors' ,numberOfDoors='$numberofDoors', tireSize='$tireSize', price='$price' WHERE `index` ='$id'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo 'record has been successfuly';
mysql_close($con);
?>
Take a good look at your query. You are referring to PHP variables in several different fashions in the same statement. In the query $manufacturerTable is just $manufacturerTable, you encase a few others in single quotes, some of which you remove the $ from, others you do not. I know I preach this far too often, but you should really look into using prepared statements. They take all the guess work out of using variables in your queries, and they prevent you from being victimized by injection hacks. But the short answer here is that you are not referencing your variables correctly in the query.
Sometimes putting the variables directly in the syntax can cause issues. Have you tried to use concatenation for the query.
$query = "UPDATE ".$manufacturerTable." SET username='vehicleMake', engineType='."$engineType."', engineCC='".$engineCC."', year='".$year."', chasisNo='".$chasisNumber."', numberOfDoors='".$numberofDoors."' ,numberOfDoors='".$numberofDoors."', tireSize='".$tireSize."', price='".$price."' WHERE index =".$id;
$sql = mysql_query($query); # this should be put in the if else
If index is number based you do not need the '' surrounding it. Plus is username='vehicleMake' or is it a variable. if it is a variable, add the $ or use concatenation like the rest. Your SQL check should be something like follows.
if (mysql_query($query))
{
echo 'record has been successfuly';
} else {
die('Error: ' . mysql_error() . ' | ' . $query);
}
The reason you export the query is so you can try it manually to make sure it works and what error you may be getting. phpMySQL can show a different error then the mysql_error() at times
Plus you should be escaping all input that is user entered using mysql_escape_string() or mysql_real_escape_string()

Categories