Placeholder variable for table name in fetchAll function - php

I have a function in PHP that uses a SELECT SQL query.
I using placeholder variable (?) in the query like this. (this placeholder is for table name in mysql database):
protected function _fetchPreviousShiftData($table, $report_time)
{
$query = "SELECT * FROM ? WHERE report_date=? and shift=?";
$previousShiftData = $this->_getDbConnection()->fetchAll($query,array($table, date("Y-m-d"), $this->_shiftValue($report_time, 8)));
return $previousShiftData;
}
but I have an error in $table variable, how should I use "?" for $table variable?
The error is like this:
PHP 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 ''adsl_support' WHERE report_date='2013-04-06' and shift='18-2'' at line 1' in C:\php_shared_lib\Zend\Db\Statement\Pdo.php:228

You can't use this for table name or fields names...
Only for passed values...
You can make a list of the possibles table names,
check it and build query with
"SELECT FROM `$table`..."
if check passed

Related

Syntax error or access violation: 1064 in code [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 having problems running a PDO execute and returns an error in MySQL syntax.
The code is as follows:
try {
global $connect;
$arr = array(':ranked' => $db_rank, ':tier' => $db_tier, ':id' => $_SESSION['user_id']);
$query = $connect->prepare('UPDATE users SET :ranked = :tier WHERE id = :id');
$query->execute($arr);
} catch (PDOException $e) {
echo $e->getMessage();
}
where $db_rank returns a string with the column name(conversion from json) and $db_tier returns a joined string(again conversion from json).
It is inside a loop that should update 1-3 columns, but upon execution an exception is thrown:
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 ''<column name1>' = '<value1>' WHERE id = '3'' at line 1
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 ''<column name2>' = '<value2>' WHERE id = '3'' at line 1
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 ''<column name3>' = '<value3>' WHERE id = '3'' at line 1
It should probably be because of the passing of the table column as a variable, in which case how should I proceed to loop it with 3 different pre-set table names without making it spaghetti code ?
Found my answer:
Should prepare the statement with " and not with ' because inside the array the type changes 3 times(once from function, once from passing and once from PREPARE statement). The variables themselve are const and are fetched using a whitelist already(upon decoding from the json request).

$sql="SELECT * FROM billing ORDER BY billing_no limit :go,5";$stmt = $db->prepare($sql);$stmt ->execute(array(':go'=>$go));

Im just trying for pagination in one of my project and I am getting an error like this
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 MySQL server version for the right syntax to use near ''0',5' at line 1
Please Help me..
You get this error because $go parameter is being inserted as string rather than int.
I recommend to bind parameters before execute. You can do it like this:
$stmt->bindParam(':go', $go, PDO::PARAM_INT);

SQLState error when binding parameters

Today I got an unusual response when trying to make a few queries, here is the error output.
[17-Feb-2014 12:37:24 America/Denver] PHP Warning: 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 = 'AH3D'' at line 1 in file on line 28
Here is the code I was using, this is how i've always done it.
public function get($key = null) {
$get = $this->conn->prepare("SELECT url FROM urls WHERE key = :get");
$get->execute(array(':get' => $key));
return $get->fetch();
}
How I call the function.
echo $tiny->get($_GET['key']);
Key is a mysql reserved keyword you need to use back-ticks arround your columns name key
$get = $this->conn->prepare("SELECT url FROM urls WHERE `key` = :get");
Mysql Reserved Words

MYSQL IN Clause error

I have used the below code in mysql query:
$all_PIDs=array();
foreach($pID as $p)
{
$all_PIDs[]=$p->ID;
}
$AIDS=implode(',',$all_PIDs);
$table_tsk = new Timesheets_Table_Tasks();
$select_tsk = $table_tsk->select()
->from($table_tsk, array
(
'Total'=>'SUM(timesheets_tasks.Time)',
'Charged'=>'SUM(timesheets_tasks.Time_Charged)'
))
->where('timesheets_tasks.ProjectID IN ('.$AIDS.')')
;
But using the above code I am getting the following error:
"An error has occured
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"
I have added a quotation mark(") for IN clause. But the problem is the query only displays for the first $AIDS number. Could someone help me to clear the error?
Thanks!
It should be specified as:
->where('timesheets_tasks.ProjectID IN (?)', $all_PIDs)
so you're passing an array of integers, not the comma-separated list of it
On your codes the quotes are not part of your MySQL query but only your PHP portion. DO this
$AIDS= "'".implode("','",$all_PIDs)."'";
And then
>where('timesheets_tasks.ProjectID IN ('.$AIDS.')'

Prepare synatax error SQLSTATE[42000] [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.
$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.

Categories