我没有从menucanhan.php获取数据?type = view。我的代码有问题吗? Plz,帮我检查一下!非常感谢!
db.php:从localhost
继续数据<?php
class DB {
// Database credentials
private $dbHost = 'localhost';
private $dbUsername = 'root';
private $dbPassword = '';
private $dbName = 'thuctapcoso';
public $db;
public function __construct(){
if(!isset($this->db)){
// Connect to the database
try{
$conn = new PDO("mysql:host=".$this->dbHost.";dbname=".$this->dbName, $this->dbUsername, $this->dbPassword);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db = $conn;
}catch(PDOException $e){
die("Failed to connect with MySQL: " . $e->getMessage());
}
}
}
public function getRows($table,$conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$table;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['limit'];
}
$query = $this->db->prepare($sql);
$query->execute();
if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $query->rowCount();
break;
case 'single':
$data = $query->fetch(PDO::FETCH_ASSOC);
break;
default:
$data = '';
}
}else{
if($query->rowCount() > 0){
$data = $query->fetchAll(PDO::FETCH_ASSOC);
}
}
return !empty($data)?$data:false;
}
}
?>
/////////////////////////////////////////////// ////////////////////////////////////
menucanhan.php:
<?php
include 'db.php';
$db = new DB();
$tblName = 'menucanhan';
if(isset($_REQUEST['type']) && !empty($_REQUEST['type'])){
$type = $_REQUEST['type'];
switch($type){
case "view":
$records = $db->getRows($tblName);
if($records){
$data['records'] = $db->getRows($tblName);
$data['status'] = 'OK';
}else{
$data['records'] = array();
$data['status'] = 'ERR';
}
echo json_encode($data);
break;
default:
echo '{"status":"INVALID"}';
}
}
?>