【问题标题】:PHP script looping stringPHP脚本循环字符串
【发布时间】:2020-02-26 19:41:14
【问题描述】:

我有一个字符串,我需要将此信息放入数据库。

我不确定操作字符串以与插入脚本一起使用的最佳方法。我的技能水平很低。我读过一些关于循环的文章,但不知道如何或从哪里开始。

有没有更好的方法来操作字符串以使数据库插入更容易?

非常感谢

<?php
$date = $_SESSION['date'];
$string="UnAllocated,SUSY MCGRANAHAN,R,null,null;
UnAllocated,BERNADINE WASHER,A,null,null;
UnAllocated,DAVID KEHRER,R,null,null";
/*
I have been trying to break it down in the following way.
$new = preg_split("[;]", $string);

$x1=(explode(',', $new[1]));
$x2=(explode(',', $new[2]));

I would like to insert it into the following table
INSERT INTO table ("date, team, name, driver, car
values
('$date' ,'$x1[0]', '$x1[1]', '$x1[2]', '$x1[3]'),
('$date' ,'$x2[0]', '$x2[1]', '$x2[2]', '$x2[3]')");
*/
Table
|  date |      team     |    name   |  driver  |   car  |
---------------------------------------------------------
|  cur  |  unallocated  |  SUSY..  |     A    |   null |
|  cur  |  unallocated  |  BERN...|     R    |   null |

【问题讨论】:

  • 您的问题到底是什么?
  • $string 你的数据是如何格式化的?提出这个问题的最好方法是向我们展示您拥有的数据是如何格式化的,并向我们展示您想要拥有的表格。然后就很容易将数据放入表中。

标签: php mysql loops for-loop


【解决方案1】:

您可以使用以下代码插入到您的数据库表中。

<?php

$string="UnAllocated,SUSY MCGRANAHAN,R,null,null;
UnAllocated,BERNADINE WASHER,A,null,null;
UnAllocated,DAVID KEHRER,R,null,null";

$arr = explode(';', $string);

foreach($arr as $row){
    $arr_row = explode(',', trim($row)); // Converting each line to array which can be used as values.
    print_r($arr_row);
    // Write your insert statement into your database.
    // e.g INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...); 
}

现在您可以使用 $arr_row[0]、$arr_row[1] ... 等等来构建您的 sql。

【讨论】:

  • 感谢您的回复,我会试一试,让您知道我的进展情况:)
  • 感谢您的代码,我已经尝试将它与插入脚本一起使用,但它只插入第一行而不是以下。
  • 您能说明您是如何将数据插入数据库的吗?
  • require('dbconnect.php'); //db 凭证 foreach($arr as $row){ $arr_row = explode(',', trim($row)); // 将每一行转换为可以用作值的数组。 // 向表中插入数据 $result = mysqli_query($mysqli, "INSERT INTO team (date, team, name)VALUES ('$date_in', '$arr_row[0]', '$arr_row[1]')") ; } header('位置:menu.php');`
  • 哪一行被插入到您的数据库中?请在查询末尾添加分号,例如 mysqli_query($mysqli, "INSERT INTO team (date, team, name)VALUES ('$date_in', '$arr_row[0]', '$arr_row[1]'); ");
猜你喜欢
  • 2010-11-10
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多