0

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.

2

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.