我想创建一个API来访问有关我们使用的MySQL数据库中的库赞助人和书籍的信息。它基于CRUD示例,除了GET之外的一切都被删除了
所以我有4个文件:
持有职能的db_pdo_mysql.php
index.php
调用班级
book.php
持有书类
patron.php
持有赞助人类
在index.php文件中,我将这些类调用为:
require_once '../../restler/restler.php';
spl_autoload_register('spl_autoload');
$r = new Restler();
$r->addAPIClass('book');
$r->addAPIClass('patron');
$r->handle();
book.php中:
<?php
class book {
public $dp;
function __construct(){
/**
* $this->dp = new DB_PDO_Sqlite();
* $this->dp = new DB_PDO_MySQL();
* $this->dp = new DB_Serialized_File();
*/
$this->dp = new DB_PDO_MySQL();
}
function get($id=NULL) {
return is_null($id) ? $this->dp->getAll() : $this->dp->book($id);
}
}
}
?>
patron.php:
<?php
class patron {
public $dp;
function __construct(){
/**
* $this->dp = new DB_PDO_Sqlite();
* $this->dp = new DB_PDO_MySQL();
* $this->dp = new DB_Serialized_File();
*/
$this->dp = new DB_PDO_MySQL();
}
function get($id=NULL) {
return is_null($id) ? $this->dp->getAll() : $this->dp->patron($id);
}
}
?>
和db_pdo_mysql.php
<?php
class DB_PDO_MySQL
{
private $db;
function __construct ()
{
try {
//update the dbname username and password to suit your server
$this->db = new PDO(
'mysql:host=[HOST REMOVED];dbname=[DATABASE REMOVED]', '[USERNAME REMOVED]', '[PASSWORD REMOVED]');
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,
PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new RestException(501, 'MySQL: ' . $e->getMessage());
}
}
function patron ($id)
{
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql = 'SELECT * FROM patrons WHERE code = ' . mysql_escape_string(
$id);
return $this->id2int($this->db->query($sql)
->fetch());
} catch (PDOException $e) {
throw new RestException(501, 'MySQL: ' . $e->getMessage());
}
}
function book ($id)
{
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql = 'SELECT * FROM books WHERE barcode = ' . mysql_escape_string(
$id);
return $this->id2intBooks($this->db->query($sql)
->fetch());
} catch (PDOException $e) {
throw new RestException(501, 'MySQL: ' . $e->getMessage());
}
}
function getAll ()
{
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$stmt = $this->db->query('SELECT * FROM patrons');
return $this->id2int($stmt->fetchAll());
} catch (PDOException $e) {
throw new RestException(501, 'MySQL: ' . $e->getMessage());
}
}
private function id2int ($r)
{
if (is_array($r)) {
if (isset($r['code'])) {
$r['code'] = intval($r['code']);
} else {
foreach ($r as $a) {
$a['code'] = intval($a['code']);
}
}
}
return $r;
}
private function id2intBooks ($r)
{
if (is_array($r)) {
if (isset($r['barcode'])) {
$r['barcode'] = intval($r['barcode']);
} else {
foreach ($r as $a) {
$a['barcode'] = intval($a['barcode']);
}
}
}
return $r;
}
}
?>
我使用[domain]/api/test/index.php/patron/[patron id]
和[domain]/api/test/index.php/book/[book id]
来访问数据。
我很困惑!
答案 0 :(得分:0)
我在index.php中犯了一个错误,我没有正确地调用patron类!