OmOiYuMe
OmOiYuMe

Reputation: 13

Insert array values from comma separated string into mysql

I have this comma separated data, where rows are separated by ;

04:03:49,https://foo.bar/1; 04:03:34,https://foo.bar/2; 04:03:24,https://foo.bar/3; 04:03:09,https://foo.bar/4; 04:03:07,https://foo.bar/5; 04:03:07,https://foo.bar/6; 04:02:41,https://foo.bar/7;

And a mysql table like this one:

time link
04:03:49 https://foo.bar/1
04:03:34 https://foo.bar/2

So im using this code to convert the data from $_POST to array:

$data=@$_POST['array'];
$array=explode(';', $data);

That results in:

Array ( 
  [0] => 04:03:49,https://foo.bar/1 
  [1] => 04:03:34,https://foo.bar/2 
  [2] => 04:03:24,https://foo.bar/3 
  [3] => 04:03:09,https://foo.bar/4 
  [4] => 04:03:07,https://foo.bar/5 
  [5] => 04:03:07,https://foo.bar/6 
  [6] => 04:02:41,https://foo.bar/7 
  [7] => 
)

So, i need to insert that data into my db using the time in one column and the link in the other, been trying a few examples but can't seem to find the answer thanks in advance for the help.

I tried using this query:

$consulta= "DECLARE @array varchar(max) = '($array)'
SET @array = REPLACE( REPLACE(@array, ';', '), ('), ', ()', '')
DECLARE @SQLQuery VARCHAR(MAX) = 'INSERT INTO hora (hora,link) VALUES ' + @array
EXEC (@SQLQuery)";

But it errors with:

Warning: Array to string conversion in C:\xampp8\htdocs\plantas\index.php on line 138

Upvotes: 1

Views: 1539

Answers (1)

Mohammad Qasim
Mohammad Qasim

Reputation: 186

You can just loop over the $array and then explode it again using , separator. Then you can run MySQL insert query to insert the data in your table.

Like

foreach($array as $row){
  $data = explode(',', $array);
  //Run MySQL query here to insert this data in your table
  $sql_query = "INSERT INTO hora (hora,link) VALUES ('".$data[0].'", '".$data[1].'") ";
 //Something like 
  $mysqli->query($sql_query);

}

Remember to always sanitize user data befor inserting it in database

Update: if using mysqli

$query = $mysql->prepare("INSERT INTO hora (hora,link) VALUES (?, ?)");
$query->bind_param("ss", $data[0], $data[1]);
$query->execute();

This will prevent SQL Injection attacks.

Upvotes: 1

Related Questions