search

Home  >  Q&A  >  body text

Learn how to use mysqli prepared statements for database operations

<p>I'm trying to use prepared statements, but the code below doesn't work. I received the following error: </p> <blockquote> <p>Fatal error: Calling non-object member function execute() on line 12 of /var/www/prepared.php</p> </blockquote> <pre class="brush:php;toolbar:false;"><?php $mysqli = new mysqli("localhost", "root", "root", "test"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL:" . $mysqli->connect_error; } $stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)"); //Insert a row $stmt->execute(array('one',1)); // Insert another row with different values $stmt->execute(array('two',1)); ?></pre> <p>Also, do I need to use mysqli for prepared statements? Can anyone point me to an example of a complete prepared statement, including joins, inserts and selects, and error handling? </p>
P粉838563523P粉838563523456 days ago508

reply all(2)I'll reply

  • P粉729436537

    P粉7294365372023-08-25 12:07:07

    You can also use PDO which I prefer. In fact, in your code example, you seem to be confusing PDO and Mysqli.

    $db = new PDO($dsn, $user, $pass);
    $stmt = $db->prepare("INSERT INTO users (name, age) VALUES (?,?)");
    $stmt->execute(array($name1, $age1));
    $stmt->execute(array($name2, $age2));

    Unlike mysqli, you don't need to call a separate bind function, although the functionality is available if you like/want/need to use it.

    Another interesting thing about PDO is named placeholders, which may be less confusing in complex queries:

    $db = new PDO($dsn, $user, $pass);
    $stmt = $db->prepare("INSERT INTO users (name, age) VALUES (:name,:age)");
    $stmt->execute(array(':name' => $name1, ':age' => $age1));
    $stmt->execute(array(':name' => $name2, ':age' => $age2));

    reply
    0
  • P粉348088995

    P粉3480889952023-08-25 09:46:53

    Frommysqli::prepareDocumentation:

    bind_paramDocumentation.

    Right now:

    $name = 'one';
    $age  = 1;
    
    $stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)");
    
    // 绑定参数。我猜测是'string'和'integer',但请阅读文档。
    $stmt->bind_param('si', $name, $age);
    
    // *现在*我们可以执行
    $stmt->execute();

    reply
    0
  • Cancelreply