开发者

simple question of scope using a MySQL class in PHP

开发者 https://www.devze.com 2023-02-12 05:47 出处:网络
This should be a no brainer, its late and i cant see what i am doing wrong: MySQL class: class MySQL { public $db;

This should be a no brainer, its late and i cant see what i am doing wrong:

MySQL class:

class MySQL
{
public $db;
private $result;

public function __construct ($host, $user, $password, $database)
{
  $this -> connectDB ($host, $user, $password, $database);
}

public function __destruct ()
{
  $this -> breakDB();
}

private function connectDB ($host, $user, $password, $database)
{
  $this -> db = mysql_connect ($host, $user, $password) or die (mysql_error());
  if (is_resource ($this -> db))
  {
    mysql_select_db ($dat开发者_JAVA技巧abase) or die (mysql_error());
    mysql_set_charset('utf8',$this -> db); 
  }
}

private function breakDB()
{
  if (is_resource ($this -> db))
  {
    mysql_close ($this -> db);
    }
}
}

class using MySQL:

class Scraper {
private $urls_array = array();
private $mysql;

public function __construct ()
{
        $this -> mysql = new MySQL ('xxx', 'xxx', 'xxx', 'xxx');
}
private function getURLs($city=NULL,$provider=NULL) {

    /* Get all URLs to scrape */
    $result = $this -> mysql -> db = mysql_query("SELECT `xxx`,`xxx`,`xxx`, `xxx` FROM `URL` WHERE `xxx` = '1'");
   }
   }

The line i am having probs with is:

$result = $this -> mysql -> db = mysql_query("SELECT `xxx`,`xxx`,`xxx`, `xxx` FROM `URL` WHERE `xxx` = '1'");

I dont know how to use $mysql correctly so it sends the mysql_query to the connection i opened in the constructor? Any help apreciated THANKS!


You just need to rearrange the line a bit:

$result = mysql_query("SELECT `xxx`,`xxx`,`xxx`, `xxx` FROM `URL` WHERE `xxx` = '1'",
                      $this -> mysql -> db);

I would suggest creating a query method in your MySQL class though and making the db private.

At its most basic:

class MySQL {
   private $db;

   // ... as before ...

   public function query($queryText) {
       return mysql_query($queryText, $this->db);
   }
}

Of course, using mysqli might be a better idea all round.


You could make things a little easier on yourself by including a query function on the MySQL class you've created. The basic jist would look like this:

public function query($sqlQuery)
{
     return mysql_query($sqlQuery, $this->db);
}

You would use it like so:

$result = $this->mysql->query("SELECT `xxx`,`xxx`,`xxx`, `xxx` FROM `URL` WHERE `xxx` = '1'");


You would have to do this:

$result = mysql_query("SELECT ...", $this->mysql->db);

The $db property only holds the MySQL resource which you can optionally supply to the mysql functions. It would seem to make more sense if you included a query method in your MySQL class so this happens transparently and you can use $this->mysql->query('SELECT ...').

0

精彩评论

暂无评论...
验证码 换一张
取 消