Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.