我正在尝试在 php 和 mysql 中编写一个函数,以使用 PDO 从 PHP 和 mysql 中选择值
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 ;
}
我有错误
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
其实我在尝试什么
如果传递了 ID 的值 (2),则语句将是
select * from TCMS where id=2 order by id
如果 ID=0 那么 select 语句将是
select * from TCMS order by id
我是 PDO 的新手,不确定确切的语法。
如何做到这一点?
最佳答案
改为这样做:
function getRec($id=0)
{
//($id==0?$addQuery="":$addQuery=" where id =".$id);
if ($id == 0)
{
$statement = $dbh->prepare("select * from TCMS order by id");
$statement->execute();
}
else
{
// Notice the SQL string has changed. Placeholder :name now properly takes the place of a SQL value.
$statement = $dbh->prepare("select * from TCMS where id = :name order by id");
$statement->execute(array(':name' => $id));
}
$row = $statement->fetchAll();
return $row ;
}
您做错的是您试图将占位符作为任意字符串值来绑定(bind)和执行 SQL,这不是占位符的用途。
占位符将被设置在值的位置(不是表名或其他任何东西),以便在执行期间传入的值将由 PDO 在内部正确处理以进行正确的转义。
我编写的函数应该有助于创建有效的 SQL。
关于php - 在 PDO 中使用 where 选择使用 php mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331441/