简体   繁体   English

用PHP将数组插入MySQL数据库?

[英]Using PHP to insert array into MySQL database?

Here's my current code: 这是我目前的代码:

// connect to database  
$con = mysqli_connect("localhost","username","password","database");
if (!$con) {
    die('Could not connect: ' . mysqli_error());
}

// get the json file
$jsondata = file_get_contents('http://www.example.com');

// convert json to php array
$data = json_decode($jsondata, true);

// assign each of the variables
$id = $data['0']['id'];
$name = $data['0']['name'];
$status = $data['0']['status'];

$insertstatement = mysqli_query($con,"INSERT INTO `table` (`id`, `name`, `status`) VALUES ('".$id."', '".$name."', '".$status."');");

Technically this code is working, but it's only adding the first item. 从技术上讲,这段代码正在运行,但它只是添加了第一项。

For example, here's the original json that's being imported: 例如,这是导入的原始json:

[
   {
      "id":"19839",
      "status":"active",
      "name":"First Name",
   },
   {
      "id":"19840",
      "status":"active",
      "name":"Second Name",
   },
   {
      "id":"19841",
      "status":"active",
      "name":"Another Name",
   },
   {
      "id":"19842",
      "status":"active",
      "name":"Last Name",
   }
]

My code would only be inserting this into the database: 我的代码只会将其插入数据库:

{
 "id":"19839",
 "status":"active",
 "name":"First Name",
}

How do I make it loop through all of them and insert all of the rows? 如何让它循环遍历所有行并插入所有行? Also is there, a way to insert them in reverse order (starting from the last one, ending at the first one)? 还有,一种方法以相反的顺序插入它们(从最后一个开始,到第一个结束)?

Any help would be greatly appreciated :) 任何帮助将不胜感激 :)

  • To iterate over array you have to use foreach operator. 要迭代数组,您必须使用foreach运算符。
  • To perform multiple inserts you have to use prepared statements 要执行多个插入,您必须使用预准备语句

So despite what in all other hastily written answers said, the code should be 所以尽管所有其他匆匆写的答案都说,代码应该是

$stmt = $con->prepare("INSERT INTO `table` (`id`, `name`, `status`) VALUES (?,?,?)");
$stmt->bind_param("sss", $id, $name, $status);
foreach ($data as $row)
{
    $id = $row['id'];
    $name = $row['name'];
    $status = $row['status'];
    $stmt->execute();
}

In order to insert multiple rows of data or array of the data you have to iterate upon the array variable using the foreach() so that it will loop you by single row so that you can perform the needed operation that you want to perform. 为了插入多行数据或数据数组,您必须使用foreach() 迭代数组变量,以便它将循环您的单行,以便您可以执行您想要执行的所需操作。

You can insert the data using mysqli.* or PDO or by using prepared statements . 您可以使用mysqli.*PDO或使用mysqli.* prepared statements插入数据。 And it is up to you who can decide of under which scenario you are going to insert the data. 您可以决定在哪种情况下插入数据取决于您。

MYSQLI: 库MySQLi:

<?php
$data = json_decode($jsondata, true);
foreach($data as $single_data)
{
$insertstatement = mysqli_query($con,"INSERT INTO `table` (`id`, `name`, `status`) VALUES ('".$single_data['id']."', '".$single_data['name']."', '".$single_data['status']."');");
}
?>

Prepared Statements: 准备好的声明:

<?php
$query = $con->prepare("INSERT INTO `table` (`id`, `name`, `status`) VALUES (?,?,?)");
$query->bind_param("sss", $id, $name, $status);
foreach ($data as $row)
{
    $id = $row['id'];
    $name = $row['name'];
    $status = $row['status'];
    $result->execute();// This will execute the statement. 
}
?>

PDO with Prepared Statements: 已准备好的声明的PDO:

<?php
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbusername,$dbpassword);
$statement = $link->prepare("INSERT INTO testtable(name, lastname, age)
    VALUES(:id, :name, :status)");
foreach($data as $row)
{
$statement->execute(array(
    "id" => $row['id'],
    "name" => $row['name'],
    "status" => $row['status']
));
}
?>

Hope so my explanations would be clear for better understanding of all the three type of statements. 希望我的解释清楚明白,以便更好地理解所有这三种陈述。

With a foreach loop: 使用foreach循环:

foreach($data as $index => $row){
    $insertstatement = mysqli_query($con,"INSERT INTO `table` (`id`, `name`, `status`) VALUES ('". $row['id'] ."', '". $row['name'] ."', '". $row['status'] ."');");
}

However please note that you should be careful when inserting any data from untrusted sources, since it leaves you vulnerable to SQL injections. 但是请注意,从不受信任的来源插入任何数据时应该小心,因为它使您容易受到SQL注入的攻击。 Learn read more about SQL injection here: How can I prevent SQL injection in PHP? 在这里学习如何阅读有关SQL注入的更多信息: 如何在PHP中阻止SQL注入? .

You should use the MySql multiple row inserts. 您应该使用MySql多行插入。

INSERT INTO tbl_name (col1,col2) VALUES(1,2), (3,4);

MySql insert reference: http://dev.mysql.com/doc/refman/5.7/en/insert.html MySql插入参考: http//dev.mysql.com/doc/refman/5.7/en/insert.html

In php, you would do something like (modified your code) 在PHP中,你会做类似的事情(修改你的代码)

// connect to database  
$con = mysqli_connect("localhost","username","password","database");
if (!$con) {
    die('Could not connect: ' . mysqli_error());
}

// get the json file
$jsondata = file_get_contents('http://www.example.com');

// convert json to php array
$data = json_decode($jsondata, true);

$query = "INSERT INTO `table` (`id`, `name`, `status`) VALUES ";

foreach($data as $d) {
$query .= "('".$d['id']."', '".$d['name']."', '".$d['status']."'),";
}
// Query. Note the trim to remove the last ,
$insertstatement = mysqli_query($con, trim($query,',');

You can also continue reading from ON DUPLICATE KEY... & other useful additions to the above. 您还可以继续阅读ON DUPLICATE KEY ...以及上述其他有用的补充内容。 You should also make sure your data is correctly escaped / from a 100% safe source. 您还应该确保您的数据被正确转义/来自100%安全的来源。 If status contains something like " '; TRUNCATE TABLE... " unescaped, you're potentially in trouble. 如果状态包含“ '; TRUNCATE TABLE ... ”之类的未转义状态,则可能会遇到麻烦。

EDIT: The two other solutions also work and insert all rows. 编辑:其他两个解决方案也可以工作并插入所有行。 My version however inserts all rows in one query. 但是,我的版本会在一个查询中插入所有行。 Depending on how large your data is, it might not be feasible to run - say - 1000 queries instead of one. 根据您的数据大小,运行 - 比如说 - 1000个查询而不是一个查询可能是不可行的。

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

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