查询适用于mysql但不适用于PHP

时间:2014-02-08 19:52:59

标签: php

以下是我准备好的声明,我用它来插入表格。当我在mysql中运行相同的查询时,只更改实际值中的?,然后查询成功运行,但它不在PHP中,并给出以下错误:

Call to a member function execute() on a non-object

请让我知道我做错了什么:

$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);

注意:我回复了$ qid,$ username,他们得到了正确的值。

1 个答案:

答案 0 :(得分:1)

您不能将?用于表名。在SQL中,值看起来像"value",而表/列名称看起来像`colname`(反引号,不是单引号);它们不可互换。

您可以使用sprintf并使用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);