I've received Mixed responses on this depending what walk-through I read,
I've defined a class with 2 functions.
I want both functions to have access to the DB credentials
Currently, this code does not work unless I Copy and paste the variables into each function.
What am I doing wrong here?
<?php
class database {
function connect() {
var $username="my_username";
var $servername="localhost";
var $database="my_DB";
var $password="An_Awesome_Password";
var $con;
$con = mysql_connect($servername,$username,$password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
}
function disconnect() {
$con = mysql_connect($servername,$username,$password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_close($con);
}
}
?>
This block:
var $username="my_username";
var $servername="localhost";
var $database="my_DB";
var $password="An_Awesome_Password";
var $con;
Should come before the function()
, not inside it; but still inside the class
definition.
And it's good form to add an explicit visibility; private to start with:
class database {
private $username="my_username";
private $servername="localhost";
// etc. etc.
Then, the functions refer to them as:
$this->username;
$this->con;
etc.
Ideally you will want to have those credentials to be passed in by the constructor:
private $servername;
private $database;
private $username;
private $password;
private $con;
function __construct($host, $user, $password, $dbname)
{
$this->servername = $host;
$this->username = $user;
$this->password = $password;
$this->database = $dbname;
}
Even more ideally, learn about PDO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With