t4thilina
t4thilina

Reputation: 2197

Sending an array to the database

Hiii... I can get an array from $_POST['C'] to my PHP file. I need to send it to the database. Here I have posted what I tried.

<?

if(!empty($_POST['G'])){

for($i=0;$i<sizeof($_POST['C']);$i++){

var_dump($_POST['C']);

$Query="INSERT INTO Questions(Questions_ID,Question_Name)          VALUES($i+1,'$_POST[C][$i]')";

if(!mysqli_query($con,$Query)){

die("<script>alert( \"Error: ". mysqli_error($con)."\");window.location.href='FormCreationTrial.php';</script>");

} }

}

?>

This is the var_dump of the array. array(3) { [0]=> string(1) "A" [1]=> string(5) "Male2" [2]=> string(7) "Female2" } Notice: Array to string conversion in C:\xampp\htdocs\PHIS\FinalSubmissionOfTheFormPHP.php on line 19. Line 19 is where I have written the query.

When I'm trying to send the array one by one it gives me an error like ' Duplicate entry 'Array[0]' for key 'Question_Name_UNIQUE'. Please someone help me to solve this.

Upvotes: 0

Views: 63

Answers (2)

Tom Tom
Tom Tom

Reputation: 3698

$size = sizeof($_POST['C']) - 1;
for($i = 0; $i < $size; $i++) {

Is better performance wise, so the loop doesn't call sizeOf at each iteration

$Query="INSERT INTO Questions(Questions_ID,Question_Name) VALUES(".($i+1).", '".$_POST[C][$i]."')";

Furthermore you don't seem to generate your id field properly which means you will get duplicate errors. Either set your id on auto generate in the table structure or get the latest id from your table and increment from there. You could also create a trigger to do it but that might be a bit hard for you.

And be warned, your code will be vulnerable to SQL injections.

Upvotes: 1

Ma&#39;moon Al-Akash
Ma&#39;moon Al-Akash

Reputation: 5413

First of all your for statement should be something like (which most probably will solve your issue):

for($i = 0; $i < sizeof($_POST['C']) - 1; $i++) {

Second thing, you don't use "echo" with "var_dump", use "var_dump" alone, so your var_dump line should be something like:

var_dump($_POST['C']);

Hope this helps

Upvotes: 1

Related Questions