简体   繁体   中英

Right way to use mysqli_stmt… with an array

I have an array with thousands of elements. Is this the right way to get it into the database:

$connection = mysqli_connect($url, $usr, $pwd, $db) or die('<br><br>Error: ' . mysqli_error() . "<br><br>");
$stmt=mysqli_stmt_init($connection);
mysqli_stmt_prepare($stmt,"INSERT INTO Bible_KJV (verse) VALUES(?)");


$out .= "<br><hr><br>";
//Inserting the book in the database
for($i = 0;$i < count($lines);$i++) {
    mysqli_stmt_bind_param($stmt,"s",$lines[$i]);
    mysqli_stmt_execute($stmt);
    $versenr = $i+1;
    $out .= "Verse nr.: $versenr was inserted <br>";
}

There's also a bulk insert solution. Provided that php and MySQL share the same filesystem, you could do something like:

$filename=.... /* insert a temp filename here */
$connection = mysqli_connect($url, $usr, $pwd, $db) or die('<br><br>Error: ' . mysqli_error() . "<br><br>");
file_put_contents($filename,implode('\n',$lines));
mysqli_query($connection,"LOAD DATA INFILE '$filename' INTO TABLE `Bible_KJV`");
unlink($filename); // cleanup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM