gpt4 book ai didi

php - 将数组元素插入数据库字段MYSQL

转载 作者:行者123 更新时间:2023-11-29 12:36:49 24 4
gpt4 key购买 nike

我有一个名为“客户”的数据库和五个名为名称、地址、城市、上限、国家/地区的数组。在我的数据库中,我想创建 10 条记录,其中包含每个客户的信息。使用我的代码,所有数据都插入到数据库中,但首先插入所有名称、所有地址等,所以我得到 50 条记录而不是 10 条。我该如何修复它?

    <?php

$name = array('Alfreds Futterkiste','Ana Trujillo Emparedados','Antonio Moreno Taqueria','Around the Horn','Berglunds snabbkop','Blauer See Delikatessen','Blondel pere et fils ','Bolido Comidas preparadas','Bon app','Bottom-Dollar Marketse');

$address = array('Obere Str. 57','Avda. de la Constitucion 2222','Mataderos 2312','120 Hanover Sq.','Berguvsvagen 8','Forsterstr. 57','24, place Kleber','C/ Araquil, 67','12, rue des Bouchers','23 Tsawassen Blvd');

$city = array('Berlin','Mexico D.F.','Mexico D.F.','London','Lulea','Mannheim','Strasbourg','Madrid','Marseille','Tsawassen');

$cap = array('12209','05021','05023','WA1 1DP','S-958 22','68306','67000','28023','13008','T2F 8M4');

$country = array('Germany','Mexico','Mexico','UK','Sweden','Germany','France','Spain','France','Canada');

$conn= mysqli_connect('127.0.0.1','root','','preesame') or die("Connection failed: " . $conn->connect_error);

foreach ($name as $key=>$value)
{
$namess = mysqli_real_escape_string($conn,$value);
$addressess = mysqli_real_escape_string($conn,$addresses);
$citiess = mysqli_real_escape_string($conn,$cities);
$capss = mysqli_real_escape_string($conn,$caps);
$countriess = mysqli_real_escape_string($conn,$countries);
$insert = mysqli_query($conn,"INSERT INTO customers (id,name,address,city,cap,country) VALUES ('',$namess[$key],$addressess[$key],$citiess[$key],$capss[$key],$countriess[$key])");
}

$conn->close();
?>

最佳答案

1) 连接到数据库一次。您不必在每个循环中每次都进行连接

2) 使用SINGLE循环和SINGLE查询:

foreach ($name as $key => $value) {
$sql = "INSERT ... (id, name, address, foo, bar, baz) VALUES ('', $value, $addresses[$key], $foo[$key], $bar[$key], etc...)";
... run query here
}

3) 阅读并了解 sql injection attacks因为您对获取您的服务器 pwn3d 持开放态度。

关于php - 将数组元素插入数据库字段MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26657102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com