i am trying to write a function in php and mysql to select values from PHP and mysql using PDO
function getRec($id=0)
{
($id==0?$addQuery="":$addQuery=" where id =".$id);
$statement = $dbh->prepare("select * from TCMS :name order by id");
$statement->execute(array(':name' => $addQuery));
$row = $statement->fetchAll();
return $row ;
}
i got 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
MySQL server version for the right syntax to use near ” where id =2′
order by id’ at line 1′ in /Applications/XAMPP/xamppfiles/htdoc
actually what i am trying
if value (2) of ID is passed then statement will be
select * from TCMS where id=2 order by id
And if ID=0 then select statement will be
select * from TCMS order by id
i am new to PDO and not sure of exact syntax.
how to do this ?
Do this instead:
What you’re doing wrong is you’re attempting to bind and execute the SQL with the placeholder as arbitrary string values, which is not what the placeholder is for.
The placeholder is to be set in the place of the value (not table names or anything else) so that the value when passed in during execution will be properly handled by PDO internally for the correct escaping.
The function I wrote should help to create valid SQL.