更新:用于计数的代码没有问题。连接到database
$this->conn = new PDO("mysql:host=". $this->host . ";db_name=" . $this->db_name, $this->username, $this->password);
db_name
应该是dbname
。所以像
$this->conn = new PDO("mysql:host=". $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
我正在尝试将PHP REST api
与mysql
数据库一起使用,但这似乎不起作用,因为我首先尝试从我的select
来database
,但是尽管数据库中有记录,但这return
仍然没有结果
下面是我的代码
database.php
<?php
class Database
{
//Database Credentials
private $host = "localhost";
private $username = "root";
private $password = "password";
private $db_name = "rtmdb";
public $conn;
//Get Database Connection
public function getConnection()
{
$this->conn = null;
//Try connection
try
{
$this->conn = new PDO("mysql:host=". $this->host . ";db_name=" . $this->db_name, $this->username, $this->password);
$this->conn->exec("set names utf8");
}
catch(PDOException $exception)
{
echo "Connection error:" . $exception->getMessage();
}
return $this->conn;
}
}
admin.php 从数据库中选择
<?php
class Admin
{
//Database Connection and Table name
private $conn;
private $table_name = "admin";
//object properties
public $id;
public $fname;
public $lname;
public $oname;
public $uname;
public $email;
public $idnumber;
public $password;
public $profimage;
public $datecreated;
public $modifiedby;
public $datemodified;
public $status;
//Construct $db as database connection
public function __construct($db)
{
$this->conn = $db;
}
public function crawl()
{
$query = "SELECT * FROM " . $this->table_name;
$stmt = $this->conn->prepare($query);
$stmt->execute();
return $stmt;
}
}
crawl.php 文件以获取数据和json_encode
结果
//Include database and object files
include_once "../config/database.php";
include_once "../objects/admin.php";
$database = new Database();
$db = $database->getConnection();
$admin = new Admin($db);
//Query Admin
$stmt = $admin->crawl();
$num = $stmt->rowCount();
echo json_encode($num);
if($num > 0)
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$admin_list = array(
"id" => $id,
"uname" => $uname
);
array_push($admin_arr['records'], $admin_list);
}
echo json_encode($admin_arr);
}
else
{
echo json_encode(
array("message" => "No registered admin found.")
);
}
但是尽管有记录,我仍以rowCount()
为0和“没有注册管理员”的身份
下面是我的表格结构的屏幕截图
数据库结构
我在数据库中也只有一个数据
但是这些似乎没有给我任何结果。请问什么问题以及如何解决?