首页 > 解决方案 > PHP脚本循环字符串

问题描述

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

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

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

非常感谢

<?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 |

标签: phpmysqlloopsfor-loop

解决方案


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

<?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。


推荐阅读