聘我网

新概念招聘3.0

一个mysql的类

vote up0vote downstar

我写了一个mysql的类,并且想要调用但是老出问题请帮我看看

   class mysql{

    private $host;
    private $user;
    private $pass;
    private $db;
  function __construct($host,$user,$pass,$db){
       $this->host=$host;
       $this->user=$user;
       $this->pass=$pass;
       $this->db=$db;
       $this->connect();

  }
  function connect(){

     mysql_connect($this->host,$this->user,$this->pass);
              mysql_select_db($this->db);
  }
function query($sql){
    return mysql_query($sql);
}
function num_rows($sql){
    return mysql_num_rows($sql);
}

 function fetch_array($query) {
         mysql_fetch_array($query);
    }
 //==========================================

 function select($table){
    $this->query("select * from $table");
}
  function insert($table,$name,$value){
    $this->query("insert into $table ($name) values ($value)");
  }
  function update($table,$name,$value,$id){
    $this->query("update $table set $name=$value where id=$id");
  }
  function delete($table,$name,$value){
    $this->query("delete from $table where $name=$value");
  }

}

这是我写的调用

$sql=new mysql("127.0.0.1","root","dba","test");
$result=$sql->select("test");
while($rows=$sql->fetch_array($result)){
    echo $rows['name'];
}

出现的错误是Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in D:\php\stady\test.php on line 37。这个错误好像是说我的mysql语句有错,但是那条语句不会有错啊,到底是哪里错了请帮我看下,我经常调用mysql的时候会出现这个问题但是是类写错了还是调用写错了

更新 我用

sql=new mysql("127.0.0.1","root","dba","register");
if(isset($sql)){
        echo "成功";
    }
else{
    echo "失败";
}

    if( $result=$sql->query("select * from admin")){
        echo "成功";
    echo    $sql->num_rows($result);

    }
else{
    echo "失败";
}

这种方法查出好像是我的select这个方法写错了但是不知道错哪里了,前面那个方法可以得出结果

 

1 个答复

vote up0vote down

问题似乎处在这里:

 function select($table){
    $this->query("select * from $table");
}

应该是

 function select($table){
    return $this->query("select * from $table");
}

另外,一般最好把$conn带上,如下:

function getDBConn()
{
    global $LOCAL_DB_PORT;
    global $LOCAL_DB_USER;
    global $LOCAL_DB_PASS;
    $con = mysql_connect("localhost:".$LOCAL_DB_PORT, $LOCAL_DB_USER, $LOCAL_DB_PASS);
    mysql_select_db("ip", $con);
    mysql_query("set names utf8", $con);
    return $con;
}

$con = getDBConn();

$result = mysql_query($query,$con);
链接

您的回答





不是您要找的问题? 浏览其他含有标签 的问题或者 自己问个.