PDO Error with MySQL query [duplicate] - php

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I have been staring at the below code for over an hour any cannot see any issues.
public function add($data){
$sql = 'INSERT INTO ' . $this->name . '(fbid, userAccessToken, name, location, story, gender, email, email_md5, referrer, date, use, optin) VALUES (:fbid, :userAccessToken, :name, :location, :story, :gender, :email, :email_md5, :referrer, :date, :use, :optin)';
$mysqldate = date('Y-m-d G:i:s');
$result = $this->dbh->prepare($sql);
if($result->execute(array(
':fbid' => $data['fbid'],
':userAccessToken' => $data['userAccessToken'],
':name' => $data['name'],
':location' => $data['location'],
':story' => $data['story'],
':gender' => $data['gender'],
':email' => $data['email'],
':email_md5' => md5($data['email']),
':referrer' => $data['referrer'],
':date' => $mysqldate,
':use' => $data['use'],
':optin' => $data['optin']
))){
$return = $this->dbh->lastInsertId();
}
}
The error is
PHP Warning: PDOStatement::execute() [pdostatement.execute]:
SQLSTATE[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 'use, optin)
VALUES ('517371547', 'no-auth', 'Shane Jones', 'Manchest' at line 1

USE is a reserved word in mySQL.
You need to put it in backticks, or use a different column name.

use is a keyword in MySQL. If you want to use it as a column identifier, enclose it in backticks:
$sql = 'INSERT INTO `' . $this->name . '` ( `fbid`, `userAccessToken`, `name`, `location`, `story`, `gender`, `email`, `email_md5`, `referrer`, `date`, `use`, `optin`) VALUES (:fbid, :userAccessToken, :name, :location, :story, :gender, :email, :email_md5, :referrer, :date, :use, :optin)';
Anyway you should always enclose all identifiers in backticks, to prevent such errors!

USE is a reserved keyword that must be enclosed with backticks ` (see documentation).

Your problem comes from the fact that you are building your query manually.
While with whatever sane database abstraction library which will take the duty of building syntactically correct queries for you, the code become as small as few short lines:
public function add($data){
global $db;
$data['date'] = date('Y-m-d G:i:s');
$db->query('INSERT INTO ?n SET ?u',$this->name,$data);
return $db->insertId();
}
and raise no error on any of nearly hundred reserved words even if you know none of them.

Related

PHP PDO SQL syntax error [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I've looked around the internet and haven't been able to resolve this issue.
I'm trying to insert a row into a mySQL table using PDO through this function
function newItem($name, $desc, $price, $catID){
echo $name . "\n";
echo $price . "\n";
echo $desc . "\n";
echo $catID . "\n";
$conn = self::connect();
//INSERT Order
$sql = "INSERT INTO catalogue (Name, Price, CatID, Desc)
VALUES ('$name', $price, $catID, '$desc')";
// use exec() because no results are returned
$conn->exec($sql);
}
when i do, i get this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Desc) VALUES ('User', 0.00, 3, 'theUser')' at line 1' in C:\xampp\htdocs\classes\catalogue.php:65 Stack trace: #0 C:\xampp\htdocs\classes\catalogue.php(65): PDO->exec('INSERT INTO cat...') #1 C:\xampp\htdocs\classes\main.php(39): Catalogue->newItem('User', 'theUser', '0.00', '3') #2 {main} thrown in C:\xampp\htdocs\classes\catalogue.php on line 65
I can confirm that the self::connect(); method works, and the problem only occurs when i try to insert data into the Desc column.
I've spent a good while trying to sort this issue, however my knowledge of PDO is quite vague....
Can anyone see where I've gone wrong?
the echo's show this:
User 0.00 theUser 3
DESC is a keyword. You have to escape the column Name using backtics or better rename the column.
$sql = "INSERT INTO catalogue (Name, Price, CatID, `Desc`)
VALUES ('$name', $price, $catID, '$desc')";
For more Information about keywords see the official documentation.
Desc is reserved keyword in mysql in must be in backtick https://dev.mysql.com/doc/refman/5.7/en/keywords.html.html and use prepare and bind statement
$sth = $conn->prepare("INSERT INTO catalogue (Name, Price, CatID, `Desc`)
VALUES (:Name, :Price, :CatID, :Desc)");
$sth->bindParam(':Name', $name, PDO::PARAM_STR);
$sth->bindParam(':Price', $price, PDO::PARAM_STR);
$sth->bindParam(':CatID', $catID, PDO::PARAM_INT);
$sth->bindParam(':Desc', $desc, PDO::PARAM_STR);
$sth->execute();
Try this
$sql = "INSERT INTO catalogue (Name, Price, CatID, Desc)
VALUES ('".$name."', $price, $catID, '".$desc."')";

PHP: PDO MySQL error

I don't really know MySQL but I try.
I have this script in PHP
$sql = $DB->prepare("INSERT INTO `users`(`id`, `firstname`, `lastname`, `email`, `password`) VALUES ($this->firstname, $this->lastname, $this->email, $this->password))");
and when I use
print_r($sql->errorInfo());
It is giving me this error
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter
number: no parameters were bound in
C:\Bitnami\wampstack-5.5.27-0\apache2\htdocs\OOPLogin\register.php on
line 115 Array ( [0] => HY093 [1] => [2] => )
If anyone could help me, I would appreciate it very much.
Thank you.
EDIT: I changed it to
$sql = $DB->prepare("INSERT INTO `users`(`firstname`, `lastname`, `email`, `password`) VALUES ($this->firstname, $this->lastname, $this->email, $this->password))");
And now it's giving me
Array ( [0] => 42000 [1] => 1064 [2] => 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 '#gmail.com, ff0b80f26259f9c0178aeed5198bac48))' at line 1 )
Assuming your using PDO, you need to bind parameters with a prepared statement.
Here's an example, using the PDO::prepare documentation for reference:
$statement = $DB->prepare("INSERT INTO `table` (`id`) VALUES (?)");
$statement->execute(array($user_id));
Additional example using mysqli as an alternative...
$statement = $DB->prepare("INSERT INTO `table` (`id`) VALUES (?)");
$statement->bind_param("i", $user_id);
$statement->execute();
You need to bind each of your parameters instead of putting them inline your prepared statement.
You are misusing the prepare() function. When using prepared statements, you are supposed to use either ? or :name as placeholders for your values. This prevents you from constructing a malicious SQL query from user input.
Also, you are listing 5 fields, but only give 4 values. If id is an AUTO_INCREMENT field then it can just be omitted from the query.
Finally, you had too many ) in your query,
$sql = $DB->prepare("INSERT INTO `users`(`firstname`, `lastname`, `email`, `password`)
VALUES (:firstname, :lastname, :email, :password)");
Now you just pass an array of values to execute() to bind to the placeholders.
$sql->execute(array(
'firstname' => $this->firstname,
'lastname' => $this->lastname,
'email' => $this->email,
'password' => $this->password
));
P.S. Your original code didn't work because you forgot to put quotes around your strings.
INSERT INTO `users` (`email`) VALUE ('test#example.com');
Your ID-column does not have a corresponding value to insert, if that column is auto-incrementint you can skip it, like so:
$sql = $DB->prepare("INSERT INTO `users`(`firstname`, `lastname`, `email`, `password`) VALUES ($this->firstname, $this->lastname, $this->email, $this->password))");
you need as many values to insert, as you have columns
An Insert query need to have the same parameters in table fields and values in the same order.
So, if you have id, firstname, lastname, email, password
you need to have idValue, firstnameValue, lastnameValue, emailValue, passwordValue
A good way to try if query is well formed is do an echo $sql or a var_dump($sql) and paste the result on a sql ID query like Mysql Workbench or HeidiSql

PHP PDO execute insert into db not working and dont know why

$q = "INSERT INTO accounts (from_bank, from_user, to_user, amount, date_time, notes) VALUES (:from_bank, :from_user, :to_user, :amount, :date_time, :notes)";
$query = $db->prepare($q);
$result = $query->execute(array(
":from_bank" => $from_bank,
":from_user" => $from_user,
":to_user" => $to_user,
":amount" => $amount,
":date_time" => $date_time,
":notes" => $notes
));
Ok this has been solved (cant answer my own question until level 8 currently im level 6) it was an unrelated line to do with $date_time = 'now()'; it was originally missing single quotes and now it works as it should I cant believe it didnt have any errors even tho I tryed using a try to catch any errors any ideas why this error wasnt caught?
in pdo you don't put single quotes around your parameters:
$q = "INSERT INTO accounts (from_bank, from_user, to_user, amount, date_time, notes) VALUES (:from_bank, :from_user, :to_user, :amount, :date_time, :notes)";
also here's a link to a tutorial you might find very useful:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

Wrong SQL Syntax? [duplicate]

This question already has answers here:
MySQL, safely using reserved word in query [duplicate]
(2 answers)
Closed 9 years ago.
I am building a small Twitter clone for personal use, and I have so trouble with it.
Fist, I want to show you my SQL structure of the table "poke_history":
http://puu.sh/3Sci0.png
This is the command I use to insert the values into a table (in PHP):
$insert = "INSERT INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
This is the annoying error that I am getting:
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 'from, time, reason) VALUES ( '1'' at line 3.
Let me clarify some things.
$to_id is a number.
$from_id is a number.
$time is a number (coming from PHP's time()).
$reason is a text string.
I am using MySQL and PHP5.
Try to quote your column identifiers like
INSERT INTO poke_history (`id`, `from`, `time`, `reason`) ...
Everything inside `` is considered to be a "identifier" not a language keyword. From the SQL-syntax it should be clear that after INSERT INTO tablename cannot come a FROM, but the MySQL sometimes needs this kind of guidance (and other sql parsers, too).
credit to mario as well:
from is a reserved keyword. Use backticks to escape them.
for example
`from`
INSERT INTO table (`from`) ....
So your code would like this:
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
$insert = "INSERT INTO poke_history (`id`, `from`, `time`, `reason`) VALUES (".$to_id.", ".$from_id.", ".$time.", '".$reason."')";
mysql_query($insert) or die(mysql_error());
Numbers don't need to be quoted. Only strings.
Also don't use mysql, it's deprecated. Better use PDO, with prepared statements, to avoid issues like this.
You should try to use prepared statements to prevent SQL injection.
$query = "
INSERT INTO
poke_history (`id`, `from`, `time`, `reason`)
VALUES
(:id, :from, :time, :reason)";
$db = new PDO("mssql:host=sqlserver;dbname=database", "username", "password");
$statement = $db->prepare($query);
$parameters = array(
":id" => $name,
":from" => $from,
":time" => $time,
":reason" => $reason
);
$statement->execute($parameters);
I think that you forgot to add * in between INSERT and INTO, here is the fixed script:
$insert = "INSERT * INTO poke_history (id, from, time, reason) VALUES ('".$to_id."', '".$from_id."', '".$time."', '".$reason."')";
mysql_query($insert) or die(mysql_error());
The reason why you are getting the error is because you are trying to use a built in function name for one of your columns. Say you have the following CREATE TABLE...
CREATE TABLE customers
(
name varchar(80),
streetAddr varchar(160),
"from" varchar(60),
);
Notice that to create the table I had to put the column from in quotes. Now if you wanted to insert a row into this table, your insert statement should look like the following:
INSERT INTO ShoppingFun.dbo.customers
(
name,
streetAddr,
"from"
)
VALUES
(
'MRBubbleGum',
'1061 SW BubbleGumVillage St',
'yourmom'
)

INSERT INTO syntax error but normally should work

I'm repeatedly getting a syntax error when inserting in to mysql, normally this works fine but I can't seem to get it to work. I can echo out the variables no problem but for some reason I can't insert them.
variables (the session vars are brought over from another page)
session_start();
$name=$_SESSION['bName'];
$email=$_SESSION['email'];
$ship_address = $_SESSION['sAddress'];
$voucher=$_SESSION['voucher'];
$sku=$_SESSION['sku'];
$credit_card=$_POST['credit_card'];
$security_code=$_POST['security_code'];
$payment_type=$_POST['payment_type'];
$cc_number=substr($credit_card, 0, 4) . str_repeat('x', (strlen($credit_card) - 4)) . substr($credit_card, -4, 4);
$phone=$_SESSION['billPhone'];
$status="Redeemed";
$date = date('Y/m/d');
$tracking ="";
insert query
//Insert Queries
$sqlInsert = "INSERT INTO `customers`(`name`, `email`, `address`, `phone`, `sku`, `creditcard`, `securitycode`, `paymenttype`, `voucher`, `purchase_id`, `tracking`, `status`, `date_recieved`)
VALUES( $name, $email, $ship_address, $phone, $sku, $credit_card, $security_code, $payment_type, $voucher, $purchase_id, $tracking, $status, $date)";
mysql_query($sqlInsert) or die ('Error Inserting into database' . mysql_error());
I've also tried
VALUES( '$name', '$email', '$ship_address', '$phone', '$sku', '$credit_card', '$security_code', '$payment_type', '$voucher', '$purchase_id', '$tracking', '$status', '$date')
but it doesn't work. The error I get is
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 'lastname, fahad#semail.com, 22 toronto ont l6a0l4, 416-123-4567, 1001234, 1234567' at line 1
Any ideas?
Thanks
all string values must be quoted.
VALUES("'.$name.'", "'.$email.'" ...
Do it like this, so the fields are delimited:
VALUES( '$name', '$email', ...
check your error message to see what kind of garbage you are currently generating.
You could use PDO to create prepared statements instead. Then you won't have to worry about escaping your values like drdwilcox's example 'Jerry''s'. It also helps as a counter measure against SQL Injection attacks.
I would almost guarantee that you have a single-quote in your name field. If you want to place a single quote into a string field in SQL, you must double it: 'Jerry''s'
And you need the '$name' version.

Categories