首页 > 解决方案 > 使用 PHP 将数组插入数据库

问题描述

我尝试了许多方法通过 localhost 将我的数组插入到我的 PHPmyAdmin 数据库中。到目前为止,没有一个工作过。我相信我可能将太多不同的解决方案混合在一起。我可能试图错误地插入 INT。

我的解决方案基于此参考:https ://www.phpflow.com/php/insert-php-array-into-mysql-table/

$result = array( "0" => array(1, "blah", "blah", "blah", "blah", 2, 3),
                 "1" => array(2, "blah", "blah", "blah", "blah", 4, 5));

$connect = mysqli_connect("localhost", "root", "", "test");
if(is_array($result)){
foreach ($result as $row) {  
    $fieldVal0 = (int) $result[$row][0];
    $fieldVal1 = mysql_real_escape_string($result[$row][1]);
    $fieldVal2 = mysql_real_escape_string($result[$row][2]);
    $fieldVal3 = mysql_real_escape_string($result[$row][3]);
    $fieldVal4 = mysql_real_escape_string($result[$row][4]);
    $fieldVal5 = (int) $result[$row][5];
    $fieldVal6 = (int) $result[$row][6];

    $query ="INSERT INTO testtable ( id, english, navajoVerb, person, mode, verbNum, bookNum) VALUES ( '". $fieldVal0."','".$fieldVal1."','".$fieldVal2."','". $fieldVal3."','".$fieldVal4."','".$fieldVal5."','".$fieldVal6."' )";

    mysqli_query($connect,$query);  
}
}

我的数据库结构的图像

标签: phpmysqlarraysdatabase

解决方案


我相信自 php 5.5.x 以来 mysqli 已被贬低,无论如何我建议在使用数据库和 PHP 时使用PDO 。它使您的数据转义也容易得多。

1:$records 是从哪里来的 if 语句?因为如果不是,它永远不会超过那个。

2:您将数值声明为嵌套数组中的字符串,不确定类型转换是否是最佳解决方案。你可以只使用整数。

array(1, "blah" ....

这可能有效:

 $result = array( "0" => array(1, "blah", "blah", "blah", "blah", 2, 3),
                 "1" => array(2, "blah", "blah", "blah", "blah", 4, 5));

$connect = mysqli_connect("localhost", "root", "", "test");

if(is_array($result))
{


    // First array ( 0 and 1) 
    foreach ($result as $key =>$row) 
    {
        // We can just loop over the next array so we have to type less
        // lets declare a new array with escaped results

        $escaped_results = array();

        // Now loop over the row
        foreach( $row as $key => $value)
        {
            // if we don't set anything inbetween the brackets [] we tell php to auto fill the array 
            // so it adds a new array element starting from 0 
            $escaped_results[] = mysqli_real_escape_string($connect, $value);
        }

        // lets make the query easier and simpler
        // we just use implode to build the values 
        $query ="INSERT INTO testtable ( id, english, navajoVerb, person, mode, verbNum, bookNum) VALUES ('". implode("','", $escaped_results) ."')";

        // execute the query
        $result = mysqli_query($connect, $query);  

        // catch the error
        if (!$result) {
            die('Invalid query: ' . mysqli_error($connect));
        }
    }
}

虽然我会推荐一些关于 php 的 PDO 教程,因为这会让你的生活变得更轻松。


推荐阅读