MySQL在foreach内部插入仅被调用一次

时间:2018-09-05 06:25:54

标签: php mysql

我有一个数组$alert_note。我遍历循环,并用一些字符串填充它:

$n = 0;
$alert_note = array();
$results = array();
while($row = mysqli_fetch_assoc($query)){

    //some code in here populates the $results[$n] array with results from $row

    $thisnote = "<b>Location alert</b><br>
    Alert ID: {$results[$n]['alert-id']}<br>
    Start: {$results[$n]['start-formatted']}<br>
    End: {$results[$n]['end-formatted']}<br>
    Radius: {$results[$n]['radius-km']} km<br>
    Distance: {$results[$n]['distance-km']} km<br>
    <ul>\n";
    //$results[$n]['data'] is a nested array, so iterate through it:
    foreach($results[$n]['data'] as $name => $data){
        $thisnote .= "<li>$name: $data</li>\n";
    }
    $thisnote .= "</ul>";
    $alert_note[$n] = $thisnote;

    $n++;
}

然后我调用一个foreach函数:

foreach($alert_note as $alert_note_contents){
    error_log("Note: $alert_note_contents");
    mysqli_query($dblink, "INSERT INTO `incident_events` (`incident`, `data`, `time`, `operator`) VALUES ('$incident', '$alert_note_contents', '$now', '$operator')");
}

$alert_note中的每个字符串都会在PHP错误日志中按预期显示,但只有最后一个字符串会插入MySQL表中。没有抛出PHP错误。知道为什么会这样吗?

1 个答案:

答案 0 :(得分:-1)

foreach之前的plz($ alert_note作为$ alert_note_contents){

这样做,这样我可以得到错误 var_dump($ alert_note);
并执行此操作,以便我可以查看ind db

是否存在任何错误
$conn = new mysqli($servername, $username, $password, $dbname);
 // Check connection 
if ($conn->connect_error) 
{ die("Connection failed: " . $conn->connect_error); } 

$sql = "INSERT INTO incident_events (incident, data, time, operator) VALUES ('$incident', '$alert_note_contents', '$now', '$operator')";
 if ($conn->query($sql) === TRUE) 
{ echo "New record created successfully"; } 
else { echo "Error: " . $sql . "<br>" . $conn->error; }
 $conn->close();