I downloaded this code but I don't understand the edit.
I would like to know what is $host
and $username
.
If I get a public server how do I change it
<?php
class Database
{
private $host = "localhost";
private $db_name = "test";
private $username = "root";
private $password = "";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
?>
This is a PHP class that has some attributes and a method. The code doesn't do anything by itself since the nothing has been instantiated. I rewrote the code a little bit and added some comments. Let me explain:
<?php
// Define a class. We will use this class later to create an object. The object will create a database connection.
class Database
{
// Some attributes (variables for all objects created)
public $conn;
public $dsn;
public function connect($host, $db_name, $username, $password)
{
// We are using PDO, so before we continue, have a brief look at this:
// http://php.net/manual/en/pdo.construct.php
// Create the DSN
$this->dsn = 'mysql:dbname=' . $db_name . ';host=' . $host;
// Try the following code, but catch any errors in the next code block
try {
$this->conn = new PDO($this->dsn, $username, $password);
// Set connection attributes. Learn more here: http://php.net/manual/en/pdo.setattribute.php
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
// echo the error if the try code block failed
echo "Connection error: " . $e->getMessage();
}
// Return the connection. You can assign a variable to the output of this method (function).
return $this->conn;
}
}
// Now instantiate the object to use the above code
$db = new Database();
$test = $db->connect('localhost', 'test', 'root', 'password');
Now, $test
can be used to read, insert, update and delete data from the database. And, the code is reusable.
$another = $db->connect('localhost', 'another', 'saferuser', 'password');
PDO Docs:
http://php.net/manual/en/pdo.construct.php (how to instantiate a PDO object) http://php.net/manual/en/book.pdo.php (entire docs)