首页 新闻 会员 周边

php小白,为啥链接了数据库,前端没报错,也没数据显示???

0
悬赏园豆:15 [已解决问题] 解决于 2022-09-20 08:38

两个页面的代码,刚学面向对象,绕晕了已经。

////////////////////////////这里是index.php页面代码
	require( 'Query.php' );
	class Db{
		protected static $pdo = null;
		public static function connection(){
			self::$pdo = new PDO('mysql:host=127.0.0.1;dbname=php10-7','root','root');
		}
		//静态方法的重载
		public static function __callStatic($name,$arguments){
			//链接上数据库
			self::connection();
			//实例化查询类
			$query = new Query(self::$pdo);
			//访问query中的方法
			return call_user_func_array([$query,$name],[$arguments[0]]);
		}
	}

	$cats = Db::table('msg')
		->field('id,username,content')
		->where('id >= 2')
		->select();
		foreach($cats as $cat){
			print_r($cat);echo '<br>';
		}
?>

//////////////////////////////////这里是Query.php页面代码
<?php
	//常用的数据库查询操作
	class Query{
		//链接对象
		public $pdo = null;
		//数据库名称
		public $table = '';
		//字段列表
		public $field = '';
		//查询条件
		public $where = '';
		//显示数量
		public $limit = 0;
		//构造方法
		public function __construct(PDO $pdo){
			$this->pdo = $pdo;
		}
		public function table($table){
			$this->table = $table;
			return $this;
		}
		public function field($field){
			$this->field = $field;
			return $this;
		}
		//设置查询条件
		public function where($where){
			$this->where = $where;
			return $this;
		}
		//设置显示数量
		public function limit($limit){
			$this->limit = $limit;
			return $this;
		}

		//创建SQL语句
		public function select(){
			//设置查询条件
			$field = empty($this->field)?'*':$this->field;
			$where = empty($this->where)?'':'WHERE'.$this->where;
			$limit = empty($this->limit)?'':'LIMIT'.$this->limit;
			$sql = 'SELECT'.$field.'FROM'.$this->table.$where.$limit;
			$stmt = $this->pdo->prepare($sql);
			$stmt->execute();
			return $stmt->fetchAll(PDO::FETCH_ASSOC);
		}
	}
?>
sunvenet的主页 sunvenet | 初学一级 | 园豆:189
提问于:2022-09-17 17:28

来个大神救救孩子吧。

sunvenet 1年前
< >
分享
最佳答案
0

转json格式输出看看

收获园豆:15
Biuget-Golang | 小虾三级 |园豆:783 | 2022-09-19 09:26
其他回答(1)
0

你echo输出一下$sql语句,你会发现sql语句少了一些空格。把这些空格拼接上。

Sui丶便 | 园豆:198 (初学一级) | 2022-09-19 14:33

谢谢大佬指点,真的是太细了,现在OOP这块都快绕晕了。

支持(0) 反对(0) sunvenet | 园豆:189 (初学一级) | 2022-09-20 08:38

我结帖结错人了,咋整啊

支持(0) 反对(0) sunvenet | 园豆:189 (初学一级) | 2022-09-20 08:39
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册