如何将字符串插入数据库 table 中的不同列?

How to insert string into different columns in database table?

基本上我从 pdf 文件中创建了一个字符串,该字符串包含逗号分隔值,我现在需要将其插入到 table 中的不同列中。 我会尝试类似问题的答案 ,但我没有得到我需要的答案。

我已经尝试将该字符串分解为一个数组,因此逗号是每个元素的分隔符,如下所示:

$array = explode(',', $text);

但是因为 table 中只有 3 列,所以我需要将这些值排序到这些列中,这样每个第三个字符串都会进入第一列,然后所有字符串都会进入后续列。我试过这样做:

$duzina=count($array);
        for($i=0;$i<$duzina;$i++) {
            if ($i = 0 && $i < 3) {
                $mysqli->query("INSERT INTO `test` (`name`, `surname`, `email`) VALUES
                (
                    '" . trim($array[$i]) . "',
                    '" . addslashes($array[$i + 1]) . "',
                    '" . addslashes($array[$i + 2]) . "'
                )
            ");
            }
            if ($i/3 == 0) {// has found a 3rd,6th,9th element of an $array

                $mysqli->query("INSERT INTO `test` (`name`, `surname`, `email`) VALUES
                (
                    '" . trim($array[$i]) . "',
                    '" . addslashes($array[$i + 1]) . "',
                    '" . addslashes($array[$i + 2]) . "'
                )
            ");
            } else {
                $mysqli->query("INSERT INTO `test` (`name`, `surname`, `email`) VALUES
                (
                    '" . trim($array[$i]) . "',
                    '" . addslashes($array[$i + 1]) . "',
                    '" . addslashes($array[$i + 2]) . "'
                )
            ");
            }

但它所做的只是插入 $array 的前 3 个元素。请帮助

除法的其余部分不是 % 而不是 /,所以替换为:

if ($i/3 == 0) {

if ($i%3 == 0) {

2 件事:

先用if / elseif /else

if ($i = 0 && $i < 3) {
    ...
}
elseif ($i%3 == 0) {
    ...
}
else
{
    ....
}

第二个:

它是 $i%3 == 0 而不是 $i/ 3 == 0

使用准备好的语句。
重构您的数据以在代码中有意义(对调试有用)
明智地循环(增加3)

请注意,以下代码未经现场测试,只是概念验证。

$array = loadpdfwhatever();
$length = count($array);

// Restructure the raw data to be meaningful to a human. Can be skipped,
// but this will help you debugging in + 3 weeks from now :-)
$restructured = [];
for($i=0;$i<$length;$i+=3) { // note the $i+3 to increment by 3.
    $restructured[] = ['name'=> $array[$i],
                       'surname'=> $array[$i+1],
                       'email'=> $array[$i+2]];
}


// Using prepared statements we only have to build up the query once.
// Makes code faster and more efficient.
if ($stmt = mysqli_prepare($link, "INSERT INTO `test` (`name`, `surname`, `email`) VALUES ( ?, ?, ? ) ")) {
    foreach($restructured as $insert) {
        mysqli_stmt_bind_param($stmt,'sss',$insert['name'],
                                           $insert['surname'],
                                           $insert['email']); 
        mysqli_stmt_execute($stmt)
    }
}