函数内的数组使用 mysqli 插入数据?

arrays inside a function to insert data using mysqli?

我需要使用变量和数组创建新列。 我如何使用函数内的变量和数组来使用 mysqli 插入数据?

我又添加了一个数组作为参数 {$b} 每次调用函数时都提供新数据

我遇到的错误描述如下:

致命错误:未捕获 mysqli_sql_exception:C:'field list' 中的未知列 'hi':\xampp\htdocs\demo11\Functions_Create_Read_Update_Delete_CRUD。php:24 堆栈跟踪:#0 C :\xampp\htdocs\demo11\Functions_Create_Read_Update_Delete_CRUD.php(24): mysqli_query(Object(mysqli), 'INSERT INTO pro...') #1 C:\xampp\htdocs\demo11\Functions_Create_Read_Update_Delete_CRUD.php(35 ): createColumns('', 'products_postin...', Array, Array) #2 {main} throw in C:\xampp\htdocs\demo11\Functions_Create_Read_Update_Delete_CRUD.php on line 24

我写的代码是:

///////////-----Create-----///////////

//Create Columns




 function createColumns($database, $table, $columns = array(), 
 $values = array())
 {
include('Connect_To_Database.php');

/*----- Implode Your column names with comma ------*/
    $col_names = implode(',', $columns);

/*----- Implode Your column values with comma ------*/
    $col_values = implode(',', $values);

/*----- Create your query in here ------*/
    $sql = "INSERT INTO $table ($col_names) VALUES 
 (($col_values))";

    /*----- Then check your query ------*/
    if (mysqli_query($mysqli, $sql)){
      echo "New record created successfully";
    }else{
      echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
    }

    mysqli_close($mysqli);

 }
 $a = array("post_type", "post_image_name", "post_image_size_x");
 $b = array("hi", "hello", "there");
 createColumns("", "products_posting", $a, $b);

首先,创建列不同于添加记录,因此您需要更好地解决问题。

根据代码,我假设您想将列名作为数组提供,并根据它们向 table 插入一条记录。为此,您不需要迭代列数组中的项目。不要这样做,而是尝试 内爆 它并添加你的 SQL 查询,如下所示:

function createColumns($database, $table, $columns = array())
{
    include('Connect_To_Database.php');

    /*----- Implode Your column names with comma ------*/
        $col_names = implode(',', $columns);

    /*----- Create your query in here ------*/
        $sql = "INSERT INTO $table ($col_names) VALUES ('John', 'Doe', 'john@example.com')";

    /*----- Then check your query ------*/
        if (mysqli_query($mysqli, $sql)){
          echo "New record created successfully";
        }else{
          echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }

        mysqli_close($conn);
    
}
$a = array("post_type", "post_image_name", "post_image_size_x");
createColumns("", "products_posting", $a);

如需进一步检查,您可以查看:PHP Implode Function