PDO MySQL Query仅返回一组结果

时间:2016-07-02 18:00:19

标签: php mysql pdo

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

以下是完整代码:

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

1 个答案:

答案 0 :(得分:4)

快速浏览一下,似乎只是你将功能分得太多了。

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

在页面的下方,echo使用$rows['field'] foreach个别字段,但您执行此操作 $rows循环。由于每次循环循环时$_POST['Find']都会被重新填充,并且由于在循环完成后你没有销毁变量,所以你最后会得到一个仍然包含结果集最后一行的变量。

您需要将实际打印每个单独行内容的位置放在循环中,循环遍历语句对象以检索字段。另一方面,如果完全输入任何用户输入,你只想要这样做,所以整个事情仍然需要在检查是否设置$results的第一个条件的正分支内。 ,就像下面的版本一样。

我从这里开始,将变量$_POST['Find']指定为空字符串 - 如果用户根本没有发送表单,那么我们将输出该值。如果$results不为空,那么我们搜索数据库,遍历结果集,在此循环中创建HTML字符串,并将结果存储在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> ,以明确表示它已填充在循环内,它包含一个行,而不是所有行。

RECORD_AUDIO