Bind_param()错误

时间:2014-02-07 11:00:20

标签: php mysqli sqlbindparameter

当我运行我的代码时,我收到以下错误:

Error: Call to a member function bind_param() on a non-object

我现在用谷歌搜索了这个问题几个小时,我无法弄清楚问题出在哪里。我知道这个主题被发布了很多次,但我是php初学者,我不明白为什么这不起作用。

这是我使用的代码:

CLASS:

class Item {
    private $iname;

    function __construct($name)
    {
        $this->iname = $name;
    }

    public function addItem()
    {
        global $mysqli, $db_table_prefix;

            $stmt = $mysqli->prepare("INSERT INTO ".$db_table_prefix."items (
                    iname,
                    VALUES (
                    ?
                    )");
            $stmt->bind_param("s", $this->iname);
            $stmt->execute();
            $inserted_id = $mysqli->insert_id;
            $stmt->close();

    }
}

并发布表单页面:

require_once("models/config.php");


if(!empty($_POST))
    {
        $item_name = trim($_POST["iname"]);

        $item = new Item($item_name);
        $item->addItem();

    }

require_once("models/header.php");
echo "
<body onload='initialize()'>
    <div id='wrapper'>
        <div id='top'><div id='logo'></div></div>
        <div id='content'>
            <h>Add new Item</h>
            <div id='main'>
                <div id='regbox'>
                    <form name='newItem' action='".$_SERVER['PHP_SELF']."' method='post'>
                        <p>
                        <label>Item description:</label>
                        <input type='text' name='iname' />
                        </p>
                        <input type='submit' name='Submit' value='Add Item'/>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>";
?>

1 个答案:

答案 0 :(得分:0)

您有SQL语法错误:

INSERT INTO ".$db_table_prefix."items (
                iname,
                VALUES (
                ?
                )

这应该是:

INSERT INTO ".$db_table_prefix."items (
                iname)
                VALUES (
                ?
                )

由于语法错误,未创建$ stmt对象,因此错误为Call to a member function bind_param() on a non-object

如果您遇到问题,请务必输出MySQL错误消息:

echo $mysqli->error;