【问题标题】:Insert array values from comma separated string into mysql将逗号分隔字符串中的数组值插入mysql
【发布时间】:2021-10-17 16:47:11
【问题描述】:

我有这个逗号分隔的数据,其中行由;分隔

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;

还有一个像这样的mysql表:

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

所以我使用此代码将数据从 $_POST 转换为数组:

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

结果:

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] => 
)

所以,我需要使用一列中的时间和另一列中的链接将该数据插入到我的数据库中,尝试了一些示例,但似乎无法找到答案,提前感谢您的帮助。

我尝试使用此查询:

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

但它的错误是:

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

【问题讨论】:

  • 你如何在 mysql 中插入数据。到目前为止,您尝试过什么?
  • 我找到了这个例子,但是它抛出了一个关于数组到字符串转换的错误:$consulta= "DECLARE @array varchar(max) = '($array)' SET @array = REPLACE( REPLACE(@array, ';', '), ('), ', ()', '') DECLARE @SQLQuery VARCHAR(MAX) = 'INSERT INTO hora (hora,link) VALUES ' + @array EXEC (@SQLQuery)";
  • 如果你用你正在使用的代码和你得到的错误更新你的答案会更好
  • 只需遍历数组以生成 INSERT 语句的 VALUES 部分(您可以在 INSERT 中设置多组值),然后执行该部分。你的目标是这种结构INSERT INTO yourtable (colA, colB) VALUES (1, 2), (3, 4), (5, 6)
  • 如果您找到了解决方案,请将其添加为答案。解决方案不是问题的一部分。我会给你几分钟的时间来整理它,然后回滚你的编辑。 stackoverflow.com/help/self-answer 。很高兴你解决了它

标签: php mysql arrays explode


【解决方案1】:

您可以循环遍历$array,然后使用, 分隔符再次分解它。然后您可以运行 MySQL 插入查询来将数据插入到您的表中。

喜欢

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);

}

切记在将用户数据插入数据库之前始终清理用户数据

更新:如果使用 mysqli

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

这将阻止SQL Injection attacks

【讨论】:

  • 我收到解析错误:语法错误,foreach($row in $array){ 行中出现意外标识符“in”
  • 更新了我的答案
  • 这很容易受到 sql 注入的影响。您应该展示一个使用参数和准备好的语句的示例
猜你喜欢
  • 2016-10-13
  • 1970-01-01
  • 1970-01-01
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 2016-09-04
相关资源
最近更新 更多