The story so far
I am used to developing using the mysqli_connect()
function to connect to the database like so:
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "pass";
$db_name = "db";
$connect = mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysqli_select_db($connect, "$db_name") or die ("no database");
?>
When I connect in this way I always write my queries like:
$sql = mysqli_query($connect, "INSERT INTO table (column1, column2, column3) VALUES('$value1','$value2','$value3')") or die (mysql_error());
However I have recently been working on a project with a new hosting company who won't allow this. The above connection script will give a 500 error and when I asked the hosting company they said I should connect using PDO, which I have never done before.
I am now able to connect using this script:
<?php
class DbConnect {
const DB_HOSTNAME = 'localhost';
const DB_USERNAME = 'root';
const DB_PASSWORD = 'pass';
const DB_DATABASE = 'db';
public $error;
public function connect() {
try {
$db = new \PDO("mysql:dbname=" . self::DB_DATABASE . ";host=" . self::DB_HOSTNAME, self::DB_USERNAME, self::DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
$this->error = $e->getMessage();
return FALSE;
}
return $db;
}
public function fail($message) {
$out = "{$message}";
return $out;
}
public function success($message) {
$out = "{$message}";
return $out;
}
}
$connect = new DbConnect;
$db = $connect->connect();
if ($db === FALSE) {
echo $connect->fail($connect->error);
} else {
echo $connect->success("Connected to database");
}
?>
However, I am now trying to integrate this into an entire site and and am having some issues.
Question
First of all, I just replaced one connection script with the other using <?php include_once("../connect_to_sql.php"); ?>
(I didn't expect it to work, I just wanted to see what kind of errors I got) and besides a page full of errors I got the following at the very top. I thought if it was connecting by itself there should be nothing on my other pages where it is included that should cause the connection to fail:
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)
Secondly, when I do get this connecting correctly inside my other files I don't want to have to change every single query I'm making. Will the $connect
variable from the second connection file work the same way for the mysqli_query()
function? Or what would be the best way to go about this where I would have to make minimal changes.
And finally, what are the differences/benefits of connecting in this way or which way is better/more efficient?