Forum Moderators: coopster

Message Too Old, No Replies

insert multiple rows

         

skoff

1:44 am on Aug 30, 2011 (gmt 0)

10+ Year Member



Hi!
I have a code here that is working well but the thing is that it only works if i have one field. If i try with two fields like this code it will only insert the image field well. In my description field it always insert array.
<?PHP
include("connect.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
if(!$link) die ('Could not connect to database: '.mysql_error());
mysql_select_db($db_name,$link);



if(isset($_REQUEST['store']))
{
$description = $_POST['description'];
foreach($_POST['image'] as $key => $image) {
$query = mysql_query("INSERT INTO albums (image, description) VALUES ('{$image}','{$description}')");
}
}

mysql_close($link);
?>

<form action="formtest.php" method="post">

<input type="text" name="image[]" value="">Image1
<input type="text" name="image[]" value="">Image2<br>
<input type="text" name="description[]" value="">desc1
<input type="text" name="description[]" value="">desc2<br>
<input type="submit" name="store" value="Submit">

</form>

lostdreamer

7:38 am on Aug 30, 2011 (gmt 0)

10+ Year Member



ok, you're looping through your image array, but in the loop you use the variable for the descriptions, which is still an array....

Try this:


foreach($_POST['image'] as $key => $image) {
$query = mysql_query("INSERT INTO albums (image, description) VALUES ('{$image}','{$description[$key]}')");
}


Also, if you're planning to use this live, you should do something about the "sql injection" vulnerability you have in here.... (look it up in google)

This should do:

foreach($_POST['image'] as $key => $image) {
$query = mysql_query("INSERT INTO albums (image, description) VALUES ('". mysql_real_escape_string($image)."','". mysql_real_escape_string($description[$key])."')");
}

skoff

4:20 pm on Sep 18, 2011 (gmt 0)

10+ Year Member



Thanks a lot lostdreamer :)