简体   繁体   中英

PDO MySQL Query only returning one set of results

I built a search form for an app and it is currently only pulling back on result at a time where there should be multiples. I am sure this is something dumb and was wondering if someone can tell me what I am doing wrong.

Here is the full code:

<?php

// php search data in mysql database using PDO
// set data in input text

$TaskId = "";
$ClientId="";
$TaskName = "";
$TaskDescription = "";
$TaskStartAt = "";


if(isset($_POST['Find']))
{
    // connect to mysql
try {
    $pdoConnect = new PDO("mysql:host=localhost;dbname=tt","root","root");
} catch (PDOException $exc) {
    echo $exc->getMessage();
    exit();
}

// id to search
//$TaskId = $_POST['TaskId'];
$ClientId = $_POST['ClientId'];
// date to search
//$DateCreated = $_POST['DateCreated'];

 // mysql search query
$pdoQuery = "SELECT * 
FROM tasks t 
left join users u using (UserId)
left join clients cl using (ClientId)
WHERE t.isdeleted = 0 and  ClientId = :ClientId";

$pdoResult = $pdoConnect->prepare($pdoQuery);

//set your id to the query id

$pdoExec = $pdoResult->execute(array(":ClientId"=>$ClientId));


if($pdoExec)
{
        // if id exist 
        // show data in inputs
    if($pdoResult->rowCount()>0)
    {
        echo '<table>';
        foreach   
        ($pdoResult as $rows)
        {
            //$TaskId = $row['TaskId'];
            $ClientId = $rows['ClientId'];
           // $TaskName = $row['TaskName'];
           // $TaskDescription = $row['TaskDescription'];
        }
        echo '</table>';
    }
        // if the id not exist
        // show a message and clear inputs

   }else{
    echo 'ERROR Data Not Inserted';
  }
}


?>


<!DOCTYPE html>
<html>
<head>
    <title>Task Tracker</title>
    <link rel="stylesheet" href="css/table.css" type="text/css" />

<link rel="stylesheet" href="assets/demo.css">
<link rel="stylesheet" href="assets/header-fixed.css">
<link href='http://fonts.googleapis.com/css?family=Cookie' rel='stylesheet'    type='text/css'>
<script type="text/javascript"> 
//Display the Month Date and Time on login.
function display_c(){
 var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}

function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
</script>

 </head>
<body>

<header class="header-fixed">
<div class="header-limiter">

    <h1><a href="#">Task Tracker</a></h1>




    <nav>
        <a href="dashboard.php" class =>Dashboard</a>
        <a href="addtask.php" class=>Task Management</a>
  <a href="configuration.php" class =>Configuration</a>
  <a href="logout.php" class =>Logout</a>
  <a href="search.php" class ="selected">Reports & Analytics</a>

    </nav>
    </nav>

   </div>
  </header>

    <title> Query a task</title>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

   </head>

    <form action="search.php" method="post">

       <!--  Enter a Task Id : <input type="text" name="TaskId" value=""> <br><br> -->
        Enter a Client Id : <input type="text" name="ClientId" value="<?php echo $ClientId;?>"><br><br>



        <input type="submit" name="Find" value="Find Data">

        <br> </br>


        <table border="0">
        <tr COLSPAN=2 BGCOLOR="lightblue">
        <td>Id</td>
        <td>Client</td>
        <td>Task Name</td>
        <td>Task Description</td>
        <td>Hours</td>
        <td>Date Created</td>
        <td>Who Completed Task</td>
   </tr>
    <?php     
    {

   if($pdoResult->rowCount()>0) 

    {
  echo "<tr>".
       "<td>".$rows["TaskId"]."</td>".
       "<td>".$rows["ClientName"]."</td>".
       "<td>".$rows["TaskName"]."</td>".
       "<td>".$rows["TaskDescription"]."</td>".
       "<td>".$rows["Hours"]."</td>".
       "<td>".$rows["DateCreated"]."</td>".
       "<td>".$rows["UserName"]."</td>".
       "</tr>";
    }

   else{
        echo 'No data associated with this Id';
    }

 }
?>

</table>
    </form>

</body>

</html>

At a quick glance, it seems to be simply that you've split your functionalities up too much.

At the top of the page, you establish your database connection and retrieve the result set. Then you echo a table element, foreach through the PDO Statement object and assign the contents of the current row to the variable $rows . Note: the content of the current row .

Further down on the page, you echo the individual fields, using $rows['field'] —but you do this outside your foreach loop. Since $rows gets repopulated everytime the loop loops around, and since you don't destroy the variable after the loop completes, you end up at the end with a variable that still contains the last row from your result set.

You need to put the place where you actually print the contents of each individual row inside the loop that iterates through your statement object to retrieve the fields. On the other hand, you only want to do this at all if any user input has been entered at all, so the whole thing still needs to be inside the positive branch of the very first condition that checks if $_POST['Find'] is set, like in the version below.

I start out here by assigning a variable $results to be an empty string—that's the value we'll output if the user hasn't sent the form at all. If $_POST['Find'] is not empty, then we search the database, iterate through the result set, create an HTML string in this loop, and store the result in the $results variable. If no rows are returned or the execute() call fails entirely, we throw an exception to be handled by an exception handler (that you will have to define at a central level, for your entire project), passing along a generic error message to be displayed to the user.

Note that I've also stripped out a lot of extraneous stuff and comments to make the relevant bits clearer and renamed the $rows variable to $row to make it clear that since it's populated inside a loop, it contains one row, not all of them.

<?php

// Set the global exception handler—should of course be done
// in a global boilerplate file, rather than for each file
set_exception_handler('your_exception_handler_here');
$results = "";

if(!empty($_POST['Find']))
{
    $pdoConnect = new PDO("mysql:host=localhost;dbname=tt","root","root");
    $pdoConnect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $ClientId = $_POST['ClientId'];

    $pdoQuery = "SELECT * 
    FROM tasks t 
    left join users u using (UserId)
    left join clients cl using (ClientId)
    WHERE t.isdeleted = 0 and  ClientId = :ClientId";

    $pdoResult = $pdoConnect->prepare($pdoQuery);
    $pdoExec = $pdoResult->execute(array(":ClientId"=>$ClientId));

    if($pdoResult->rowCount()>0)
    {
        $results = '<table border="0">
            <tr COLSPAN=2 BGCOLOR="lightblue">
                <td>Id</td>
                <td>Client</td>
                <td>Task Name</td>
                <td>Task Description</td>
                <td>Hours</td>
                <td>Date Created</td>
                <td>Who Completed Task</td>
            </tr>';

        foreach ($pdoResult as $row)
        {
            $ClientId = $row['ClientId'];
            $results .= "<tr>".
                "<td>".$row["TaskId"]."</td>".
                "<td>".$row["ClientName"]."</td>".
                "<td>".$row["TaskName"]."</td>".
                "<td>".$row["TaskDescription"]."</td>".
                "<td>".$row["Hours"]."</td>".
                "<td>".$row["DateCreated"]."</td>".
                "<td>".$row["UserName"]."</td>".
                "</tr>";
        }
            $results .= "</table>";
    } else {
        $return = '<span class="error_message">No data associated with this Id</span>');
    }
}
?>


<!DOCTYPE html>
<html>
<head>
    <title>Task Tracker</title>
</head>

<body>
    <title>Query a task</title>
    <form action="search.php" method="post">
        Enter a Client Id : <input type="text" name="ClientId" value="<?php echo $ClientId;?>"><br><br>
        <input type="submit" name="Find" value="Find Data">
    </form>

    <?php
        echo $results;
    ?>

</body>
</html>

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