Tuesday, January 27

mySql using Prepared Statement with php

test.html

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

<?php
    if (isset($_POST['submit'])) {
    
    $mysqli = new mysqli('localhost', 'user', 'password', 'mytestdb');
    
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    
    $stmt = $mysqli->prepare("INSERT INTO table_name VALUES (?)");
    $stmt->bind_param('s', $test);   // bind $test to the parameter
    
    // escape the POST data for added protection
    $test = isset($_POST['test']) ? $mysqli->real_escape_string($_POST['test']) : '';
    
    /* execute prepared statement */
    $stmt->execute();
    
    printf("%d Row inserted.\n", $stmt->affected_rows);
    
    /* close statement and connection */
    $stmt->close();
    
    /* close connection */
    $mysqli->close();
    }
?>

real_escape_string() is superfluous. The whole point of using prepared statements is to avoid having to escape the values manually.

No comments:

Post a Comment