Search code examples
phpmysqli

How to insert into MySQL using mysqli


I am just learning about databases and I want to be able to store user inputs. What would be a basic example on how to get form data and save it to a database using PHP?

Also making the form secure from SQL attacks.


Solution

  • 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.