I'm trying to switch all my MySQL connections from the old mysql_query to PDOs. I'm trying to update multiple rows and columns of a MySQL table using different arrays and I'm receiving the following error:
[42000]: Syntax error or access violation: 1064 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 '(accnt, car, radio, misc) values ('admin', '300.00', '400.00', '10.00') WHERE ID' at line 1
From the following code:
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//$data = array_map(null,$account,$car_lease,$radio_lease,$misc_lease);
$A = count($lease_ID);
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH->prepare('UPDATE lease (accnt, car, radio, misc) values (:account, :car_lease, :radio_lease, :misc_lease) WHERE ID = :lease_ID');
$i = 0;
while($i < $A) {
$STH->bindParam(':account', $account[$i]);
$STH->bindParam(':car_lease', $car_lease[$i]);
$STH->bindParam(':radio_lease', $radio_lease[$i]);
$STH->bindParam(':misc_lease', $misc_lease[$i]);
$STH->bindParam(':lease_ID', $lease_ID[$i]);
$STH->execute();
$i++;
}
}
catch(PDOException $e) {
echo "I'm sorry, but there was an error updating the database.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
I believe this problem is arising from the way I'm calling the statement handle, but I'm not sure what part of my syntax is incorrect. Also, is this the best way of handling such situations? Or is there a better method to update multiple rows in a table?
You have confused the syntax between INSERT and UPDATE statements. Instead of a VALUES() list, you need a SET clause:
$STH = $DBH->prepare('
UPDATE lease
SET
accnt = :account,
car = :car_lease,
radio = :radio_lease,
misc = :misc_lease
WHERE ID = :lease_ID
');
Review the MySQL UPDATE syntax reference for the full specification to use with UPDATE statements.
I think this would be the simplest and easiest solution, if you can trust your keys and values:
$update = 'SET ';
$fields = array_keys($_POST);
$values = array_values($_POST);
foreach ($fields as $field) {
$update .= $field . '=?,';
}
$update = substr($update, 0, -1);
$db->query("update sub_projects ${update} where id=${_GET['id']}");
$db->execute($values);
Simple way to update multiple fields .but very important that inputs on your editing page must be in same order with your data base table.
hope its help
if (isset($_POST['pageSubmit'])) {
echo '<pre>';
print_r($_POST['page']);
echo '</pre>';
$fields = array('id','name','title','content','metaKey','metaDescr','metaTitle');//fields array
$fields = array_map(function($field){
return "`$field`";
},$fields);
$queryArray = array_combine($fields,$_POST['page']);//createng array for query
$countFields = count($queryArray);//getting count fields
$id = array_splice($queryArray , 0,-($countFields-1));//getting id of page
$insertArray = $queryArray;//getting new fields array without first key and value
function updatePage($db, array $fields, array $id){
$where = array_shift($id);
$sql = array();
foreach ($fields as $key => $value) {
$sql[] = "\n".$key."" ." = "."'".$value."'";
}
$sql = implode(",",$sql);
try {
$query = $db->prepare("UPDATE `pages` SET $sql WHERE `id` = $where ");
$query->execute();
} catch (Exception $e) {
echo $e->getMessage();
}
}
updatePage($db, $insertArray, $id);
}
better way is CASE, it is 3-4 time faster than preapared stmt
Related
database.php: //database class file
public function multipleInsert($table,$attrArray,$valuesArray) {
$sql = "INSERT INTO ".$table."(";
$array =[];
$appendValues = "";
$valuesInArray = "";
foreach ($attrArray as $key => $value) {
$sql.="".$value.", ";
}
$sql = substr_replace($sql,") VALUES ",strlen($sql)-2);
foreach ($valuesArray as $valArr) {
$valuesInArray.= "(";
foreach ($valArr as $key => $value) {
array_push($array, $value);
$valuesInArray.="?,";
}
$appendValues.= substr_replace($valuesInArray,"),",strlen($valuesInArray)-1);
$valuesInArray = "";
}
$appendValues = substr_replace($appendValues,"",strlen($appendValues)-1);
$sql.=$appendValues;
//die($sql);
$result = $this->executeQueryPRE($sql,$array);
return $result;
}
private function executeQueryPRE($sql,$arr) {
try{
$executeSQL = $this->Connection->prepare($sql);
print_r($executeSQL);die();
$executeSQL->execute($arr);
if($executeSQL) {
if($this->Connection->lastInsertId())
return $this->Connection->lastInsertId();
else
return true;
}
else
return false;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
sample.php // sample file which utilizing multiple insert query
require_once("database.php");
$Database = new Database;
$arr = ["ct_name","ct_num","ct_status"];
$arr1 = [["x","1234567890",1],["y","1234567890",1],["z","1234567890",1],["a","1234567890",1]];
$Database->multipleInsert("contact",$arr,$arr1);
Using PDO prepare statement, I am trying develop a dynamic multiple insert query. when I try to execute it, the values are getting inserted into table twice. I have gone for print_r($executeSQL) and die() option before executing it showed me a proper multiple insertion query as below.
PDOStatement Object ( [queryString] => INSERT INTO contact(ct_name,
ct_num, ct_status) VALUES (?,?,?),(?,?,?),(?,?,?),(?,?,?) )
why is it inserting twice and what is the reason and how can I overcome with this problem ?
Not an answer to your actual question but maybe to the actual problem you want to solve:
I don't think this string concat stuff is worth any trouble.
Takes longer for the php script to execute, pollutes the MySQL query cache, is error prone.
Therefore unless you can point to a very,very specific problem I think it loses on all points against: Just prepare a statement and execute it multiple times.
<?php
/*
table must be a valid table identifier
columns must be an array of valid field identifiers
recordData is an array of records, each itself an array of corresponding values for the fields in $columns
recordData is the only parameter for which proper encoding is taken care of by this function
*/
function foo($table, $columns, $recordData) {
$query = sprintf('
INSERT INTO %s (%s) VALUES (%s)
',
$table,
join(',', $columns) /* put in the field ids like a,b,c,d */,
join(',', array_pad(array(), count($columns), '?')) /* put in a corresponding number of ? placeholders like ?,?,?,? */
);
// resulting query string looks like INSERT INTO tablename (a,b,c,d) VALUES (?,?,?,?)
// let the MySQL server prepare that query
$stmt = $yourPDOInstance->prepare($query);
// it might fail -> check if your error handling is in place here....
// now just iterate through the data array and use each record as the data source for the prepapred statement
// this will (more or less) only transmit the statement identifier (which the MySQL server returned as the result of pdo::prepare)
// and the actual payload data
// .... as long as $yourPDOInstance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); has been set somewhere prior to the prepare....
foreach( $recordData as $record ) {
$stmt->execute( $record );
// might fail, so again: check your error handling ....
}
}
$cols = ["ct_name","ct_num","ct_status"];
$data = [
["x","1234567890",1],
["y","1234567890",1],
["z","1234567890",1],
["a","1234567890",1],
];
foo("contact", $cols, $data);
(script is tested by php -l only; no warranty)
see also: http://docs.php.net/pdo.prepared-statements
I have a mysql database table currency_exchange with columns currency,xrate and time.
I have a json currency feed which is providing currency exchange rates as:
"AED": 3.67266,"AFN": 57.1294 etc..
I need to update the values in my database. My php code is as follows:
$phpArray = json_decode($jsonData, true);
$extime = $phpArray['timestamp'];
$rates = $phpArray['rates'];
include_once 'connstring.inc.php';
$uptime = date("m-d-Y H:i:s");
if (isset($rates) && !empty($rates) )//if data set and not empty
{
$conn->beginTransaction();
$stmt = $conn->prepare("UPDATE `currency_exchange` set `currency` = :currency, `xrate` = :exchangerate,`time` = :time");
try
{
foreach($rates as $key => $value)
{
$stmt->execute(array(':currency' => $key, ':exchangerate' => $value, ':time' => $uptime));
}
$conn->commit();
}//end try
catch(PDOException $e)
{
$conn->rollBack();
}
}//end if
Currently my table is empty. I need to have a if empty insert else update code. How is that possible.
Requesting Help. Thanks in advance.
Update:
Checked for $rowcount in currency_exchange table. if ($rowcount > 0) update it else insert. Solved it..
As you have mentioned your table is empty, for the first time you have to perform an "INSERT" query. An "Update" query is used to update existing data only.
You have to replace
$stmt = $conn->prepare("UPDATE `currency_exchange` set `currency` = :currency, `xrate` = :exchangerate,`time` = :time");
with
$stmt = $conn->prepare("INSERT INTO `currency_exchange` (`currency` ,`xrate`,`time`) VALUES (currency, exchangerate,time");
This question already has an answer here:
bulk updating a list of values from a list of ids
(1 answer)
Closed 9 years ago.
Is this the only way to use two foreach statements with arrays going into a MySQL database?
The first one will update the ot_hours field, and the second foreach will update the lieu_hours field. I tried to combine both to do one query but it kept updating with wrong values.
This is what I have right now that works but is ugly.
foreach($_POST['overtimehours'] as $key => $value) {
dbQuery("UPDATE $TABLE SET ot_hours='$value', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3)");
}
foreach($_POST['lieutimehours'] as $key2 => $value2) {
dbQuery("UPDATE $TABLE SET lieu_hours='$value2', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key2 AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3)");
}
I'm sure there's much better ways to do this. This is why I'm hoping someone can help me :)
Thanks in advance for all responses
Applied to your case, here is the adapted answer of Danny:
<?php
//first query:
$arrk = array_keys($_POST['overtimehours']);
$arrv = array_values($_POST['overtimehours']);
$id_list = implode(',', $arrk);
$whens = implode(
"\n ",
array_map(
function ($id, $value) {
return "WHEN {$id} THEN {$value}";
},
$arrk,
$arrv
)
);
$sql1 = "
UPDATE $TABLE
SET ot_hours = CASE trans_num
{$whens}
END,
ot_status=1,
ot_submitdate='$ot_submitdate'
WHERE id IN ({$id_list})
AND uid='$contextUser'
AND (ot_status=0 OR ot_status=1 OR ot_status=3)
";
//second query:
$arrk = array_keys($_POST['lieutimehours']);
$arrv = array_values($_POST['lieutimehours']);
$id_list = implode(',', $arrk);
$whens = implode(
"\n ",
array_map(
function ($id, $value) {
return "WHEN {$id} THEN {$value}";
},
$arrk,
$arrv
)
);
$sql2 = "
UPDATE $TABLE
SET lieu_hours = CASE trans_num
{$whens}
END,
ot_status=1,
ot_submitdate='$ot_submitdate'
WHERE id IN ({$id_list})
AND uid='$contextUser'
AND (ot_status=0 OR ot_status=1 OR ot_status=3)
";
//now use pdo to run sql1 and sql2
?>
At least you're willing to learn new things, that's good.
Don't assume that everything you expect to be posted is actually posted.
Use the ternary operation and the isset function to check if your posts are actually in place:
$overTimeHours = isset($_POST['overtimehours']) ? $_POST['overtimehours'] : false;
$lieuTimeHours = isset($_POST['lieutimehours']) ? $_POST['lieutimehours'] : false;
if($overTimeHours != false && $lieuTimeHours != false)
{
// Proceed ; checkpoint #1
}
else
{
// The values were not posted, do some error handling.
}
So at this point, inside of checkpoint #1, you would be doing this:
foreach($overTimeHours as $key => $value)
{
dbQuery("UPDATE $TABLE SET ot_hours='$value', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3)");
}
foreach($lieuTimeHours as $key2 => $value2)
{
dbQuery("UPDATE $TABLE SET lieu_hours='$value2', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key2 AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3)");
}
You would probably not find it ugly to run through a single for loop if you only had one array to parse through.
Now you have two arrays (obviously), so if the minimum amount of loops for one array is one for loop, then the minimum amount of loops that you need for two arrays have to be two. The arrays are UNRELATED so you can't use one to make parsing the other one easier.
Parsing through $overTimeHours with
$overTimeHours as $key => $value
assuming that you really need the keys and the values inside of the array, is the shortest thing you can do. Same story goes for lieuTimeHours
Your code is vonurable to SQL-injections.
Don't insert variables into your query like this:
SET lieu_hours='$value2'
A decent programmer (or a 12-year old kid) could easily enter something like this into your database:
yo';DROP TAbLE users;--
Or something similar, to delete data from your database. You must use prepared statements in order to prevent from being attacked with basic SQL-injections.
Prepared statements are available in most situations there are, but I highly recommend using either PDO or the mysqli syntax.
Here's an example of how you can create a PDO connection:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
Now you can init the database variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
And now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
Now you can create a query that accepts prepared statements:
$query = "UPDATE :table SET ot_hours=:ot_hours, ot_status=1, ot_submitdate=:ot_submitdate WHERE trans_num=:key AND uid=:contextUser AND (ot_status=0 OR ot_status=1 OR ot_status=3);";
And you can now easily prepare it, execute your variables INTO the query WITHOUT being vonurable to sql injections (The difference is really: the non-prepared queries run COMMANDS, meanwhile the prepared ones are plain STRINGS):
$statement = $db->prepare($query); // Prepare the query.
$success = $statement->execute(array(
':table' => $TABLE,
':ot_hours' => $ot_hours,
':ot_submitdate ' => $ot_submitdate ,
':key' => $key,
':contextUser' => $contextUser
)); // Here you insert the variable, by executing it 'into' the prepared query.
if($success)
{
// Update was successful.
]
else
{
// Update was not successful, feel free to catch an PDOException $PDOexception
}
Also I note that I added a ";" at the end of your script, which is not REQUORED but I feel that it's safer, to make sure to tell that your execution is finished and you don't want anything related to follow (even though It's not from you).
I hope that I answered your question/s (and hopefully way beyond that), I hope that you'll consider what I said :) Feel free to ask if there are any questions.
Also, don't hesitate to correct me if I may have said anything incorrectly meanwhile writing this answer.
I would recommend you to use prepared statement. You should at least correctly encode other variables you use ($TABLE, ...)
$firstUpdate =
"UPDATE $TABLE
SET ot_hours=:value, ot_status=1, ot_submitdate='$ot_submitdate'
WHERE trans_num=:key
AND uid='$contextUser'
AND (ot_status=0 OR ot_status=1 OR ot_status=3)";
$secondUpdate =
"UPDATE $TABLE
SET lieu_hours=':value', ot_status=1, ot_submitdate='$ot_submitdate'
WHERE trans_num=:key
AND uid='$contextUser'
AND (ot_status=0 OR ot_status=1 OR ot_status=3)";
$db = PDO(...); // I assume here a connection managed by PDO
$stmt = $db->prepare($firstUpdate);
foreach($_POST['overtimehours'] as $key => $value) {
$stmt->execute(array(":key"=>$key,":value"=>$value);
}
$stmt = $db->prepare($secondUpdate);
foreach($_POST['lieutimehours'] as $key => $value) {
$stmt->execute(array(":key"=>$key,":value"=>$value);
}
In my opinion first thing you have to do is reduce the number of opening the connections with the DB like the following:
$query = "";
foreach($_POST['overtimehours'] as $key => $value) {
$query .="UPDATE $TABLE SET ot_hours='$value', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3) ; ";
}
foreach($_POST['lieutimehours'] as $key2 => $value2) {
$query .= "UPDATE $TABLE SET lieu_hours='$value2', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key2 AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3); ";
}
if ($query) dbQuery($query);
second and it is important, like you said combine the two arrays in one try and debug your code untill you succeed .
I have an array like this
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
When I do a var-dump I get this ->
{ ["phone"]=> int(111111111) ["image"]=> string(19) "sadasdasd43eadasdad" }
Now I am trying to add this to the DB using the IN statement -
$q = $DBH->prepare("INSERT INTO user :column_string VALUES :value_string");
$q->bindParam(':column_string',implode(',',array_keys($a)));
$q->bindParam(':value_string',implode(',',array_values($a)));
$q->execute();
The problem I am having is that implode return a string. But the 'phone' column is an integer in the database and also the array is storing it as an integer. Hence I am getting the SQL error as my final query look like this --
INSERT INTO user 'phone,image' values '111111111,sadasdasd43eadasdad';
Which is a wrong query. Is there any way around it.
My column names are dynamic based what the user wants to insert. So I cannot use the placeholders like :phone and :image as I may not always get a values for those two columns. Please let me know if there is a way around this. otherwise I will have to define multiple functions each type of update.
Thanks.
Last time I checked, it was not possible to prepare a statement where the affected columns were unknown at preparation time - but that thing seems to work - maybe your database system is more forgiving than those I am using (mainly postgres)
What is clearly wrong is the implode() statement, as each variable should be handled by it self, you also need parenthesis around the field list in the insert statement.
To insert user defined fields, I think you have to do something like this (at least that how I do it);
$fields=array_keys($a); // here you have to trust your field names!
$values=array_values($a);
$fieldlist=implode(',',$fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="insert into user($fieldlist) values(${qs}?)";
$q=$DBH->prepare($sql);
$q->execute($values);
If you cannot trust the field names in $a, you have to do something like
foreach($a as $f=>$v){
if(validfield($f)){
$fields[]=$f;
$values[]=$v;
}
}
Where validfields is a function that you write that tests each fieldname and checks if it is valid (quick and dirty by making an associative array $valfields=array('name'=>1,'email'=>1, 'phone'=>1 ... and then checking for the value of $valfields[$f], or (as I would prefer) by fetching the field names from the server)
SQL query parameters can be used only where you would otherwise put a literal value.
So if you could see yourself putting a quoted string literal, date literal, or numeric literal in that position in the query, you can use a parameter.
You can't use a parameter for a column name, a table name, a lists of values, an SQL keyword, or any other expressions or syntax.
For those cases, you still have to interpolate content into the SQL string, so you have some risk of SQL injection. The way to protect against that is with whitelisting the column names, and rejecting any input that doesn't match the whitelist.
Because all other answers allow SQL injection. For user input you need to filter for allowed field names:
// change this
$fields = array('email', 'name', 'whatever');
$fieldlist = implode(',', $fields);
$values = array_values(array_intersect_key($_POST, array_flip($fields)));
$qs = str_repeat("?,",count($fields)-1) . '?';
$q = $db->prepare("INSERT INTO events ($fieldlist) values($qs)");
$q->execute($values);
I appreciated MortenSickel's answer, but I wanted to use named parameters to be on the safe side:
$keys = array_keys($a);
$sql = "INSERT INTO user (".implode(", ",$keys).") \n";
$sql .= "VALUES ( :".implode(", :",$keys).")";
$q = $this->dbConnection->prepare($sql);
return $q->execute($a);
You actually can have the :phone and :image fields bound with null values in advance. The structure of the table is fixed anyway and you probably should got that way.
But the answer to your question might look like this:
$keys = ':' . implode(', :', array_keys($array));
$values = str_repeat('?, ', count($array)-1) . '?';
$i = 1;
$q = $DBH->prepare("INSERT INTO user ($keys) VALUES ($values)");
foreach($array as $value)
$q->bindParam($i++, $value, PDO::PARAM_STR, mb_strlen($value));
I know this question has be answered a long time ago, but I found it today and have a little contribution in addition to the answer of #MortenSickel.
The class below will allow you to insert or update an associative array to your database table. For more information about MySQL PDO please visit: http://php.net/manual/en/book.pdo.php
<?php
class dbConnection
{
protected $dbConnection;
function __construct($dbSettings) {
$this->openDatabase($dbSettings);
}
function openDatabase($dbSettings) {
$dsn = 'mysql:host='.$dbSettings['host'].';dbname='.$dbSettings['name'];
$this->dbConnection = new PDO($dsn, $dbSettings['username'], $dbSettings['password']);
$this->dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
function insertArray($table, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="INSERT INTO `".$table."` (".$fieldlist.") VALUES (${qs}?)";
$q = $this->dbConnection->prepare($sql);
return $q->execute($values);
}
function updateArray($table, $id, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$firstfield = true;
$sql = "UPDATE `".$table."` SET";
for ($i = 0; $i < count($fields); $i++) {
if(!$firstfield) {
$sql .= ", ";
}
$sql .= " ".$fields[$i]."=?";
$firstfield = false;
}
$sql .= " WHERE `id` =?";
$sth = $this->dbConnection->prepare($sql);
$values[] = $id;
return $sth->execute($values);
}
}
?>
dbConnection class usage:
<?php
$dbSettings['host'] = 'localhost';
$dbSettings['name'] = 'databasename';
$dbSettings['username'] = 'username';
$dbSettings['password'] = 'password';
$dbh = new dbConnection( $dbSettings );
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
$dbh->insertArray('user', $a);
// This will asume your table has a 'id' column, id: 1 will be updated in the example below:
$dbh->updateArray('user', 1, $a);
?>
public function insert($data = [] , $table = ''){
$keys = array_keys($data);
$fields = implode(',',$keys);
$pre_fields = ':'.implode(', :',$keys);
$query = parent::prepare("INSERT INTO $table($fields) VALUES($pre_fields) ");
return $query->execute($data);
}
if(isset($_POST['Update'])) {
$placename = $_POST['placename'];
$description = trim(addslashes($_POST['description']));
$hotel = $_POST['hotel'];
$transport = $_POST['transport'];
$map = $_POST['map'];
$sqlp = "UPDATE places SET placename = $placename, description = $description, hotel = $hotel, transport = $transport, map = $map WHERE place_id = ". $sPlace['place_id'];
connection();
if(mysql_query($sqlp)) {
echo "Successfully Updated";
} else {
echo mysql_error();
}
}
Error Message is following-
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 '
map = map WHERE place_id = 54' at line 1
You error in that code is that you don't add quotes around variables, it should be like this:
$query = "UPDATE `table` SET `name`='".mysqli_real_escape_string($_POST['name'])."' WHERE `id`=1";
But please try to use PDO with transaction as you will be able to debug any errors and you don't have to worry about SQL Injection.
Try this: (you will see errors, and if it's not ok, it will rollback)
$db = new PDO('mysql:host=localhost;dbname=databaseName', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false));
$placename = $_POST['placename'];
$description = trim(addslashes($_POST['description']));
$hotel = $_POST['hotel'];
$transport = $_POST['transport'];
$map = $_POST['map'];
try {
$db->beginTransaction();
$stmt = $db->prepare("UPDATE `places` SET `placename`=:placename, `description`=:description, `hotel`=:hotel, `transport`=:transport, `map`=:map WHERE `place_id`=:place_id");
$stmt->execute(array(':placename' => $placename, ':description' => $description, ':hotel' => $hotel, ':transport' => $transport, ':map' => $map, ':place_id' => $sPlace['place_id']));
$db->commit();
} catch(PDOException $ex) {
$db->rollBack();
echo $ex->getMessage();
}
You have an error in your SQL syntax ... 'map = map WHERE place_id = 54' at line 1
map = map <-- is invalid. the right-side should be an sql value (quoted string, number, etc). Perhaps map = 'map' (quote the value) is the intended result?
The problem you are seeing has come about because none of your string literals have been quoted, so the comma in the value of $transport is being evaluated as a separator between SQL SET clauses and so gives rise to the syntax error that you witness.
You should quote your string literals—or better yet, use parameterised statements so that your variables do not get evaluated for SQL at all (which avoids all forms of SQL injection attack).