Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Prepared Statements in Mysql with PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 376
    Comment on it

    Prepared Statement is the feature which allows us to write a set of sql statement in which some fields values are unspecified. The unspecified field are labeled  with the question mark as "?".

    for example :

    INSERT INTO TABLENAME VALUES(?, ?, ?)

     The application binds the value to the parameters and the application can execute the same statement many times and then the database executed the statement.

    lets see how it works,

    INSERT INTO TABLENAME (firstname, lastname, email) VALUES (?, ?, ?)

    the above sql prepared statement binds the value of the columns at the run time this can be done using the bind_param() method as :

    $prepstmt->bind_param("sss", $firstname, $lastname, $email);

    the bind_param() function binds the values of the parameters here the first parameter '"sss" states that the parameters to be bind are the strings only. the argument lists the types of data to be bind in database.

    The argument may be one of four types:

    • i - integer
    • d - double
    • s - string
    • b - BLOB

    the example of the prepared statement is as below :

     

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "";
    $dbname = "myDB";
    
    $con = new mysqli($servername, $username, $password, $dbname);
    
    if ($con->connect_error) {
        die("Connection failed: " . $con->connect_error);
    }
    
    $stmt = $con->prepare("INSERT INTO Example (firstname, lastname, email) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $firstname, $lastname, $email);
    
    $firstname = "Remo";
    $lastname = "Mark";
    $email = "remo@example.com";
    $prepstmt->execute();
    
    $firstname = "Mary";
    $lastname = "Moe";
    $email = "mary@example.com";
    $prepstmt->execute();
    
    
    echo "New records created successfully";
    
    $prepstmt->close();
    $con->close();
    ?>

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: