How to insert into MySQL using mysqli

File sample.html

<form action="sample.php" method="POST">
    <input name="name" type="text">
    <input name="text" type="text">
    <input name="submit" type="submit" value="Submit">
</form>

File sample.php

<?php

if (isset($_POST['submit'])) {
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb');

    // replace every piece of data in SQL with question mark 
    $sql = "INSERT INTO SampleTable (name, text) VALUES (?,?)"
    //                                  2 question marks ^^^
    // prepare this query
    $stmt = $mysqli->prepare($sql);
    // bind every variable, adding s for each to the types string
    $stmt->bind_param('ss', $_POST['name'], $_POST['text']);
    //     2 s letters ^^        ^^   2 variables   ^^

    /* Execute prepared statement */
    $stmt->execute();
}

This is a very basic example. Many PHP developers today are turning to PDO. Mysqli isn’t obsolete, but PDO is much easier, IMHO.

Leave a Comment