Log in

View Full Version : insert multiple rows via a php array into mysql



sniperman
07-22-2009, 01:10 AM
I have a script that generates an array of 20 values (a string value, not an array yet) and passes these via the POST method to PHP.

HTML

<input name="player1" type="text" id="player1"
value="30, this, that, another, 203, 11, 13, 2, 8, 17, 14,
19, 17, 13, 15, 18, 20, 6, 15, 15," />

This is processed in PHP

<?php
$player1 = check_input($_POST['player1']);
?>


I need to insert those into MySQL as an array and i guess it should look something like this

mysql_query ("INSERT INTO `Player`
(value1, value2, value3, value4, value5, value6, value7, value8, value9, value10,
value11, value12, value13, value14, value15, value16,
value17, value18, value19, value20) VALUES ('$player1')")

or die(mysql_error());

but it doesn't work.
I read on another forum the implode() explode() methods in PHP deal with turning string variables to arrays, and I could use those converted arrays in such a way???



$player001 = explode (',' $player1); // this creates an array delimited by commas ... i think???

mysql_query ("INSERT INTO `Player`
(value1, value2, value3, value4, value5, value6, value7, value8, value9, value10,
value11, value12, value13, value14, value15, value16, value17, value18,
value19, value20) VALUES ('$player001[0]', '$player001[1]',
'$player001[2]'), '$player001[3]'), '$player001[4]'), '$player001[5]'),
'$player001[6]'), '$player001[7]'), '$player001[8]'), '$player001[9]'),
'$player001[10]'), '$player001[11]'), '$player001[12]'), '$player001[13]'),
'$player001[14]'), '$player001[15]'), '$player001[16]'), '$player001[17]'),
'$player001[18]'), '$player001[19]')")

or die(mysql_error());

does anyone know how to implement PHP's explode() properly??

forum_amnesiac
08-06-2009, 12:23 PM
I don't know if you've solved this yet but here is how to use the PHP explode function in your example.


$player01 = explode(", ", $player1);

mysql_query ("INSERT INTO `Player`
(value1, value2, value3, value4, value5, value6, value7, value8, value9, value10,
value11, value12, value13, value14, value15, value16, value17, value18,
value19, value20) VALUES ('$player01[0]', '$player01[1]', etc....)

I have used ", " in the explode line because that is how you are currently separating the values in your HTML.

Hope this helps