php - 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 |
解决方案
您可以使用下面的代码插入到您的数据库表中。
<?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。
推荐阅读
- python - 在 Ubuntu (WSL) 上编译 PySide2 应用程序时出现 Qt 版本不匹配错误,在 openSUSE 上运行良好
- database - Codeigniter multiple database connection slows my pages. Do I have to close the connections? Where?
- google-query-language - 在 ARRAY_LITERAL 中,数组文字缺少一行或多行的值
- sql-server - 如果在构建期间没有更改,如何修复 Ms SQL CLR 二进制代码
- laravel - 如何将 Softdeletes 添加到通知表 laravel
- c# - 从 .net core WEB API 获取 500 错误以执行长时间运行的任务
- gradle - 无法解析 org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.51
- python - 当存在重复元素时,如何使迭代器在列表理解中的单个元素中操作?
- ios - 在 RealmSwift 迁移中删除表
- spring - 如何从java中的属性文件中按值读取特定键