MySQL内部for循环。插入仅在第一个循环上运行

时间:2014-11-22 02:05:07

标签: php mysql arrays for-loop

我创建了一个for循环,循环遍历数组或从字符串中爆炸的单词。 for循环工作并已通过echo语句进行测试。运行此代码时,它只将1条记录插入数据库,而不是数组中的字符串数。

$item=explode(" ", $items);
for ($i = 0; $i < count($item); ++$i) {
    // Create connection
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO invlog (itemid, qty)
VALUES ('".$item[$i]."', '-1')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);    
    }

2 个答案:

答案 0 :(得分:2)

为了提高效率,并避免多次数据库调用,您实际上应该只执行一次语句。

所以循环,创建查询,然后执行它。

喜欢这样..

$item=explode(" ", $items);
$query="";
 for ($i = 0; $i < count($item); ++$i) {
  // Build Query 
  $query.="(".$item[$i].",-1),";
 }
 $query = rtrim($query); // Remove last trailing comma from the right hand side of query string

 //Connect to database, and do DB stuff outside of loop in one call
 $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
 // Check connection
 if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
 }
 $sql = "INSERT INTO invlog (itemid, qty)
 VALUES ".$query;

  if (mysqli_query($conn, $sql)) {
    echo "New records created successfully";
  } else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
  }

  mysqli_close($conn);    

答案 1 :(得分:0)

$replacer  = array("\r\n", "\n", "\r", "\t", "  ");
$items = str_replace($replacer, " ", $items);
$item=explode(" ", $items);
// Create connection
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}


for ($i = 0; $i < count($item); ++$i) {

$sql = "INSERT INTO invlog (itemid, qty)
VALUES ('".$item[$i]."', '-1')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}


    }
    mysqli_close($conn);