gpt4 book ai didi

php - 如何将多行文本的每一行单独存储到mysql中

转载 作者:行者123 更新时间:2023-11-29 08:02:21 24 4
gpt4 key购买 nike

我是 php 和 mysql 的初学者,所以如果我的问题听起来很愚蠢,请耐心等待。

我有一个多行文本,我需要将其每一行存储到 mysql 中表的一行中。我应该提到的是,每一行的字符串都用逗号(“,”)作为分隔符分隔。

假设我有以下文本:

title1,name1,url1,number1

title2,name2,url2,number2

title3,name3,url3,number3

我不确定是否需要使用

$lines=explode("\n",$mytext)

分解多行文本,因为它会给我一个行数组,但我不知道如何将每一行拆分为单独的字符串变量并将它们插入到表行中。

任何帮助将不胜感激。

最佳答案

这应该可以,不确定mysql部分,我只是通过w3schools.com查找它

$con = mysqli_connect('host','username','password','dbname');

// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {

// Slice the data by lines first.
$linesOfData = explode('\n',$myText); // becomes an array of data

// $linesOfData = array_filter($linesOfData); // uncomment this if you feel like the data will come with an empty line, removes any empty values in the array.

// loop through the sliced data
foreach($linesOfData as $lineOfData) {
$arrayOfValues = explode(',',$lineOfData);

// loop through the array of values
foreach($arrayOfValues as $value) {
/* condition_statement ? value_if_yes : value_if_false
This is equivalent to
if(!empty($value[0]){$title=$value[0]}else{$title=null}
to check if the array has that index, to avoid error
*/
$title = !isset($value[0]) ? trim($value[0]) : null;
$name = !isset($value[1]) ? trim($value[1]) : null;
$url = !isset($value[2]) ? trim($value[2]) : null;
$number = !isset($value[3]) ? trim($value[3]) : null;

// insert to database, not recommended for commercial projects, this is vulnerable to sql injections, you should learn about prepared statements.
mysqli_query($con,"INSERT INTO tablename (title, name, url, number) VALUES ('$title','$name','$url','$number')");
}
}

// close the connection immediately after using it
mysqli_close($con);
}

关于php - 如何将多行文本的每一行单独存储到mysql中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23465946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com