0

I am trying to add this array into the database correctly. I have 3 input boxes and when I echo $key all my info is there like this Jonesbass23 but when I run code each field gets a new row in the database it doesn't all go into 1 row and the values are going into the wrong columns as well. Also will add my $_POST array dynamically changes based on how many input fields the user wants so my database entries could be multiple. Thought I had a handle on it but guess not. Any help would be appreciated thank you.

    <?php
session_start();
$errmsg_arr = array();
$errflag = false;
require_once 'dbconfig.php';        // Database Connection

//Retrieve data input from addfish.php

$username = $_SESSION['username'];

print_r($_POST);
}

//Returns error message text on screen


if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: addfish.php");
exit();
}

//Insert data into database


$statement = $dbc->prepare("INSERT INTO entries(username, species, length, weight)
    VALUES(:username, :species, :length, :weight)");

foreach($_POST as $key => $data) {

echo $key;
echo $data['species']; // The data of species1, species2, or species3, etc.
echo $data['length'];
echo $data['weight'];


try {
    $statement->execute(array(
        "username" => "$username",
        "species" => $data['species'],
        "length" => $data['length'],
        "weight" => $data['weight']
    ));
}

catch(PDOException $e) {
    echo "Exception caught: $e";
}
} 
?>  

2 Answers 2

1

The problem is that you're executing 1 insert for every key of the $_POST:

foreach($_POST as $key => $value)

So if your field has 3 inputs, your post would look like this:

$_POST => array (
   ['key1'] => 'value1'
   ['key2'] => 'value3'
   ['key3'] => 'value2'
)

And your foreach will perform one insert per every key, that's why you end up with a new row for every key, not to mention that you're inserting only one letter of the $key string: $key[1] will return the second letter of the $key string, for example.

Also, the reason you don't need to loop over $_POST is simply because each key contains a different value, and you can access them normally by $_POST['species'], for example, as FuzzyTree suggests.

Update:

You can group the information of your inputs by naming them as follows:

<input type="text" name="species1[species]" />
<input type="text" name="species1[length]" />
<input type="text" name="species1[weight]" />
<br />
<input type="text" name="species2[species]" />
<input type="text" name="species2[length]" />
<input type="text" name="species2[weight]" />

And so on, so you can loop over them on your php like this:

foreach($_POST as $key => $data) {
    echo $key; // This will print species1, species2, species3, etc.

    echo $data['species']; // The data of species1, species2, or species3, etc.
    echo $data['length'];
    echo $data['weight'];
}

Also, it's suggested that you prepare your statement before and not inside the loop. There's no problem in doing this, but that's the point of using a prepared statement. An example combining both sugestions:

$statement = $dbc->prepare("INSERT INTO entries(username, species, length, weight)
    VALUES(:username, :species, :length, :weight)");

foreach($_POST as $key => $data) {
    try {
        $statement->execute(array(
            "username" => $username,
            "species" => $data['species'],
            "length" => $data['length'],
            "weight" => $data['weight']));

    } catch(PDOException $e) {
        echo "Exception caught: $e";
    }
}
4
  • my $key contains multiple rows of input that change based on how many rows the user adds on their own so $_POST['species'] then next would be $_POST['species2'] ext...
    – Damon
    Commented Jul 21, 2014 at 17:09
  • Then you should group all the pertinent information of species or species two under them, by naming your inputs like species1['field'], species2['field'] and so on, so you can retrieve their info like $_POST['species1']['data'].
    – arielnmz
    Commented Jul 21, 2014 at 17:53
  • Ok I have updated my code at the top. When I use print_r($_POST); it prints my array and all the names and values are correct. When it runs echo $key; I get the correct names species1, species2 ect... but my echo $data['species'] $data['length'] ect.. are blank and it puts null values into my sql database.
    – Damon
    Commented Jul 24, 2014 at 18:44
  • Try removing the quotes surrounding the keys on your HTML forms. e.g. change name="species1['species']" to name="species1[species]".
    – arielnmz
    Commented Jul 24, 2014 at 18:51
0

You have to serialize your array.

Here is the example from the documentation

$sqldata = array (serialize($session_data), $_SERVER['PHP_AUTH_USER']);

Basically it puts your array into a single line, assigns it to a variable and stores it so it can be 'unserialized' later (basically it parses through the characters).

1
  • Bad practice, check 1NF.
    – chrisp
    Commented Jul 21, 2014 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.