-2

我的要求是我想存储与他们相对应的联系人姓名,phone_no但是当我foreach在爆炸变量后使用循环时

foreach($phone_no11 as $phone_nos)

foreach($contact_name11 as $contact_names)

然后对于每个名字,所有电话号码都在存储,所以如果我phone_no是 999,888,777 并且contact_name是 Watch,Sun,Sky 那么它存储在数据库中的是

手表 999 手表 888 手表 777 太阳 999 太阳 888 太阳 777 天空 999 天空 888 天空 777

请帮我

<?php 
if(isset($_GET['phone_no'])&& isset($_GET['contact_name'])) { 
    include("connection.php"); 
    $phone_no1 = $_GET['phone_no']; 
    $phone_no11 = (explode(",",$phone_no1)); 
    $contact_name1 = $_GET['contact_name']; 
    $contact_name11 = (explode(",",$contact_name1));     // Insert data that retrieves from "temp_members_db" into table "registered_members" 
    foreach($phone_no11 as $phone_nos) 
    foreach($contact_name11 as $contact_names) 
    $sql = mysql_query("INSERT INTO phone_directory (contact_name,contact_number) VALUES ('$contact_names','$phone_nos')"); 
} 
?> 
4

1 回答 1

1

像这样的东西。

if(isset($_GET['phone_no'])&& isset($_GET['contact_name'])) { 
include("connection.php"); 
$phone_no1 = $_GET['phone_no']; 
$phone_no11 = (explode(",",$phone_no1)); 
$contact_name1 = $_GET['contact_name']; 
$contact_name11 = (explode(",",$contact_name1));     // Insert data that retrieves from "temp_members_db" into table "registered_members" 

$total_records = count($phone_no11);

for($i=0;$i<$total_records;$i++)
{
   $sql = mysql_query("INSERT INTO phone_directory (contact_name,contact_number) VALUES ('$contact_name11[$i]','$phone_no11[$i]')");
} 

} 

所以首先计算,你有多少电话号码或联系号码(total_records),然后通过循环插入它们。

如果您有很多记录,那么将 mysql 查询放在循环中并不是一个好习惯。批量查询工作完美。

就像是

 if(isset($_GET['phone_no'])&& isset($_GET['contact_name'])) { 
include("connection.php"); 
$phone_no1 = $_GET['phone_no']; 
$phone_no11 = (explode(",",$phone_no1)); 
$contact_name1 = $_GET['contact_name']; 
$contact_name11 = (explode(",",$contact_name1));     // Insert data that retrieves from "temp_members_db" into table "registered_members" 

$total_records = count($phone_no11);

$records = '';

for($i=0;$i<$total_records;$i++)
{
   $records .= ",('$contact_name11[$i]','$phone_no11[$i]')";
} 

 $records = sunstr($records,1);
 $sql = mysql_query("INSERT INTO phone_directory (contact_name,contact_number) VALUES $records;

}

这将首先进行批量查询,然后将其运行在循环之外。

于 2013-10-03T12:39:03.547 回答