Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to insert multiple records into MySQL Using MySQLi/PDO

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 315
    Comment on it

    Here we will learn how to insert multiple records into MySQL Using MySQLi/PDO using the mysqli_query()/exec function in MySQLi and PDO respectively.The examples below insert two new records to the "Employee" table:


    For example:

    MySQLi mode
    
    <?php
    $server_name = "localhost";
    $user = "root";
    $pass = "123456";
    $db = "testdb";
    
    // Here we are creating a  connection
    $con = new mysqli($server_name, $user, $pass, $db);
    // Checking the connection
    if ($con->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sqlquery = "INSERT INTO Employee (fname, lname, email,city,state)
    VALUES ('ajay', 'kumar', 'ajay@yopmail.com','haridwar','Uttarakhand');";
    $sqlquery .= "INSERT INTO Employee (fname, lname, email,city,state)
    VALUES ('sanjeev', 'Singh', 'sanjeev@yopmail.com','dehradun','Uttarakhand');";
    
    if ($conn->multi_query($sqlquery) === TRUE) {
        echo "Created a record successfully";
    } else {
        echo "Error: " . $sqlquery . "<br>" . $con->error;
    }
    $conn->close();
    ?> 
    

    PDO mode example:

    <?php
    $server_name = "localhost";
    $user = "root";
    $pass = "123456";
    $db = "testdb";
    
    try {
        $con = new PDO("mysql:host=$server_name;dbname=$db", $user, $pass);
        // setting the error in PDO mode for any exception
        $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        // starting the transaction
        $con->beginTransaction();
        // SQL statements
        $con->exec("INSERT INTO Employee (fname, lname, email,city,state)
        VALUES ('ajay', 'kumar', 'ajay@yopmail.com','haridwar','Uttarakhand')");
        $conn->exec("INSERT INTO Employee (fname, lname, email,city,state)
        VALUES ('sanjeev', 'Singh', 'sanjeev@yopmail.com','dehradun','Uttarakhand')");
    
        // committing the transaction
        $con->commit();
        echo "Successfully created new records";
        }
    catch(PDOException $e)
        {
        // roll back the transaction on any failure
        $con->rollback();
        echo "Error: " . $e->getMessage();
        }
    $con = null;
    ?> 
    

 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: