Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在MySQL中插入PHP变量和数组_Php_Mysql_Sql_Arrays - Fatal编程技术网

在MySQL中插入PHP变量和数组

在MySQL中插入PHP变量和数组,php,mysql,sql,arrays,Php,Mysql,Sql,Arrays,我有一个包含多个选择框的表单。因此,我将变量插入数据库(例如,输入字段的内容)以及数组(多个选择框值) 我尝试将其作为两个单独的查询来执行,但在第一次查询后出现错误: 列计数与第1行的值计数不匹配 下面是我的代码片段(第一个查询),其中被调试注释掉了: $instruments = mysqli_real_escape_string($con, $_POST['instruments']); //var_dump($_POST['instruments']); $columns = implo

我有一个包含多个选择框的表单。因此,我将变量插入数据库(例如,输入字段的内容)以及数组(多个选择框值)

我尝试将其作为两个单独的查询来执行,但在第一次查询后出现错误:

列计数与第1行的值计数不匹配

下面是我的代码片段(第一个查询),其中被调试注释掉了:

$instruments = mysqli_real_escape_string($con, $_POST['instruments']);
//var_dump($_POST['instruments']);

$columns = implode(", ",array_keys($instruments));
//var_dump($columns);

$escaped_values = array_map('mysql_real_escape_string', array_values($instruments));
//var_dump($escaped_values);

$values  = implode(", ", $escaped_values);
//var_dump($values);

$sql = "INSERT INTO `depfinder_sandbox`(instrument1, instrument2, instrument3, instrument4, instrument5) VALUES ($values)";

$result1 = mysqli_query($con, $sql) or die(mysqli_error($con));
在调试过程中,我发现了以下内容:

  • var\u dump($instruments)
    尽管设置了变量,但返回NULL
  • 但是,
    var\u dump($\u POST['instruments'])
    会按它应该的方式返回
  • 如果我使用
    $\u POST['instruments']
    var\u dump($escaped\u values)
    返回
    字符串(4)“0,1”
    ,这是不正确的
  • var\u dump($values)
    无论我做什么都返回NULL
即使变量按预期返回,如果
$instruments[]
可以包含1到5个值,但查询规定了5(instrument1、instrument2、instrument3、instrument4、instrument5),我还会有列计数问题吗

更新

以下是我现在拥有的:

foreach ($_POST['instruments'] as $key => $value)
{ 
    $instruments[$key] = mysqli_real_escape_string($con, $value);
}

var_dump($instruments); // returns perfectly

$columns = implode(", ",array_keys($instruments));
var_dump($columns); // returns: string(4) "0, 1"

$values  = implode(", ", $columns);
$sql = "INSERT INTO `depfinder_sandbox`(instrument1, instrument2, instrument3, instrument4, instrument5) VALUES ($values)";
$result1 = mysqli_query($con, $sql) or die(mysqli_error($con)); // returns: Column count doesn't match value count at row 1

是否从查询中删除列名并在表定义中使用默认值?然后,它将插入尽可能多的字符串,并对其余部分使用默认值?1)mysqli\u real\u escape\u string的第二个参数接受字符串,您似乎传递了一个数组。2) 您正在混合使用
mysql.*
mysqli.*
。还有@ICanHasKittenz说的:)@Fluffeh您能给我举个例子说明您的意思吗?@Sebastian您能粘贴
$\u POST['instruments']
的示例输出吗?这应该可以解决大部分问题。