how to insert into mysql using Prepared Statement

2019-01-11 10:15发布

问题:

This question already has an answer here:

  • How can I prevent SQL injection in PHP? 28 answers

So I am just learning about databases and I want to be able to store user inputs. Can someone give me 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

回答1:

sample.html

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

sample.php

<?php

if (isset($_POST['submit'])) {

    $mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb');

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    $stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)");
    $stmt->bind_param('s', $sample);   // bind $sample to the parameter

    $sample = isset($_POST['sample'])
              ? $_POST['sample']
              : '';

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

    printf("%d Row inserted.\n", $stmt->affected_rows);

    /* close statement and connection */
    $stmt->close();

    /* close connection */
    $mysqli->close();
}

?>

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