[英]Query works in mysql but not in PHP
Following is my prepared statement which I am using to make insertion in a table. 以下是我准备在表中插入的准备语句。 When I run the same query in mysql by only changing
?
当我仅通过更改在mysql中运行相同的查询时
?
in actual values then the query runs successfully but it doesnot in PHP and gives following error: 如果使用实际值,则查询将成功运行,但不能在PHP中运行,并出现以下错误:
Call to a member function execute() on a non-object
Kindly let me know what I did wrong: 请让我知道我做错了什么:
$stmt = $con->prepare("
INSERT INTO test_given (
test_id, test_giver, test_completed, dt_created
)
SELECT * FROM (
SELECT ?, ?, '0',NOW()
) AS tmp
WHERE NOT EXISTS (
SELECT test_id FROM test_given WHERE test_id = ? AND test_giver = ?
) limit 1
");
// s means only string input is allowed
$stmt->bind_param("ssss", $qid, $username,$qid, $username);
Note: I echoed $qid, $username and they are getting right values. 注意:我回显了$ qid,$ username,它们得到正确的值。
You can't use ?
你不能使用
?
for table names. 表名称。 In SQL, values look like
"value"
, while table/column names look like ` colname
` (backtick, not single quote); 在SQL中,值看起来像
"value"
,而表/列名看起来像` colname
(反引号,不是单引号); they're not interchangeable. 它们是不可互换的。
You can use sprintf
and manually escape the table name with mysqli_escape_string
, ie.: 您可以使用
sprintf
并使用mysqli_escape_string
手动对表名进行mysqli_escape_string
,即:
$stmt = $con->prepare(sprintf("
INSERT INTO test_given (
test_id, test_giver, test_completed, dt_created
)
SELECT * FROM (
SELECT `%s`, `%s`, '0',NOW()
) AS tmp
WHERE NOT EXISTS (
SELECT test_id FROM test_given WHERE test_id = ? AND test_giver = ?
) limit 1
"), $qid, $username);
// s means only string input is allowed
$stmt->bind_param("ss", $qid, $username);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.