-3

This code is supposed to insert the same row multiple times, but with different values stored in $myArray in the sender field:

$sql = ("SELECT contacts FROM Users WHERE username = '$usernametmp' ");
$result = $conn->query($sql)->fetch(PDO::FETCH_COLUMN);
$myArray = explode(',', $result);
$sql = "INSERT INTO Messages (sender,username,timestamp,msgtype) VALUES (('" . implode("','",$myArray) . "'),'$usernametmp',(CURRENT_TIMESTAMP),'8')";

The contacts indeed are there, but I get this error:

Error: SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)

What I think I understand is wrong is that implode would work across multiple cells in the same column, but is there a way I can do this without using a foreach?

pedrorijo91
  • 7,635
  • 9
  • 44
  • 82
Corey Hart
  • 173
  • 1
  • 2
  • 15
  • Don't save CSV in a column http://stackoverflow.com/questions/41304945/best-type-of-indexing-when-there-is-like-clause/41305027#41305027 http://stackoverflow.com/questions/41215624/sql-table-with-list-entry-vs-sql-table-with-a-row-for-each-entry/41215681#41215681 – e4c5 Jan 25 '17 at 09:44
  • Thanks, but I´m not going to use LIKE to query on the array data in this cell. – Corey Hart Jan 25 '17 at 10:12
  • Nope. You need a loop and create a group of `values`. See this answer for reference: http://stackoverflow.com/a/452934/1973588 – Sandyandi N. dela Cruz Jan 25 '17 at 09:43
  • Any clue why there´s -3 in front of my question? I do not see any complaints. – Corey Hart Jan 25 '17 at 21:30

1 Answers1

0

This typically happens when you are trying to insert multiple values at once.

You'll need some kind of loop to insert multiple values (foreach), and loop as many times as rows you need with a ,() for each new value,

e.g.

INSERT INTO myable (id, firstname, lastname, email) VALUES
(1, 'Tony', 'Guy', 'tony@example.com')
,(2, 'Jeff', 'Bloke', 'jeff@exmaple.com')

easy way is have a look at the data you have exploded by doing a dump on it, and see the structure and what you're dealing with, then build a foreach with it

Brian Ramsey
  • 850
  • 7
  • 21