[英]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.