So i have decided that its time to modernize my code by updating some of my script from mysql to PDO. Ihave used the last days trying to get to know PDO better, but i cant relate the examples that i have found to my script.
Database Connection:
mysql_connect('localhost', 'root', '') or die ('The server is facing issues at the moment');
mysql_select_db('openchat') or die('Problem with connecting to the database');
Php function with db connection included:
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `user` WHERE `username` = '$username'"), 0) == 1) ? true : false;
}
The function checks if the user already exists, where $username is the posted username in a form, and the function checks if the username is taken or not. I am just showing a small part of the code so i hope this is enough information to get the code :)
Update
I think i finnaly have made an updated version that works!
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=openchat', 'user', 'user123');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
die('The server is facing issues' . '</br>' . $e->getMessage());
}
function test() {
global $db;
$query = $db->query("SELECT COUNT(`user_id`) FROM `user` WHERE `username` = 'testbruker'");
$result = $query->fetchColumn();
return ($result == 1) ? true: false;
}