Jump to content

foreach mysqli INSERT


The Little Guy

Recommended Posts

is there a better way to insert an array into a database? Something that only uses the mysqli_query() function once?

 

 

<?php
foreach($_POST['myArray'] as $val){
     mysqli_query($db,"INSERT INTO dbTable (`column1`) VALUES ('$val')");
}
?>

 

Or, is the above the only way to do it?

Link to comment
https://forums.phpfreaks.com/topic/63358-foreach-mysqli-insert/
Share on other sites

I'd say use the foreach approach. There will be little noticable difference in performance and it's much more readable what you are trying to accomplish. In the applications that depend on true real time processing looking at every line of code for efficiency is important but for most applications readability is a bigger consideration. Write code that looks clean and easy to follow. It will help you debug things more quickly and it will help anyone who comes in after you to maintain the code. This is of course just my opinion... so do as you see best.

Link to comment
https://forums.phpfreaks.com/topic/63358-foreach-mysqli-insert/#findComment-315783
Share on other sites

Errr... I didn't read your foreach statement very well. You don't want to create a loop for each column in the table... just for each row.

 

$query = "INSERT INTO dbtable (field1, field2, field3) VALUES ('$val1', '$val2', '$val3')";

 

Looping through something like the above would be more acceptable.

Link to comment
https://forums.phpfreaks.com/topic/63358-foreach-mysqli-insert/#findComment-315785
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.