PDO MySQL查询只返回一组结果


PDO MySQL Query only returning one set of results

我为一个应用程序建立了一个搜索表单,它目前只在应该有多个的时候拉回结果。我确信这是愚蠢的事情,我想知道是否有人可以告诉我我做错了什么。

下面是完整的代码:

<?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>

乍一看,你似乎把功能分割得太多了。

在页面的顶部,建立数据库连接并检索结果集。然后通过PDO Statement对象回显table元素foreach,并将当前行的内容分配给变量$rows。注:当前行的内容

在页面的更下方,您使用$rows['field']对单个字段进行echo处理,但是您在 foreach循环之外执行操作。由于每次循环循环时都会重新填充$rows,并且在循环完成后不会销毁该变量,因此最终得到的变量仍然包含结果集中的最后一行。

需要将实际打印每一行内容的位置放在循环中,该循环遍历语句对象以检索字段。另一方面,您只希望在用户输入已经输入的情况下才执行此操作,因此整个操作仍然需要在检查$_POST['Find']是否设置的第一个条件的正分支中,就像下面的版本一样。

我从这里开始赋值一个变量$results为一个空字符串——如果用户根本没有发送表单,我们将输出这个值。如果$_POST['Find']不为空,则搜索数据库,遍历结果集,在此循环中创建HTML字符串,并将结果存储在$results变量中。如果没有返回任何行或execute()调用完全失败,我们抛出一个异常,由异常处理程序处理(您必须在中心级别为整个项目定义异常处理程序),并传递一个通用错误消息以显示给用户。

请注意,我还剥离了许多无关的东西和注释,使相关的位更清晰,并将$rows变量重命名为$row,以清楚地表明,由于它是在循环中填充的,它包含一个行,而不是全部。

<?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>