2017-09-22 218 views
1

我在尝试构建一个API以从mySQL返回数据。我仍然试图抓住PDO。我有下面的查询应该返回从数据库中的所有行,基于单个参数,但我已经注意到它往往返回1比应该返回。当有两行时,它返回1,当有一行时它不返回任何内容。PDO SQL查询返回的行数比预期的要少

我附上了数据库结果的屏幕截图。

任何建议,将不胜感激。

[![<?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] 

回答

1

在你cemetery功能你有一个fetch。这是将光标前进一个位置,因此当您回到主脚本并使用fetch时,您总是位于第二行。

解决方案:

  1. 河套fetch在功能和刚刚返回的所有值的数组。

  • 不要在功能fetch并返回结果集,所以你可以fetch满块。