Php 这是嵌套方法吗?为什么我得到空查询?
我想知道为什么我会在代码中出错?有人能帮忙吗? 我的类是使用嵌套方法从数据库中获取一些信息,假设我得到一个空查询Php 这是嵌套方法吗?为什么我得到空查询?,php,mysql,methods,nested,Php,Mysql,Methods,Nested,我想知道为什么我会在代码中出错?有人能帮忙吗? 我的类是使用嵌套方法从数据库中获取一些信息,假设我得到一个空查询 <?php class db { public function __construct(){ if(mysql_connect("localhost","root","0000")){ mysql_select_db("myblog"); }else{ echo mysql_error(); } } public function s
<?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;
}
?>
您需要在要附加到$sql
的每个方法中使用$this
// Declare the class property
public $sql = "";
// And use $this->sql in the methods
// Also note whitespace added around SELECT, FROM, WHERE
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;
}
然后在查询它时,使用$ddb->sql
,因为您没有返回sql字符串
$ddb->select("*")->from("news")->where("id='1'");
$query = mysql_query($ddb->sql);
不用说,希望您打算调用mysql\u real\u escape\u string()
对您构造到where()
方法中的任何变量。事实上,您没有特别的转义。在$qq上运行var_转储
这将立即向您显示问题所在
在我看来,您的查询中似乎缺少了几个空格,并且您没有返回查询字符串$sql,而是返回数据库类中的$this
使用$this->sql
而不是方法中的$sql
,from
,where
像这样输出查询:$ddb->select(“*”)->from(“news”)->where(“id='1')->sql
,或者创建一个getSQL()
方法,该方法只返回$sql
字段并像$ddb->select(“*”->from(“news”)->where(“id='1')->getSQL()
那样查询它
您还应该考虑创建一个创建<代码> MySqLyQueQue>代码>的方法(不只是字符串)或一些方法来检索方法,因此使用起来更容易。
您必须定义一个特殊的方法来使用对象作为字符串:
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;
}
向每个方法添加调试,以便了解它们返回的内容。回显完成的语句,以便查看它的外观。您的查询最终没有空格SELECT*FROMnewsWHEREid=1
@rsplak,实际上,mysql\u query()在这段代码中甚至没有字符串。当发出回显语句时,输出是SELECT*SELECT*fromNewsSelect*FROMnewsWHEREid=1如何解决这个问题并得到正确的查询?这对我检测错误很有用,但没有解决所有问题,谢谢