循环在mysql中插入数据

时间:2013-06-17 09:59:48

标签: php mysql

我想通过mysql表中的循环插入数据,但它只插入循环执行的时间,我要插入500次相同的数据到下面的表中是代码感谢提前

enter code here



<html>
<head>
</head>
<body>
<div>
<?php

$con=mysqli_connect("localhost","root","khan","first");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

for($i=1;$i<500;$i++)
{
 $sql="INSERT INTO bio(name, fathername , address) VALUES('khan','khan','khan')";  
 echo "Number " . $i . "<br>";
}

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }

mysqli_close($con);
?>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

mysqli_query范围内加入for

$con=mysqli_connect("localhost","root","khan","first"); 
// Check connection 
if (mysqli_connect_errno()) { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

for($i=1;$i<500;$i++) { 
    $mysqli_query ="INSERT INTO bio(name, fathername , address) VALUES('khan','khan','khan')";
    echo "Number " . $i . "<br>"; 
    // <<-- you always leave a closing bracket here 
    if (!mysqli_query($con,$sql)) { 
        die('Error: ' . mysqli_error($con)); 
    } 
} 
mysqli_close($con);

现在你可以在数据库端做到这一点而不需要任何带有查询的循环

INSERT INTO bio(name, fathername , address)
SELECT 'khan','khan','khan'
  FROM
(
select a.N + b.N * 10 + c.N * 100 + 1 n
from (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) a
      , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) b
      , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) c
) t
WHERE t.n < 501

详细了解如何使用虚假数据填充表格https://stackoverflow.com/a/17139749/1920232

答案 1 :(得分:0)

这是因为你只在循环之后插入

试试这个:

for($i=1;$i<500;$i++)
{
 $sql="INSERT INTO bio(name, fathername , address) VALUES('khan','khan','khan')";  
 echo "Number " . $i . "<br>";

 if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
}

如您所见,现在mysqli_query位于循环内部,因此它将执行500次而不只是一次(注意{ }定位。

也尽量不要使用die(); 使用正确的错误处理而不是这个。

例如:

for($i = 1; $i < 500; $i++) {
//INSERT AND STUFF
if(!mysqli_query($con, $sql)) {
echo "Something went wrong. Try again.";
break;
}
}

当然你可能想要回复出错的地方。所以SQL中发生的实际错误。

Look at the Mysqli documentation for this.

如果你把它放在一个函数中,你不需要使用break;。相反,您可以使用return "something";语句返回错误并退出for循环。

现在你最终得到:

function insertFunction() {
   for(.....
       //DO INSERT
       if(!mysqli_query(...
            return "Errormessage: "+ $mysqli->error;

}

此外,您可能希望查看插入的预准备语句以及如何确保仅使用500条记录进行1次插入,而不是500次查询数据库。

This might get you started on prepared statements