insert all records in a single query does not work

100 Views Asked by At

I'm wondering why the following PHP Code does not insert values into database? I'm trying to insert ten datasets into a table with one execution (=multiple rows in single query), but after execution, the table is still empty.

<?php
include ("credentials.php");

# Create Data
$fname2 = 'J';
$lname2 = 'M';

$values = array();
for($j = 1; $j<=10; $j++) {
    $values2 = array($fname2, $lname2);
    $values = array_merge($values,$values2);

    $fname2 .= 'O';
    $lname2 .= 'A';
}

# Create SQL
$qry = 'INSERT INTO 02_Experiment (FirstName, LastName) VALUES ';
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?)";
echo "<b>SQL:</b> " . $qry . "<br>"; 
# This ECHO gives:
# INSERT INTO 02_Experiment (FirstName, LastName) VALUES (?,?), (?,?), (?,?), (?,?), (?,?), (?,?), (?,?), (?,?), (?,?), (?,?)


# Database insert
$stmt2 = $mysqli->prepare($qry);

echo "<h1>Examine Array Values:</h1><br>";
echo "<pre>\n"; print_r($values); echo "</pre>\n";
echo "<br>";
echo "<pre>\n"; var_dump($values); echo "</pre>\n";


# Execution
$stmt2->execute($values);

echo "End of PHP<br>";
?>

The database table consists of three rows: id (primary key, int(10), FirstName (varchar(300)), LastName (varchar(300)). The PHP script does not show any errors. I do not find my bug why the database table is still empty after execution.

1

There are 1 best solutions below

0
On

Your syntax and usage would be correct if you were using PDO. Mysqli doesn't support binding in the execute function so:

$stmt2->execute($values);

is incorrect. You will need to use, bind_param, or switch to a PDO connection.