سؤال

When I run my code I get the following error:

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

I googled for this problem for few hours now and I cant figure out where the problem is. I know this subject is posted to many times but I'm php beginner and I don't see why this is not working.

This is the code I use:

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

    }
}

and posting form page:

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>";
?>
هل كانت مفيدة؟

المحلول

You have an SQL syntax error:

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

This should be:

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

Because of syntax error the $stmt object isn't created, hence the error Call to a member function bind_param() on a non-object.

Always output MySQL error messages if you have problems:

echo $mysqli->error;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top