php - 使用 PHP 和 MYSQL 以单引号传递变量

标签 php mysql pdo

<分区>

我有以下变量要传递给准备语句:$subject。它是使用 PDO 完成的。不幸的是,它在传递时用单引号括起来。例如,我传递了数学,而查询改用“数学”。我已经尝试了其他答案,例如 bindParam、bindValue 以及指定它是一个字符串属性,但是我无法让它工作。如果有人知道出了什么问题,请提前致谢 我的代码在下面。

$query = "SELECT * FROM :subject;";
        $sql = $connection->prepare($query);
        $sql->bindParam(':subject', $subject); 
        try{                
            $sql->execute();
        }catch(Exception $e){
            echo $e;
        }

我收到以下错误:

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 ''maths'' at line 1' in D:\xampp\htdocs\acards\functions.php:18
Stack trace:
#0 D:\xampp\htdocs\acards\functions.php(18): PDOStatement->execute()
#1 D:\xampp\htdocs\acards\getMathsQuestions.php(13): Functions->getFeed('maths')
#2 {main}[]

最佳答案

问题在这里:

"SELECT * FROM :subject;";

bindParamwhere 子句中使用的参数一起使用,而不是表名中使用的参数。

正确的语法是这样的:

$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

Reference

关于php - 使用 PHP 和 MYSQL 以单引号传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44997377/

相关文章:

PHP+MySQL软件

MySQL 匹配 2 个或更多关键字

php - MySQL 查询使用来自不同表的字段的总和计算

Mysql 和 PDO : Insert With Select and Parameter

php - 使用 PDO 使用表单在数据库中存储 html 代码是否安全?

php - 如何在 PHP 中将 Socks5 与 fsockopen 结合使用

php - Codeigniter 下拉值不显示

mysql - 使用流畅的 NHibernate 创建继承时出现问题

PHP MySQL : issue selecting different columns from the same table

php - 抑制消息 "Fatal error: Maximum execution time of 30..."