php - PDO MySQL 查询只返回一组结果

标签 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>

最佳答案

乍一看,这似乎只是因为您将功能拆分得太多了。

在页面顶部,您可以建立数据库连接并检索结果集。然后通过 PDO 语句对象回显 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>

关于php - PDO MySQL 查询只返回一组结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38163027/

相关文章:

php在设置准备语句的try block 中执行 undefined variable

php - Symfony4 总是重定向到 index.php

php - 在 php/symfony2 中有条件地创建和保存单独的日志文件

mysql - 获取加入结果的最新记录

mysql - 每 30 分钟分组时间戳

php - 在 PDO 语句中将相同的 id 分配给 2 个 MySQL 表行

php - 从搜索栏中的用户输入中删除单引号

php - 如何在 PHP 中使用类型提示来指定模板内的变量范围? (特别是 PhpStorm)

php - Google API php 客户端 - 检索搜索结果详细信息

mysql - MySQL 中每个应用程序的用户数