Lydia
Lydia

Reputation: 2117

Insert multiple rows in to table using php

Am trying to insert multiple rows in to table using php:

<?php

$host = "localhost";
$username = "mysql_username";
$password = "mysql_password";
$dbname = "employee";
$con = mysqli_connect($host, $username, $password, $dbname) or die('Error in Connecting: ' . mysqli_error($con));

$st = mysqli_prepare($con, 'INSERT INTO emp(name, gender, designation) VALUES (?, ?, ?)');
// bind variables to insert query params
mysqli_stmt_bind_param($st, 'sss', $name, $gender, $designation);

for ($x = 0; $x <= 3; $x++) {       
    $name = 'tom';
    $gender = 'male';
    $designation = 'developer';
    mysqli_execute($st);
}

//close connection
mysqli_close($con);

?>

But the rows that i want to insert are not saved in database. Are there any mistakes in my code ?

Actually I want the for loop from json array, I just test using for loop for knowing it is worked or not.

Upvotes: 0

Views: 243

Answers (1)

user4990969
user4990969

Reputation:

I think the code is right, but try this:

<?php
$host       = "localhost";
$username   = "mysql_username";
$password   = "mysql_password";
$dbname     = "employee";
$con = mysqli_connect($host, $username, $password, $dbname) or die('Error in Connecting: ' . mysqli_error($con));

$st = mysqli_prepare($con, 'INSERT INTO emp(name, gender, designation) VALUES (?, ?, ?)');

for ($x = 0; $x <= 3; $x++) {

    $name = 'tom';
    $gender = 'male';
    $designation = 'developer';

    // bind variables to insert query params
    mysqli_stmt_bind_param($st, 'sss', $name, $gender, $designation);
    mysqli_execute($st);
}

//close connection
mysqli_close($con);
?>

The mysqli_stmt_bind_param($query, 'is',…) means the first value is an integer (i) and the next value is a string (s). Feel free to adjust to best fit your actual data types.

Upvotes: 1

Related Questions