[英]How to stop loop in while statement in PHP MySQL?
我想問一下。
可以添加exit()嗎? 在每個語句的末尾,或者除了exit()之外還有什么好辦法; ?
原因是停止顯示數據的循環, 因為如果我刪除/禁用exit(); ,數據將循環並顯示數據庫表中所有可用的行。 如果exit();,則else語句也將執行。 從代碼中刪除。
代碼如下:
<?php
$connect = mysqli_connect("localhost", "root", "", "database");
global $connect;
if(isset($_POST['Submit'])){
$input = $_POST['input'];
$sql = "SELECT * FROM table";
$get = mysqli_query($connect,$sql);
if($get && mysqli_num_rows($get) > 0 ){
while($row = mysqli_fetch_assoc($get)){
$input_db = $row['input'];
$output_db = $row['output'];
if (($input >= $input_db) && ($output <= $output_db))
{
echo "Input and output is in between";
exit();
}
else
{
echo "Data added ! <br/>";
exit();
}
}
mysqli_free_result($get);
}
else
{
echo "data is outside range";
}
}
?>
<form action="testdate.php" method="post">
<table>
<tr>
<td><i class="fa fa-unlock-alt"></i> </td>
<td>Input : </td>
<td><input type ="text" name="input" size="30"></td>
</tr>
</table>
<p><input class="btnSuccess" type ="submit" name="Submit" value="Submit"> </p>
</form>
謝謝。
要直接回答問題,您只需交換exit();
break;
。 這會停止循環而不會退出:
// Let's go infinite..
while(true)
{
echo 'This only appears once, because we\'re breaking out of the loop.';
// Not today!
break;
}
// Everything is normal again down here.
echo 'That was a close one!';
在您的特定情況下,更好的方法是只選擇所需的數據 ,否則MySQL將只為PHP丟棄發送的大部分數據而忙於發送整個表。 像這樣:
<?php
$connect = mysqli_connect("localhost", "root", "", "database");
global $connect;
if(isset($_POST['Submit']))
{
$input = (int)$_POST['input']; // * See note below
$sql = "SELECT * FROM table where ".$input.">=`input` and ".$output."<=`output`";
$get=mysqli_query($connect,$sql);
if($get && $get->num_rows)
{
echo "Input and output is in between";
}
else
{
echo "data is outside range";
}
}
?>
(int)
是一種簡單的安全措施-它阻止某人執行SQL注入。 您也需要對$output
。 如果可能,請改用准備好的查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.