简体   繁体   中英

Using result of one MySQL query as variable in another MySQL query

I'm trying to show the result HTML table based on team name

I'm able to echo right team name but unable to use it into a variable in my 2nd query I'm not able to find out what I'm doing wrong here why the query result is not visible. do I need to change something in my code?

<?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");
}

?>          

For security purposes you should use prepared statements or even better you should use PDO instead of mysqli.

to fix this issue simply assign the value of $valueToSearch variable inside the loop.

<?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");
}

?>    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM