user1868475
user1868475

Reputation: 7

Insert array data using php

I am using form to insert data into SQL.

This is my form:

<form action="insert.php" method="POST">
    Name:<input type="text" name="firstname[]" />
</form>

and this is my PHP code:

<?php

$con = mysql_connect("localhost", "root", "root");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
while ($array = $result->fetch_assoc()) {
    $query = "INSERT INTO test(firstname) VALUES ('{$array['firstname']}')";
    $result = $database->query($query);
}
mysql_close($con);

?>

It shows an error. Any help?

Upvotes: 0

Views: 450

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

To insert POST data in a table, you don't have to first fetch it from database (* this would not exist). So remove some extra code:

<?php

$con = mysql_connect("localhost","root","root");

if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);

$first_name = mysql_real_escape_string($_POST["firstname"]);

$query = "INSERT INTO test (firstname) VALUES ('$first_name')";
$result = mysql_query($query);
mysql_close($con);

?>

And update your HTML so that the field is named firstname and not firstname[].

Edit: mysql_* functions are not really recommended to be used anymore. But I had to answer within your question's requirements.

Upvotes: 1

Related Questions