从数据库中获取多个数据(等等)

时间:2018-06-22 08:32:35

标签: php mysql sql

我正在尝试从我的数据库中为一个酒店项目获得多个预订 当我尝试从数据库中获取预订时,我只收到一份预订,它应该显示/选择多个预订。

这是我的php代码: (formulier.php)     

    <?php
    $dt1 = $_POST['date1'];
    $dt2 = $_POST['date2'];

    $query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
    $result = mysqli_query($connect,$query);
    if (mysqli_num_rows($result)) {
        while($row = $result->fetch_assoc()) { include_once 'source.php';
        }
    echo "<br>formulier.php";
    echo "<br>check-in:&nbsp;&nbsp; $dt1 <br>check-out: $dt2";

    }

    else {
        die;
    }
    ?>

这是我的其他php代码:(source.php)

<?php
$dt1 = $_POST['date1'];
$dt2 = $_POST['date2'];
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)) {
    while($row = $result->fetch_assoc()) {
    }
    echo "source.php";
    echo "<br>check-in:&nbsp;&nbsp; $dt1 <br>check-out: $dt2";
}

else {
    die;
}
?>

这是我的数据库:(dt_tb)

https://gyazo.com/966efdf144a8cd1a74fa04a8127cd8f4


这是我收到的:(网站)

https://gyazo.com/1384bdafb5055f5777a40e88baccdbdd


我知道我的代码被严重搞砸了,并尝试解决了很长时间。

2 个答案:

答案 0 :(得分:0)

您在两个文件中都重复了查询!为什么? 键入时,您不需要包括2行! ,您可以直接添加它们:

$dt1 = $_POST['date1'];
$dt2 = $_POST['date2'];

$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)) {
    while($row = $result->fetch_assoc()) { 
       echo "source.php";
       echo "<br>check-in:&nbsp;&nbsp; $dt1 <br>check-out: $dt2";
    }
echo "<br>formulier.php";
echo "<br>check-in:&nbsp;&nbsp; $dt1 <br>check-out: $dt2";

}

else {
    die;
}

答案 1 :(得分:0)

我不知道您为什么需要两个文件。您可以将它们加入单循环。

<?php
$dt1 = !empty($_POST['date1']) ? $_POST['date1'] : null;
$dt2 = !empty($_POST['date2']) ? $_POST['date2'] : null;

if (!$dt1 || !$dt2) {
   throw new Exception("No dates passed!");
}

$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect, $query);

if (mysqli_num_rows($result)) {
    while($row = $result->fetch_assoc()) {
        echo "check-in:&nbsp;&nbsp; {$row['dt']}<br/>";
        echo "check-out: {$row['dt2']}<br/>";
        echo "<br/>";
    }
} else {
    echo "No bookings found between {$dt1} and {$dt2}";
    die();
}
?>

怎么了:

  1. require_once仅在第一次迭代时被调用,没有进一步的调用。通常在包含类或某些配置时使用它,但在整个逻辑中必须仅包含一次。
  2. 您尝试在source.php内的循环外回显数据
  3. 您将传递的参数回显到服务器,但不回显实际的数据库记录条目。将$dt1更改为$row['dt'],将$dt2更改为$row['dt2']