123abc
123abc

Reputation: 53

Object Oriented and Procedural Mysqli Help?

I asked a question earlier and a user stated that it looks like i'm oddly mixing the OO and procedural style usage of mysqli and that I should stick to either one or the other.

Can some one show me exactly what is wrong with my code and how my code should look like in OO and procedural form. I'm kind of curious now since the code I have seems to work for me, but then again I'm fairly new to PHP and MySQL and would like to learn the correct way.

Here is the code.

// 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);
}

Upvotes: 1

Views: 493

Answers (2)

Valentin Golev
Valentin Golev

Reputation: 10095

// 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();
}

And I don't think you should start learning oop this way. I recommend you http://php.net/manual/en/oop5.intro.php

Upvotes: 2

Kevin
Kevin

Reputation: 26524

I have used this in the past don't know if it helps, as this is not really the answer to your problem, but might be useful.

    <?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 ?>

then you can do this

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

Upvotes: 0

Related Questions