user3536315
user3536315

Reputation: 17

Array is storing one character in each field PHP

I have a form

<form action="inserir.php" method="POST">
<tr>
<td><INPUT type='checkbox' name='chk'/></td>
<td><input type='text' name='ppdata[$x]'/></td>
<td><input type='text' size='40' name='ppempresa[$x]'></td>
<td><input type='text' name='ppfuncao[$x]' size='40'></td>
</tr>`
</form>`

In my code, the user can insert more rows to the table, insert data and send it to a new file (insert.php)

foreach ($_POST["ppdata"] as $dat){
echo $dat. ' ';
}

foreach ($_POST["ppempresa"] as $empresa){
echo $empresa. ' ';
}

foreach ($_POST["ppfuncao"] as $funcao){
echo $funcao. ' ';
}



$data = count($dat);
$emp = count($empresa);
$func = count($funcao);


if($data == $emp){
  for($x = 0; $x < $emp; $x++){
    $str[] = "('{$dat[$x]}','{$empresa[$x]}','{$funcao[$x]}','{$id}')";
  }
  $s = implode(',',$str);
   $sql = mysql_query("INSERT INTO pp (data,empresa,descricao,id_user) VALUES $s;");
}

The array i'm seng only saves one char per field. if i do:

echo '$dat';

It'll echo the whole array.

If i do this:

echo '$dat[0]';

It'll only show the first letter of the string. If i write 'Hello' on the input, It will only show 'H'.

EDIT: I need to insert data in the database, depending on how much rows the user adds. but right now, the array only inserts the last letter of the last word of each field.

Upvotes: 0

Views: 323

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

Let's look at what happens when you write "Hello".

The following POST array is sent:

$_POST = array(
    "ppdata" => array(
        "Hello"
    )
);

Now, you run this:

foreach ($_POST["ppdata"] as $dat){
echo $dat. ' ';
}

At this point, $dat is equal to "Hello".

Notably, $dat is a string. This means that $dat[0] is the first character of the string, namely "H". That is how accessing a string as an array of characters works.

You probably meant to use $_POST['ppdata'] everywhere you used $dat (in count, in the loop etc.) as this is your array.

Upvotes: 4

Related Questions