The Little Guy Posted August 4, 2007 Share Posted August 4, 2007 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? Quote Link to comment https://forums.phpfreaks.com/topic/63358-foreach-mysqli-insert/ Share on other sites More sharing options...
BlueSkyIS Posted August 4, 2007 Share Posted August 4, 2007 I use implode. Something like this: "INSERT INTO dbTable ('column1') VALUES ('".implode("'), ('", $_POST['myArray'])."')"; -BSIS Quote Link to comment https://forums.phpfreaks.com/topic/63358-foreach-mysqli-insert/#findComment-315751 Share on other sites More sharing options...
The Little Guy Posted August 4, 2007 Author Share Posted August 4, 2007 Thats not what I'm looking for. I need it to create a new row for each array element. Quote Link to comment https://forums.phpfreaks.com/topic/63358-foreach-mysqli-insert/#findComment-315758 Share on other sites More sharing options...
BlueSkyIS Posted August 4, 2007 Share Posted August 4, 2007 exactly. the result of the implode will be INSERT INTO dbTable ('column1') VALUES ('$val1'), ('$val2'), ('$val3'), etc. There will be one row for each value. Quote Link to comment https://forums.phpfreaks.com/topic/63358-foreach-mysqli-insert/#findComment-315762 Share on other sites More sharing options...
dbo Posted August 4, 2007 Share Posted August 4, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/63358-foreach-mysqli-insert/#findComment-315783 Share on other sites More sharing options...
dbo Posted August 4, 2007 Share Posted August 4, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/63358-foreach-mysqli-insert/#findComment-315785 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.