Working with PHP and MySQL - need a good and secure design with OO design
Posted
by
Andrew
on Stack Overflow
See other posts from Stack Overflow
or by Andrew
Published on 2012-11-03T16:49:19Z
Indexed on
2012/11/03
17:01 UTC
Read the original article
Hit count: 199
I am new to PHP-> first time developer. I am working on my web application and it is nearly done; nevertheless, most of my sql was done directly via code using direct mysql requests. This is the way I approached it:
In classes_db.php I declared the db settings and created methods that I use to open and close DB connections. I declare those objects on my regular pages:
class classes_db {
public $dbserver = 'server;
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
$dbhandle = mysql_connect($this->dbserver, $this->dbusername, $this->dbpassword);
if (!$dbhandle) {
die('Could not connect: ' . mysql_error());
}
$selected = mysql_select_db($this->dbname, $dbhandle)
or die("Could not select the database");
return $dbhandle;
}
function closeDb($con) {
mysql_close($con);
}
}
On my regular page, I do this:
<?php
require 'classes_db.php';
session_start();
//create instance of the DB class
$db = new classes_db();
//get dbhandle
$dbhandle = $db->openDb();
//process query
$result = mysql_query("update user set username = '" . $usernameFromForm . "' where iduser= " . $_SESSION['user']->iduser);
//close the connection
if (isset($dbhandle)) {
$db->closeDb($dbhandle);
}
?>
My questions is: how to do it right and make it OO and secure? I know that I need incorporate prepared queries-> how to do it the best way? Please provide some code
© Stack Overflow or respective owner