I am trying to insert using a prepare PDO statement but it doesn't seem to be working how I would like it to be. Heres my code:
$conn = new PDO('mysql:host=localhost;dbname=myDB', $username, $password);
$sql = "INSERT INTO posts (`text`,`name`) VALUES (:text,:username)";
$q = $conn->prepare($sql);
$q->bindParam(':text', $_GET['textField'], PDO::PARAM_STR);
$q->bindParam(':username', $_SESSION['myusername'], PDO::PARAM_STR);
$q->execute();
print_r($q->errorInfo());
The issue is that this doesn't do anything and I am not sure why, I am using following the guidelines here to help me do it.
Edit: When I use print_r I get the following MySQL error:
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 ''text','name') VALUES ('a','user')' at line 1 )
Because text is a type in MySQL (look here), the query fails, because the syntax is wrong.
Add ticks around your text name and try again.
$sql = "INSERT INTO posts (text,name) VALUES (:text,:username)";
----
This is the error.
Related
I am trying to get the UUID that had just been inserted.
This works in phpMyAdmin. But throws an error in PHP.
$insert = $conn->query("
SET #usr_uuid = uuidToBin(UUID());
INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( #usr_uuid );
SELECT HEX(#usr_uuid) AS usr_uuid;
");
However I get this error:
[errno] => 1064
[sqlstate] => 42000
[error] => 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 'INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( #u' at line 3
How do I go about fixing this?
You have two options to do it.
The first of all, are using transactions. For example:
$conn->begin_transaction();
$insert = $conn->query("SET #usr_uuid = uuidToBin(UUID());";
$insert = $conn->query("INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( #usr_uuid );";
$insert = $conn->query("SELECT HEX(#usr_uuid) AS usr_uuid;";
$conn->commit();
This option only works if you're using mysqli and innodb storage engine.
Second option, doing two queries:
$insert = $conn->query("INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( uuidToBin(UUID() );";
$insert = $conn->query("SELECT HEX(usr_uuid) AS usr_uuid FROM `users`;";
This option can fall in the problem of having a new insert while you're doing it. But, if the table users have an ID, you can use mysql-insert-id() as suggested by #user3783243
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 7 years ago.
I'm getting an error with PDO:
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 'key, pseudo, ip, date) VALUES ('mykeyperso', 'mrthebigbosseur', '86.208.78.145',' at line 1 in /home/a1394006/public_html/api/skype.php on line 51
And I don't know why
My source code:
$req = $bdd->prepare('INSERT INTO logs (key, pseudo, ip, date) VALUES (:key, :pseudo, :ip, :date)');
$req->bindParam(":key", $key1, PDO::pARAM_STR);
$req->bindParam(":pseudo", $pseudo1, PDO::pARAM_STR);
$req->bindParam(":ip", $ip1, PDO::pARAM_STR);
$req->bindParam(":date", $date, PDO::pARAM_STR);
$req->execute();
My variable:
$key1 = $_GET['key'];
$pseudo1 = $_GET['pseudo'];
$ip1 = $_SERVER['REMOTE_ADDR'];
$date = $_SERVER['REQUEST_TIME'];
My database: http://prntscr.com/6zjsmd
So if someone can help me plz
Key is a reserved word in mysql. To use it as a column name, wrap it in backticks (`key`). Double quotes would apparently also work in ANSI SQL mode.
Im just new with programming in OOP, so im writing a function but it gives an error, i think im using PDO wrong, actually i now it for sure, but i dont now how to fix it. This is my code im using currently:
public function takedrugs($soort, $hoeveelheid, $id){
$conn = $this->conn;
$drugsophalen = $conn->prepare('SELECT * FROM gebruikers WHERE id=:id');
$drugsophalen->execute(array(':id' => $id));
$result = $drugsophalen->fetch();
$huidigdrugs = $result[$soort];
if($huidigdrugs >= $hoeveelheid){
//Voldoende drugs dus drugs afnemen
$drugsafnemen = $conn->prepare('UPDATE gebruikers
SET :soort = :soort - :hoeveelheid,
WHERE id = :id');
$drugsafnemen->execute(array(
':soort' => $soort,
':hoeveelheid' => $hoeveelheid,
':id' => $id));
} else {
return false;
}
}
So when i use this function i get an error, its all about the SET :soort = :soort - :hoeveelheid.
This is the error i get:
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
MySQL server version for the right syntax to use near ''Cannabis' =
'Cannabis' - '2000', WHERE id ' at line 2' in
I hope there are some people who now how to fix it since i dont :S
Thanks in advance!
You CANT bind column names SEE Complex Cases in PDO info.
Also as Jason states about lazy binding use bindParam OR bindValue
TRY
$drugsafnemen = $conn->prepare('UPDATE gebruikers
SET $soort = $soort - :hoeveelheid,
WHERE id = :id');
$drugsafnemen->bindParam(':hoeveelheid', $hoeveelheid, PDO::PARAM_INT);
$drugsafnemen->bindParam(':id', $id, PDO::PARAM_INT);
$drugsafnemen->execute();
You have two problems:
First, by using execute() all your values are being treated as a string. This results in the syntax error:
UPDATE gebruikers SET field = 'Cannabis' - '2000' ...
I assume this is not your intention. Instead, use bindParam() so you can define these parameters as integers.
$drugsafnemen->bindParam(':soort', $soort, PDO::PARAM_INT);
Second, you should are setting the column name dynamically (:soort). As such, it too is getting interpolated with $soort, which is probably not your intention.
A query executes and writes into a database table and the field data is fetched and displayed in a WHILE loop so basically it works but I get a php error :
Error Inserting!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
With line 1 being
<?php
I have tried playing around with commas and colons but I cannot get rid of the error. This is the query.
$Link = mysql_connect($Host, $User, $Password);
$user = $_SESSION['UserName'];
$query = mysql_query("INSERT INTO films VALUES ('0', '".($user)."','".($formValue["subject"])."',NOW(),'".($usercomments)."','".($formValue["rating"])."','action')");
if(mysql_query ($query, $Link)){
$message = "Thank you for your comments";
header("Location: films.php?message=$message");
}else{
$message = "Error Inserting!" . mysql_error();
header("Location: films.php?message=$message");
$query = "INSERT INTO films VALUES ('0', '$user','$formValue[subject]',NOW(),'$usercomments','$formValue[rating]','action')";
This may simplify the code and solve your error.
i recently started working with PHP and MYSQL, everything was going fine till I starter to get this error. Code works when I insert it into the query window at phpMyAdmin, but it doesnt work inside php code when i open it with a browser. Im already connected to database, so thats not the problem.
this is the error i get:
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 ''fatmam' (user,
messageid) VALUES ('ayihan', '5')' at line 1
try
{
$alicengiz = $_POST['actor'].'m';
$sql = 'INSERT INTO :tablename (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
$s->bindValue(':tablename', $alicengiz);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error 1qqq. '. $e->getMessage();
include 'error.php';
exit();
}
No. You cannot prepare table names, field names and sql keywords.
Problem is, that prepare() will add single quotes around the input, but table names and field names require backticks around them when you want to escape them.
This time you need to escape manually (*real_escape_string doesn't help here):
$sql = 'INSERT INTO `'.addcslashes($alicengiz, "\\'").'` (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
P.s.: but really, this is a bad idea. I'd use a whitelist instead of escaping, because when $_POST["actor"]."m" isn't a table name, a PDOException will be thrown.
How about this?
$alicengiz = $_POST['actor'].'m';
$sql = 'INSERT INTO messages (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
$s->execute();