dongxiao1591 2014-02-08 19:52
浏览 28
已采纳

查询适用于mysql但不适用于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 ? in actual values then the query runs successfully but it doesnot in PHP and gives following error:

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.

  • 写回答

1条回答 默认 最新

  • dongtongjian3127 2014-02-08 21:23
    关注

    You can't use ? for table names. In SQL, values look like "value", while table/column names look like `colname` (backtick, not single quote); they're not interchangeable.

    You can use sprintf and manually escape the table name with mysqli_escape_string, ie.:

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路