我正在尝试构建一个API来从mySQL返回数据。我仍然试图了解PDO的情况。我有以下查询应该返回数据库中的所有行,基于单个参数,但我注意到它经常返回1比应该返回少。如果有2行,则返回1,当有1行时,它不返回任何内容。
我附上了数据库结果的截图。
任何建议都将不胜感激。
[![<?php
// required header
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
// include database and object files
include_once '../config/database.php';
include_once '../objects/casualty.php';
// instantiate database and casualty object
$database = new Database();
$db = $database->getConnection();
// initialize object
$casualty = new casualty($db);
// set ID property of record to read
$casualty->id = isset($_GET\['id'\]) ? $_GET\['id'\] : die();
// query categorys
$stmt = $casualty->cemetery();
$num = $stmt->rowCount();
// check if more than 0 record found
if($num>0){
// products array
$casualtys_arr=array();
$casualtys_arr\["records"\]=array();
// retrieve our table contents
// fetch() is faster than fetchAll()
// http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// extract row
// this will make $row\['name'\] to
// just $name only
extract($row);
$casualty_item=array(
"ID" => $ID,
"Filename" => $fldgraphicname,
"Surname" => $fldsurname,
"FirstNameInitial" => $fldfirstnameinitial
);
array_push($casualtys_arr\["records"\], $casualty_item);
}
echo json_encode($casualtys_arr);
}
else{
echo json_encode(
array("message" => "No Casualties found.")
);
}
?>
<?php
class casualty{
// database connection and table name
private $conn;
private $table_name = "tblcasualty";
// object properties
public $id;
public $fldgraphicname;
public $fldsurname;
public $fldfirstnameinitial;
public function __construct($db){
$this->conn = $db;
}
public function cemetery(){
// query to read single record
$query = "SELECT *
FROM
tblnames
WHERE
tblcemetery_ID = ?
ORDER BY ID
";
$stmt = $this->conn->prepare( $query );
// bind id of product to be updated
$stmt->bindParam(1, $this->id, PDO::PARAM_INT);
// execute query
$stmt->execute();
// get retrieved row
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// set values to object properties
$this->fldgraphicname = $row\['fldgraphicname'\];
$this->fldsurname = $row\['fldsurname'\];
$this->fldfirstnameinitial = $row\['fldfirstnameinitial'\];
return $stmt;
}
}
?>][1]][1]
答案 0 :(得分:1)
在cemetery
功能中,您有fetch
。这是将光标前进到一个位置,所以当你回到主脚本并使用fetch
时,你总是在第二行。
解决方案:
fetch
,只返回所有值的数组。或
fetch
并返回结果集,以便fetch
完整阻止。