1

i want to insert my array data to database in one column.

my column in database is id(auto increment) & datas.

here what i try, i get error.

i want my data like this

id(primary)(AI)(INT)           datas(varchar:255)
--------                       ----
       1                       3001182708
       2                       3001182713
       3                       3001183215

im try using this answer https://stackoverflow.com/a/10054725/9661872

$rand_post = ["3001182708", "3001182713", "3001183215", "3001183558", "3001183753"]; 

$prep = array();
foreach($rand_post as $k => $v ) {
    $prep[':'.$k] = $v;
    $sth = $db->prepare("INSERT INTO tes (`datas`) VALUES (" . implode(', ',array_keys($prep)) . ")");
    $res = $sth->execute($prep);
}

Fatal error: Uncaught PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1 in C:\xampp\htdocs\savelink\index.php:23 Stack trace:

0 C:\xampp\htdocs\savelink\index.php(23): PDOStatement->execute(Array) #1 {main} thrown in

C:\xampp\htdocs\savelink\index.php on line 23

Community
  • 1
  • 1
Jazuly
  • 1,374
  • 5
  • 20
  • 43

1 Answers1

3

The problem is because each time you go through the loop you are increasing the size of the preps array, so the second time you are attempting to insert 2 values when only 1 column is specified in the query.

I think this is what you want to do. Basically it forms the entire preps array, then builds the statement from that and executes it.

$rand_post = ["3001182708", "3001182713", "3001183215", "3001183558", "3001183753"]; 

$prep = array();
foreach($rand_post as $k => $v ) {
    $prep[':'.$k] = $v;
}
print_r($prep);
$sth = $db->prepare("INSERT INTO tes (`datas`) VALUES (" . implode('), (',array_keys($prep)) . ")");
$res = $sth->execute($prep);

If you look at $sth and $prep at the end of this, you get

INSERT INTO tes (`datas`) VALUES (:0), (:1), (:2), (:3), (:4)
Array
(
    [:0] => 3001182708
    [:1] => 3001182713
    [:2] => 3001183215
    [:3] => 3001183558
    [:4] => 3001183753
)
Nick
  • 138,499
  • 22
  • 57
  • 95