使用一个MySQL查询的结果作为另一个MySQL查询的变量

时间:2019-01-19 14:54:01

标签: php mysqli

我正在尝试根据团队名称显示结果HTML表

我能够呼应正确的团队名称,但无法在第二次查询中将其用于变量中,因此在这里我看不到我在做什么错,为什么查询结果不可见。我需要更改代码中的某些内容吗?

<?php
include_once("connection.php");

$sql = "SELECT TeamName FROM `superuser` WHERE id = '303016'";
$queryRecords2 = mysqli_query($conn, $sql) or die("error to fetch employees data");

while ($row2 = $queryRecords2->fetch_assoc()) {
    echo $row2['TeamName']."<br>";
}

if(isset($_POST['search']))
{
    $valueToSearch = $row2['TeamName'];
    $valueToSearch2 = $_POST['valueToSearch2'];
    $valueToSearch3 = $_POST['valueToSearch3'];
    $sql = "SELECT * FROM `dailydata` WHERE TeamName = '".$valueToSearch."' and Date BETWEEN '".$valueToSearch2."' AND '".$valueToSearch3."'";
    $queryRecords = mysqli_query($conn, $sql) or die("error to fetch employees data");
}
else {
    $sql = "SELECT * FROM `dailydata` WHERE TeamName = ''";
    $queryRecords = mysqli_query($conn, $sql) or die("error to fetch employees data");
}

?>          

1 个答案:

答案 0 :(得分:0)

出于安全目的,您应该使用准备好的语句,甚至更好的是,应该使用PDO代替mysqli。

要解决此问题,只需在循环内分配$ valueToSearch变量的值。

<?php
include_once("connection.php");

$sql = "SELECT TeamName FROM `superuser` WHERE id = '303016'";
$queryRecords2 = mysqli_query($conn, $sql) or die("error to fetch employees data");

$valueToSearch;
while ($row2 = $queryRecords2->fetch_assoc()) {
    $valueToSearch = $row2['TeamName'];
}

if(isset($_POST['search']))
{
    $valueToSearch2 = $_POST['valueToSearch2'];
    $valueToSearch3 = $_POST['valueToSearch3'];
    $sql = "SELECT * FROM `dailydata` WHERE TeamName = '".$valueToSearch."' and Date BETWEEN '".$valueToSearch2."' AND '".$valueToSearch3."'";
    $queryRecords = mysqli_query($conn, $sql) or die("error to fetch employees data");
}
else {
    $sql = "SELECT * FROM `dailydata` WHERE TeamName = ''";
    $queryRecords = mysqli_query($conn, $sql) or die("error to fetch employees data");
}

?>