sql select总是保留一个未选中的记录

时间:2017-01-25 12:27:38

标签: php mysqli

它一直在选择,一个记录总是被遗漏

<?php
require 'database.php';
//get from url
if (isset($_GET['location'])) {
  $location = $_GET['location'];
}
$sql = "SELECT * FROM bmen where  location='$location'";
$result = mysqli_query($database,$sql) or die(mysqli_error());
$rws = mysqli_fetch_array($result);

while($rws = $result->fetch_array())
{
echo $rws['username'] . " " . $rws['phone'];
echo "<br />";
}
$database->close();

当有一条记录时,它不会显示

database image browser result image

3 个答案:

答案 0 :(得分:2)

您正在读取结果集中的第一行并在进入循环之前将其丢弃

<?php
require 'database.php';
//get from url
if (isset($_GET['location'])) {
  $location = $_GET['location'];
}
$sql = "SELECT * FROM bmen where  location='$location'";
$result = mysqli_query($database,$sql) or die(mysqli_error());

// delete this next line
//$rws = mysqli_fetch_array($result);

while($rws = $result->fetch_array())
{
    echo $rws['username'] . " " . $rws['phone'];
    echo "<br />";
}
$database->close();
  

您的脚本面临SQL Injection Attack的风险   看看Little Bobby Tables偶然发生了什么   if you are escaping inputs, its not safe!   使用prepared parameterized statements

您应该尝试使用参数化和绑定数据

对使用外部收集数据的查询进行编码
<?php
require 'database.php';
//get from url
if (isset($_GET['location'])) {

    $sql = "SELECT * FROM bmen where  location=?";
    $result = $database->prepare($sql);
    $result->bind_param('s', $_GET['location'] );
    $result->execute();

    // some error checking is also good
    if ( ! $result ) {
        echo $result->error;
        exit;
    }    

    while($rws = $result->fetch_assoc())
    {
        echo $rws['username'] . " " . $rws['phone'] . "<br />";
    }
}

答案 1 :(得分:0)

因为你两次调用了mysqli_fetch_array。因此,第一个元素总是被遗漏。首先删除 $ rws = mysqli_fetch_array($ result); 。没关系。

<?php
require 'database.php';
//get from url
if (isset($_GET['location'])) {
  $location = $_GET['location'];
}
$sql = "SELECT * FROM bmen where  location='$location'";
$result = mysqli_query($database,$sql) or die(mysqli_error());

while($rws = $result->fetch_array())
{
echo $rws['username'] . " " . $rws['phone'];
echo "<br />";
}
$database->close();

答案 2 :(得分:0)

在您的代码中您需要两次获取数据

首先在这里

$rws = mysqli_fetch_array($result);

和第二个

while($rws = $result->fetch_array())

删除这行代码,然后$rws = mysqli_fetch_array($result);