Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP OOP MySQL connect

Tags:

oop

php

mysql

Ok, so I am a complete beginner at OOP in php, and I thought I would try something easy to start with, however it it not working how I would expect

<?php 

class mySQL{

  var $host;
  var $username;
  var $password;
  var $database;

  public function connect($set_host, $set_username, $set_password, $set_database){
    $this->host = $set_host;
    $this->username = $set_username;
    $this->password = $set_password;
    $this->database = $set_database;

    mysql_connect("$host", "$username", "$password")or die("cannot connect");
    mysql_select_db("$database")or die("cannot select DB");

  }

}

$connect = new mySQL();
$connect -> connect('localhost', 'user', 'pass', 'database1');

$settings_query = mysql_query("SELECT * FROM settings");
$settings = mysql_fetch_array($settings_query);

echo $settings['title']; 

?>

All I am getting is "cannot connect" on my page.

like image 698
derrick Avatar asked Mar 04 '26 21:03

derrick


1 Answers

In your connect method, you are trying to use the following variables :

  • $host
  • $username
  • $password
  • $database

that would be local to your connect() method.
But those variables don't exist.


Instead, if you want to use the [**properties**][1] `$host`, `$username`, and `$password` that are defined in your class, **you must use `$this` to access them** :
  • $this->host
  • $this->username
  • $this->password
  • $this->database

For more informations, take a look at this page of the PHP manual -- and you might want to read more about Classes and Objects.

like image 71
Pascal MARTIN Avatar answered Mar 06 '26 13:03

Pascal MARTIN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!