[英]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:还有一张 mysql 这样的表:
time时间 | link关联 |
---|---|
04:03:49 04:03:49 | https://foo.bar/1 https://foo.bar/1 |
04:03:34 04:03:34 | https://foo.bar/2 https://foo.bar/2 |
So im using this code to convert the data from $_POST to array:所以我使用这段代码将数据从 $_POST 转换为数组:
$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
You can just loop over the $array
and then explode it again using ,
separator.您可以只遍历$array
,然后使用,
分隔符再次分解它。 Then you can run MySQL insert query to insert the data in your table.然后您可以运行 MySQL 插入查询以将数据插入到您的表中。
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更新:如果使用 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 .这将防止SQL 注入攻击。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.