Prepare synatax error SQLSTATE[42000] [duplicate] - php

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 9 years ago.
$tconn = new PDO('mysql:host='.WW_HST.';dbname='.WW_DB, WW_USR, WW_PS);
$res = $tconn->prepare('SELECT * FROM :tbl');
$res->execute(array(':tbl'=>"ugb"));
When I use this code to draw data from the 'ugb' table, I get the following error:
'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 ''ugb'' at line 1'
So it's correctly substituting :tbl for 'ugb' but whether I do a bind or just execute with an array, I always get an error. It works fine if I just do SELECT * FROM ugb though.
How can I correct this problem?

PDO does not allow you to set variables in FROM.
You only could add table name in query string.
I usually do by this way:
$allowedTables = array('first', 'second', 'third');
if(in_array($tblName, $allowedTables)) {
$$res = $tconn->prepare("SELECT * FROM $tblName");
}

I don't think that PDO will allow you to bind a parameter to the FROM statement. You could try manualy escaping the table name parameter and after that adding it to the query like this:
$table = "ugb";
$tconn = new PDO('mysql:host='.WW_HST.';dbname='.WW_DB, WW_USR, WW_PS);
$res = $tconn->prepare('SELECT * FROM '. $tconn->quote($table));
$res->execute();
Hope this helps.

Related

How to save a fcolumn with "/" using CakePHP Table save method? [duplicate]

This question already has answers here:
how to add ` character to sql queries in cakephp 3
(2 answers)
Closed 4 years ago.
Here is my code:
$conn = \Cake\Datasource\ConnectionManager::get('default');
$conn->logQueries(true);
$entities[] = $this->patchEntity($entity, $insertData);
$this->saveMany($entities);
And its generating the following insert header:
INSERT INTO aneel_sdi_razao_sintetico (Ide_RO_Sintetico, Cd_ODI, Cd_SubODI, Txt_Desc_ODI, Nr_TI, Txt_Tipo_Obra, Txt_Class_Obra, Vl_UC/UAR, Vl_COM, Vl_Proj_ST, Vl_Mont_ST, Vl_Frete_ST, Vl_Fis_ST, Vl_Sup_ST, Vl_Ger_ST, Vl_Proj_MOP, Vl_Mont_MOP, Vl_Frete_MOP, Vl_Fis_MOP, Vl_Sup_MOP, Vl_Ger_MOP, Vl_Tot_CA, Vl_JOA, Vl_Outros, Vl_Tot_Proj, Dt_Ini_Proj, Dt_Energ, Dt_Uniti, Pct_OE, txt_PLPT_OE, txt_Doa_OE, txt_Incor_OE, Nr_Fases, SDI_importacoes_id) VALUES ...
And the following 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 '/UAR, Vl_COM, Vl_Proj_ST, Vl_Mont_ST, Vl_Frete_ST, Vl_Fis_ST, Vl_Sup_ST, Vl_Ger_' at line 1
The problem is the field "Vl_UC/UAR" must have this "/" and i don't know how to place the "`" character to make the MySQL accept it.
Someone know how to make it work?
If a column contains a / it needs to be quoted and the backtick is an subshell in PHP so:
\`Vl_UC/UAR\`
However its probably easier to rename the column.

PDO Exception when DESCRIBE table [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 4 years ago.
I am getting the 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 "mytable" at
line 1
When I call the below function using
$fields = Table::getFieldsForTable('mytable');
If I hard-code :t to my table name, then the code executes fine.
public static function getFieldsForTable ($table ) {
$sql = 'DESCRIBE :t';
try {
/**
* #var $db \PDO
*/
$db = static::getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':t', $table, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (\PDOException $e){
echo "PDO ERROR" . $e->getMessage();
}
}
I have used the same code snippet over and over in other parts of the project, but I am failing to see what I have done wrong here.
Any help?
Simply because table or column names cannot be replaced by parameters in PDO - it's just a fundamental restriction in the way it works.
See answers to duplicate question:
Can PHP PDO Statements accept the table or column name as parameter?
https://stackoverflow.com/a/15990488/180733
is an excellent explanation.
If you are concerned about the security of accepting an arbitrary table name, consider an up-front fetch of all table names using SHOW TABLES, and then validate the proposed table name against that list, using in_array ($table, $tables).
bindValue with PDO::FETCH_ASSOC quotes the string as if it's a value you'd use for insert or select etc. Just concat the string
$sql="DESCRIBE ".$table;.
For security develop a regex that detects only valid table names, e.g. something like this
preg_match('/^[a-zA-Z]{1}[a-zA-Z_]{1,18}$/',$table);
Or match against a whitelist, e.g. array of accepted tables

I try to make INSERT WHERE in SQL, but it gives me an 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.
When I try to insert data where with code:
$query = dbConnect()->prepare("INSERT INTO users(key) WHERE mail='$mail' VALUES ('$key')");
I'm using XAMPP, it gives me an 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 'key) WHERE mail='maciej#localhost' VALUES (key)' at line 1 in C:\xampp\htdocs\PHP7_login\restore\index.php:38
You should use backticks for key (because is a reserved word)
and not use where
"INSERT INTO users(`key`) VALUES ('$key')"
or if you need an update
"UPDATE users
set `key` = '$key'
where mail = '$mail'"
The guess is that you want update:
update users
set key = '$key'
where mail = '$mail' ;
You should also learn to use parameters for values in queries. Substituting strings into the query string introduces the possibility of unexpected errors and makes the code vulnerable to SQL injection attacks.

SQL throwing Syntax Error when using LIKE with Parameters [duplicate]

This question already has answers here:
How do I create a PDO parameterized query with a LIKE statement?
(9 answers)
Closed 6 years ago.
I am using PDO with PHP to submit queries to my SQL server. I need to use the LIKE clause to check a username to ensure that it is allowed (eg; it does not contain any banned words), so I am using this SQL query...
SELECT * FROM `table` WHERE (`name` LIKE %?%);
I am then inserting the paramater with PDO later like this...
$statement->bindParam(1, $username)
When I try to run this, 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 '%'dibdibs'%)' at line 1' in C:\xampp\htdocs\scripts\sql.php:57 Stack trace: #0 C:\xampp\htdocs\scripts\sql.php(57): PDOStatement->execute() #1 C:\xampp\htdocs\api\users.php(30): dibdibs\pdo->query('SELECT * FROM `...', Array) #2 {main} thrown in C:\xampp\htdocs\scripts\sql.php on line 5
The PDO code works fine for other queries, when I am using = instead of LIKE, but is is throwing the above error when I try to use the LIKE clause.
I have put my full code on Pastebin, if you need to check it. I am using GET to get data, as I am using this with AJAX (which is also working fine), but the username I have tried is 'dibdibs', which works fine in other queries.
Use This
U can use any of these two
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('%value%'));
while ($results = $query->fetch())
{
echo $results['column'];
}
// without loop
$query = "SELECT * FROM tbl WHERE address LIKE ?";
$params = array("%$var1%");
$stmt = $handle->prepare($query);
$stmt->execute($params);

Using question mark instead of table name in PDO prepared statements [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 9 years ago.
I need to know can I use question marks (?) in PDO prepared statements as table name or not.
$table = $_POST['table'];
$id = $_POST['id'];
$sql = "UPDATE ? SET priority = priority + 1 WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($table,$id));
I'm getting this error:
Warning: PDO::prepare() [pdo.prepare]: 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 '? SET priority = priority + 1 WHERE id = ?'
Aside from that simple problem, there is another one - your code smells of bad database design. In a properly planned database you would never need to receive a table name via POST request.
Most likely you are using multiple tables where you have to use only one.
You need to bind the parameters like this:
$q->bindParam(1, $table);
$q->bindParam(2, $id);
Source (see Example #2)

Categories