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


How to insert string into different columns in database table?

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

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

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

但是由于我在表中只有 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) {

使用预准备语句。
重构数据以在代码中有意义(对调试有用)
明智地循环(递增 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)
    }
}

2件事:

第一次使用 if/elseif/else

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

第二:

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