面向对象和程序Mysqli帮助?

时间:2009-11-06 17:58:50

标签: php mysql

asked a question earlier并且用户表示我看起来像oddly mixing the OO and procedural style usage of mysqli而且我应该坚持使用其中一种。

有人可以告诉我我的代码究竟出了什么问题以及我的代码在OO和程序形式中应该是什么样子。我现在有点好奇,因为我的代码似乎对我有用,但是我再次对PHP和MySQL很新,并希望学习正确的方法。

这是代码。

// Query member data from the database and ready it for display
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT users.*, categories.*, users_categories.* FROM users_categories INNER JOIN users ON users_categories.user_id = users.user_id INNER JOIN categories ON users_categories.category_id = categories.id WHERE users_categories.user_id=3");

if (!$dbc) {
    // There was an error...do something about it here...
    print mysqli_error($mysqli);
}

2 个答案:

答案 0 :(得分:2)

// Query member data from the database and ready it for display
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = $mysqli->query("SELECT users.*, categories.*, users_categories.* FROM     users_categories INNER JOIN users ON users_categories.user_id = users.user_id INNER JOIN categories ON users_categories.category_id = categories.id WHERE users_categories.user_id=3");

if (!$dbc) {
    // There was an error...do something about it here...
    print $mysqli->error();
}

我认为你不应该这样开始学习oop。我建议你http://php.net/manual/en/oop5.intro.php

答案 1 :(得分:0)

我过去曾经使用过它,不知道它是否有帮助,因为这不是你问题的答案,但可能有用。

    <?php // cnxVars
    class cnxVars {

 private $host = "localhost";
 private $host_un = "username";
 private $host_pass = "test123";
 private $host_db = "si";

 public function cnx() { // Connect to MySQL
  $this->cnx = mysql_connect($this->host, $this->host_un, $this->host_pass) or mysql_error(); }

 public function db() { // Select DB
  return mysql_select_db($this->host_db, $this->cnx) or mysql_error(); }


    } // End cnxVars ?>

然后你可以这样做

$mysql = new cnxVars();
$mysql->cnx();
$mysql->db();