Uncaught PDOException: SQLSTATE[42000] - Try to Insert Data - mysql

I read and tried hard for the past two hours to run my code. But i got a syntax error in my sql query, can anyone help me?
My code:
$query = "INSERT INTO `article` (`text`,`headline`,`date`,`author`,`active`) SET (?,?,?,?,?)";
$stmt = $pdo->prepare($query);
$stmt->bindValue(1, $text, PDO::PARAM_STR);
$stmt->bindValue(2, $headline, PDO::PARAM_STR);
$stmt->bindValue(3, $date, PDO::PARAM_STR);
$stmt->bindValue(4, $author, PDO::PARAM_STR);
$stmt->bindValue(5, $active, PDO::PARAM_INT);
if($stmt->execute()) { //do something }
Fatal error:
Uncaught PDOException: 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 'SET ('some text','test headline','2017-09-30','author123',1)'
btw, how can i use php code-tags?
Thanks

Try changing "SET" in your query to "VALUES", your use of "SET" is incorrect in that context.

Your syntax is incorrect. Check the MySQL documentation:
https://dev.mysql.com/doc/refman/5.7/en/insert.html
When using insert query, you use:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);

Related

SQL error text giving me a different value that the actual value

This is the line of code that is causing the error:
$result = $mysqli->query("SELECT * FROM 'accounts'.'users' WHERE email='$email' AND hash='$hash' AND active='0'") or die($mysqli->error);
and this is the error that shows:
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 ''accounts'.'users' WHERE email='testemail#email.com' AND hash='76dc611d6eba' at line 1
However, if I print the value of hash I get this "76dc611d6ebaafc66cc0879c71b5db5c" the value that I want to search with and the value that is stored in the database. I am not sure if it is just being shortened for the error message of if something else is happening.
Try changing from ' (apostrophe) to ` (backtick) or simply removed the single quotes from db/table name, so your query looks like this:
SELECT * FROM `accounts`.`users` WHERE email='$email' AND hash='$hash' AND active='0'
Try removing quotes around database and table name
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$result = $mysqli->query("SELECT * FROM accounts.users WHERE email='$email' AND hash='$hash' AND active='0'") or die($mysqli->error);

Executing a bad PDO query does not yield an error [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
Here is an invalid SQL and I m expecting an error, but the PDO error seems always 00000, what did I do wrong?
<?php
run('select now()');
run('pls give me an error');
function run($sql) {
$pdo = new PDO('mysql:host=localhost;db=mydb', $user, $pass);
echo $sql . "<br>";
$sth = $pdo->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
print_r($row);
print_r($pdo->errorInfo());
}
And here is the result:
select now()
Array
(
[now()] => 2017-10-03 02:58:09
)
Array
(
[0] => 00000
[1] =>
[2] =>
)
pls give me an error
Array
(
[0] => 00000
[1] =>
[2] =>
)
But I have another page running against the same db and get this error:
Err 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
'please give me an error' at line 1
updated
The other page is able to produce error is actually using the following:
$sth = $pdo->query($sql);
print_r($pdo->errorInfo());
For the syntactically or any other way incorrect prepared statements to throw you need to disable prepared statements emulation:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
By default PDO is set up to emulate those, which honestly does not make much sense.
With emulated prepares disabled PDO::prepare() method creates a temporary server-side object that holds a prepared statement then executes it.
Additionally you may want to enable PDO exceptions, that way it's harder to not handle unexpected query failures:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
References:
http://php.net/manual/en/pdo.setattribute.php
I've no idea why errorInfo() sometimes doesn't work but I confirm he behavior.
Given that setting error mode to exceptions always works and given that exceptions are much more useful than manual error checking, this function is useless anyway.
So, change your function this way
function run($pdo, $sql, $params = null) {
$sth = $pdo->prepare($sql);
$sth->execute($params);
return $stmt;
}
$pdo = new PDO('mysql:host=localhost;db=mydb', $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
run($pdo, 'select now()');
run($pdo, 'pls give me an error');
and have your error message first class

Why do I get this SQL syntax error? - Syntax error or access violation: 1064

Why do I get this error: 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 '' at line 1?
<?php
include'model.php';
global $db;
try {
$sql ='SELECT accounts.username '
. 'FROM accounts '
. 'WHERE accounts.username = '
.$_POST[username];
$stmt = $db->prepare($sql);
$stmt->execute();
$navList = $stmt->fetchAll();
$stmt->closeCursor();
header('location: ./view_cms.php');
} catch (PDOException $exc) {
echo $exc->getMessage();
// header('location: ./view_error.php');
exit;
}
?>
Because you need to wrap strings in single quotes in the WHERE clause. You also need to access $_POST entries with a quoted string key:
$sql = "SELECT accounts.username ".
"FROM accounts ".
"WHERE accounts.username = '".$_POST["username"]."'";
Plus, this is the reason why PHP based web software has a bad reputation. Sanitize your inputs, for heaven's sake!! Your prepare statement doesn't do anything as you're not using parameters (your statement is not a prepared statement).

Slim MySQL Exception: SQLSTATE[42000]: Syntax error or access violation: 1064

I'm getting strange error in mysql syntax, non of the posts here helps me.
I'm tring to get next 3 items in table, so I made this function:
$app->get('/items/:id/:nOf', 'getNextItem');
function getNextItem($id,$nOf) {
$sql = "SELECT * FROM `items` WHERE `id` > :id ORDER BY `id` LIMIT :nOf";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(":id", $id);
$stmt->bindParam(":nOf", $nOf);
$stmt->execute();
$item = $stmt->fetchObject();
$db = null;
echo json_encode($item);
} catch(PDOException $e) {
$result = array("status" => "error", "message" => 'Exception: ' . $e->getMessage(),"fnc"=>"getItems($id,$nOf)");
echo json_encode($result);
}
}
End the output is:
{"status":"error",
"message":"Exception: 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 ''3''
at line 1","fnc":"getItems(1,3)"}
I don't see anything wrong. Sql command is working fine in phpmyadmin. Original post on slim forum here.
Try to bind $nOf as an integer:
$stmt->bindParam(":nOf", $nOf, PDO::PARAM_INT);

SQL syntax error/character recogition

when I post something into my html form, for example in the first name field, I enter in:
'John', i am getting the following error:
Error in query: .
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 'Smith',Address_Line_1='rtuy657tr',Address_Line_2='',City='leicester',Postcode='L' at line 1
I know it has something to do with the mysql_real_escape_string () function, but how would I use it for inserting into a the DB. I have started the function:
function db_insert_preparation(){
}
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("project1", $con);
This is where it needs to be used:
$sql2 = "INSERT INTO `".$table_name."` (`Group`, `Date_Of_Birth`, `Gender`, `Title`, `First_Name`, `Last_Name`, `Address_Line_1`, `Address_Line_2`, `City`, `Postcode`, `Contact_No`, `Email`, `Additional_Comment`, `Upload_File`) VALUES ('".db_insert_preparation($group)."','".$_POST[dateofbirth]."','".$_POST[gender]."','".$_POST[title]."','".$_POST[firstname]."','".$_POST[lastname]."','".$_POST[address1]."','".$_POST[address2]."','".$_POST[city]."','".$_POST[postcode]."','".$_POST[contactno]."','".$_POST[email]."','".$_POST[note]."','".$filename."' )";
The SQL insert statement is vulnerable to SQL injection. If one of the POST values contains a double quote " or a newline, the statement gets corrupted and syntax errors ensue. Make sure you escape everything user-provided with mysql_real_escape_string().
use mysql_real_escape_string function on mysql_real_escape_string($_POST[firstname']). Infact do it on all your post variables before you pass it to the SQL.