from("news")->where(-6ren">
gpt4 book ai didi

php - 嵌套方法对吗?为什么我得到空查询?

转载 作者:行者123 更新时间:2023-11-29 02:32:11 25 4
gpt4 key购买 nike

我想知道为什么我在使用该代码时会出错?有人可以帮忙吗?我的类(class)是使用嵌套方法从数据库中获取一些信息,假设我得到一个空查询

<?php
class db {
public function __construct(){
if(mysql_connect("localhost","root","0000")){
mysql_select_db("myblog");

}else{
echo mysql_error();
}

}

public function select($row){
$sql="SELECT".$row;
return $this;
}

public function from($table){
$sql.="FROM".$table;
return $this;
}

public function where($condition){
$sql.="WHERE".$condition;
return $this;
}

}
$ddb=new db;
$qq=$ddb->select("*")->from("news")->where("id='1'");
$query= mysql_query($qq);
while($row=mysql_fetch_object($query)){
echo $row->title;
}
?>

最佳答案

您必须定义 __toString() 特殊方法才能将您的对象用作字符串:

class db {

private $sql = '';

public function __construct() {
if (mysql_connect("localhost", "root", "0000")) {
mysql_select_db("myblog");
} else {
echo mysql_error();
}
}

public function select($row) {
$this->sql = "SELECT ".$row;
return $this;
}

public function from($table) {
$this->sql .= " FROM ".$table;
return $this;
}

public function where($condition) {
$this->sql .= " WHERE ".$condition;
return $this;
}

public function __toString() {
return $this->sql;
}

}

$ddb = new db();
$qq = $ddb->select("*")->from("news")->where("id='1'");
$query = mysql_query($qq);
while ($row = mysql_fetch_object($query)) {
echo $row->title;
}

关于php - 嵌套方法对吗?为什么我得到空查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11471438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com