php - 在 PDO 中使用 where 选择使用 php mysql

标签 php mysql pdo

我正在尝试在 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/

相关文章:

mysql - mysql 中的计数和不同(表中的逗号分隔数据)

mysql - 在nodejs中使用现有的mysql模式

php - 使用 PDO 的 PHP 查询未插入 MySQL

javascript - 我们如何在 jQuery/php/mySQL 中显示最近的通知?

php - Azure 网站中的 PDO 语句与应用程序内的 MySQL

javascript - 无法参数化链接并以 href 形式给出提到的框架位置

php - 使用 kohana 策略的 SEO 网址

php - 将 laravel 文件迁移到 xampp 服务器时出错

php - 如何在 Laravel 单元测试中避免 ThrottleRequestsException?

mysql - SQL中查找每个group by中第N个值对应的行