简体   繁体   English

使用 mysqli 从数组插入 MySQL

[英]Insert into MySQL from array with mysqli

I want to insert some data from a parsed JSON to a table, but when I do it, it doesn't work, it returns 0 rows, what am I missing?我想将一些数据从已解析的 JSON 插入到表中,但是当我这样做时,它不起作用,它返回 0 行,我错过了什么? I'm new yet with this "mysqli".我是这个“mysqli”的新手。 I have more than 25000 rows to insert to the table.我有超过 25000 行要插入到表中。

$mysqli = mysqli_connect('localhost', 'root', '', '');

$allData = $dataSource->getAllData();
foreach ($allData as $key => $value) {
    $query = 'INSERT INTO `table`(`data_id`, `name`) VALUES (' . $value['data_id'] . ', ' . $value['name'] . ')';
    $result = mysqli_query($mysqli, $query);
}

You are most likely encountering this problem, because of missing quotes in SQL.您很可能会遇到此问题,因为 SQL 中缺少引号。 All literal strings must be quoted when part of SQL statement.当 SQL 语句的一部分时,所有文字字符串都必须被引用。 PHP would happily let you know about SQL syntax errors if you would only have enabled them.如果您只启用它们,PHP 会很高兴地让您知道 SQL 语法错误。 See mysqli_fetch_assoc() expects parameter / Call to a member function bind_param() errors.参见mysqli_fetch_assoc() 期望参数/调用成员函数 bind_param() 错误。 How to get the actual mysql error and fix it?如何获取实际的mysql错误并修复它? . . To summarize just add this line before mysqli_connect()总而言之,只需在mysqli_connect()之前添加这一行

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

However, there is much better way to insert the data using mysqli.但是,使用 mysqli 插入数据有更好的方法。 You should use prepared statements.您应该使用准备好的语句。 Using parameter binding is not only safer (no SQL injections), but it also a little bit faster when you add 25000 rows.使用参数绑定不仅更安全(没有 SQL 注入),而且在添加 25000 行时速度也会更快一些。

Your fixed code with error reporting and prepared statements would look like this:带有错误报告和准备好的语句的固定代码如下所示:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'root', '', 'dbname');
$mysqli->set_charset('utf8mb4');

$allData = $dataSource->getAllData();

$stmt = $mysqli->prepare('INSERT INTO `table`(`data_id`, `name`) VALUES (?,?)');

foreach ($allData as $key => $value) {
    $stmt->bind_param('ss', $value['data_id'], $value['name']);
    $stmt->execute();
}

Seems like you should set single quotes around your data values.似乎您应该在数据值周围设置单引号。 Also adding a mysqli_error check for your mysqli_query line so you can actually see what is happening:还为您的mysqli_query行添加一个mysqli_error检查,以便您可以实际看到发生了什么:

$allData = $dataSource->getAllData();
foreach ($allData as $key => $value) {
    $query = "INSERT INTO `table`(`data_id`, `name`) VALUES ('" . $value['data_id'] . "', '" . $value['name'] . "')";
    $result = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
}

Or better yet, use mysqli_stmt_bind_param like this.或者更好的是,像这样使用mysqli_stmt_bind_param Allow MySQLi to deal with the whole query data structuring instead of having to worry about single quote placement.允许 MySQLi 处理整个查询数据结构,而不必担心单引号放置。 Also, added a check for mysqli_connect_error on your mysqli_connect line:此外,在您的mysqli_connect行上添加了对mysqli_connect_error的检查:

// Connecting, selecting database
$mysqli = mysqli_connect('localhost', 'root', '', '') or die(mysqli_connect_error());

$allData = $dataSource->getAllData();
foreach ($allData as $key => $value) {
    // Set the query.
    $query = "INSERT INTO `table`(`data_id`, `name`) VALUES (?, ?)";

    // Bind the params.
    // mysqli_stmt_bind_param($query, 'ss', $value['data_id'], $value['name']);
    mysqli_stmt_bind_param($query, 'is', $value['data_id'], $value['name']);

    // Run the query.
    $result = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
}

Note that I have a commented line for the mysqli_stmt_bind_param since it's not clear to me if your $value['data_id'] is a number or a string.请注意,我对mysqli_stmt_bind_param有一个注释行,因为我不清楚您的$value['data_id']是数字还是字符串。 The mysqli_stmt_bind_param($query, 'is',… means the first value is an integer ( i ) and the next value is a string ( s ). Feel free to adjust to best fit your actual data types. mysqli_stmt_bind_param($query, 'is',…表示第一个值是一个整数 ( i ),下一个值是一个字符串 ( s )。随意调整以最适合您的实际数据类型。

An even more automatic solution would be:一个更自动化的解决方案是:

$link = mysqli_connect('localhost', 'root', 'password', 'mydatabase') or die(mysqli_connect_error());

foreach ($groups as $key => $values) {
    $valuesArray = array();
    // figure out if we have to encapsulate in ''
    foreach($values as $key => $value){
        switch(gettype($value)){
            case 'boolean':
            case 'integer':
            case 'double': // includes float
                $valuesArray[] = $value;
            break;
            case 'string':
                $valuesArray[] = '\''.$value.'\'';
            break;
            default:
                die('not possible');
            break;
        }
    }
    $query = 'INSERT INTO mydatabase.mytable(' . implode(',',array_keys($values)) . ') VALUES (' . implode(',',$valuesArray) . ')';
    // echo $query; // debug
    $result = mysqli_query($link, $query) or die(mysqli_error());
}

This solution is plain mysqli again, for external input use prepared statements or pdo or the like!这个解决方案又是普通的 mysqli,对于外部输入使用准备好的语句或 pdo 之类的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM