SQL 循环内的 PHP/SQL 查询表

在循环响应之前,您必须检查它的长度。没有检查这段代码,但它应该工作


var len = response.length;


$("#sel_zone").empty();

if(len == 0){

    $("#sel_zone").append('<option value="">No Data Found</option>');

} else{

    for( var i = 0; i<len; i++){

        var id = response[i]['id'];

        var name = response[i]['name'];

        $("#sel_zone").append("<option value='"+id+"'>"+name+"</option>");

    }

}


慕标5832272
浏览 93回答 1
1回答

慕仙森

&nbsp; &nbsp; 只要有可能,您应该避免在循环中使用 SQL,并尝试一次性获取所有数据。在这种情况下,您可以JOIN在第一条语句中使用获取用户名。就我个人而言,我还会只列出您想要获取的列,而不是使用*...$sql = "SELECT t1.id as messageID, t1.from_id, t2.full_name, t2.title&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; FROM table1 t1&nbsp; &nbsp; &nbsp; &nbsp; JOIN table2 t2 on t2.id = t1.user_id&nbsp; &nbsp; &nbsp; &nbsp; WHERE t1.user_id = '$userid' AND t1.unread = 0";&nbsp;$result = $conn->query($sql);&nbsp;if ($result->num_rows > 0) {&nbsp;&nbsp; &nbsp; while($row = $result->fetch_assoc()) {;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $from = $row["from_id"];&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $messageID = $row["messageID"];&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ?>&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td><?php&nbsp; echo $row['full_name'];?></td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td><?php echo $row["title"];?></td>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; &nbsp; &nbsp; <?php&nbsp;&nbsp; &nbsp; }}&nbsp;无法测试它,但应该更有用。
打开App,查看更多内容
随时随地看视频慕课网APP