首页 > 解决方案 > 使用 PDO 将数据提取到表中导致没有值

问题描述

我有个问题。我想将与用户相关的所有任务提取到一个表中。但是,结果是“0 个结果”。我确实尝试回显 print_r($allTask​​),结果是 Array() 1。我不知道是什么问题,因为在不完整的数据库中,有几个任务,但是当我获取它时什么都没有显示。有人可以向我解释吗?谢谢您的帮助

注意:我将 fetch 查询放在 if(isset($_POST['submit']) 中,因为我希望每次用户添加新任务并单击提交。不完整的数据库也会更新以显示添加的新任务到桌子上

<?php
session_start();
require 'connect.php';
if (isset($_POST['submit'])) {
$owner = $_SESSION['name'];
$title=$_POST['title'];
$description=$_POST['description'];
$due_date=$_POST['due_date'];
$time=$_POST['time'];
$state=0;
$insertQuery="INSERT INTO incomplete (owner, title, description, due_date, time, state)
VALUES (:owner, :title, :description, :due_date, :time, :state)";
$preparedInsertStatement = $conn->prepare($insertQuery);
$preparedInsertStatement->bindValue(':owner', $owner);
$preparedInsertStatement->bindValue(':title', $title);
$preparedInsertStatement->bindValue(':description', $description);
$preparedInsertStatement->bindValue(':due_date', $due_date);
$preparedInsertStatement->bindValue(':time', $time);
$preparedInsertStatement->bindValue(':state', $state);
$valueInsert=$preparedInsertStatement->execute();
if($valueInsert){
    echo 'Insert is done';
}
else{
    echo 'Insert is not successful';
} 
$displayQuery="SELECT * FROM incomplete where owner=':owner'";
$displayTask= $conn->prepare($displayQuery);
$displayTask->bindValue(':owner', $owner);
$displayTask->execute();
$allTask=$displayTask->fetchAll();
echo print_r($allTask);
if(count($allTask) > 0)
{
  echo "<table border=\"1\"><tr><th>ID</th><th>Title</th><th>Description</th><th>Due 
Date</th><th>Time</th></tr>";
foreach ($allTask as $row) {
    echo "<tr><td>".$row["id"]."</td><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["due_date"]."</td><td>".$row["time"]."</td></tr>";
}

  }else{
      echo '0 results';
  }

 }
  ?>

标签: phpmysql

解决方案


使用占位符值时,请绝对确保您没有引入任何其他语法。我可以看到owner=':owner'哪个是不正确的。占位符周围不应有引号。

这应该是:

'... owner=:owner'

PDO 负责转义。报价只是在路上。


推荐阅读