how to change mysql_connect() to PDO - php

This is my db connect class which is working with php5.3 but it not working after i updated the php5.4 and show error that it's expired.
class DB {
function DB() {
$this->host = "localhost";
$this->db = "dbtest";
$this->user = "root" ;
$this->pass = "password";
$this->link = mysql_connect($this->host, $this->user, $this->pass) or die("<br>Could not connect 1: " . mysql_error());
mysql_select_db($this->db);
}
function query($query) {
$result = mysql_query($query, $this->link) or die ("<br>Could not execute command 1: ".mysql_error());
return $result;
}
function thislink() {
return $this->link;
}
function close() {
mysql_close($this->link);
}
}
How to change it into PDO or mysqli so the wamp could use it

You can't.
Your class is not a black box, you have for example a public method that returns the MySQL link identifier:
function thislink() {
return $this->link;
}
If you change that to another database interface, you will run into problems when you call this method as it will not contain what the calling end is expecting.
The same applies to your public query() method:
function query($query) {
$result = mysql_query($query, $this->link) or die ("<br>Could not execute command 1: ".mysql_error());
return $result;
}
That returns a mysql resource in case of for example a SELECT statement so if you change that to msyqli or PDO, the calling side will not be able to handle it.

class DB {
function DB() {
$this->host = "localhost";
$this->db = "dbtest";
$this->user = "root" ;
$this->pass = "password";
$this->link = new PDO("mysql:host=$this->host;dbname=$this->db", $this->user, $this->pass);
}
function query($query) {
$result = $this->link->query($query);
return $result;
}
function thislink() {
return $this->link;
}
function close() {
$this->link = NULL;
}
}

Your class should look something like this:
Note that I change the constructor to __construct(), since in PHP 7 the other way what you used will be deprecated. Also I put the variables as arguments in the constructor with default values. I also enabled error mode for your PDO connection, only have it on in testing!, never in production.
<?php
class DB {
public $host;
public $db;
public $user;
public $pass;
private $link;
public function __construct($host = "localhost", $db = "dbtest", $user = "root", $pass = "password") {
$this->host = $host;
$this->db = $db;
$this->user = $user;
$this->pass = $pass;
try {
$this->link = new PDO("mysql:host={$this->host};dbname={$this->db}", $this->user, $this->pass);
$this->link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOExcpetion $e) {
echo $e->getMessage();
}
}
function query($query) {
$stmt = $this->link->prepare($query);
$stmt->execute();
return $stmt;
}
function thislink() {
return $this->link;
}
function close() {
$this->link = null;
}
}
?>
For more information about PDO see the manual: http://php.net/manual/en/book.pdo.php
You may also want to take a look into prepared statements.

Related

How to create 2 PDO database connection instances PHP

I currently have a class which creates one database connection, however I would like to create another connection too. I have tried copying the class structure but just renaming the variables and functions however that doesn't work and it seems like it doesn't detect where my new PDO connection is as I get error Uncaught Error: Call to a member function prepare() on null in. What is the best approach to take in my case when creating 2 database connections?
config.php:
<?php
class Database
{
private $host = "localhost";
private $db_name = "database1";
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;
}
}
?>
class.user.php:
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
You could create your User class and pass the connection to the constructor. This will give you flexibility to swap out the connection.
Regarding your database class, it seems to be a wrapper, to create a PDO connection. You could do away with it, or extend the class with different params.
Perhaps look at dependency injection, and containers. They might help you here.
<?php
class User
{
private $conn;
public function __construct(PDO $conn)
{
$this->conn = $conn;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}

Implementing mysqli procedural with a class

so recently I've been trying to use more procedural mysqli for practise, and have been looking at http://www.phpknowhow.com/mysql/mysqli-procedural-functions/, and also w3schools as reference, but i'm still having trouble so I thought I'd ask.
I have this database.php file where I have alot of stuff but the important stuff is
class Database{
public $host = DB_HOST;
public $username = DB_USER;
public $password = DB_PASS;
public $db_name = DB_NAME;
public $link;
public $error;
public function __construct(){
$this -> connect();
}
private function connect(){
$link = mysqli_connect($this->host,$this->username,$this->password,$this->db_name);
if(!$link){
echo "Failed".mysqli_error($link);
}
}
// create select method
public function select($query){
$result = mysqli_query($link,$query) or die("didnt work".mysqli_error($link));
if(mysqli_num_rows($result) > 0){
return $result;
}
else{
return false;
}
}
Now the way it currently works fine in my index.php file is simply by doing something like
$db = new Database();
//CREATe query
$query = "SELECT * FROM posts";
$posts = $db->select($query);
Is there any way to implement $posts = $db->select($query) with procedural functions? Before I have done stuff like mysqli_query($link,$query), but link is public here and inside a class so I can't do that, plus I want to access the function select . Thanks!
$link is not defined in your function select.
Modify your connect function:
private function connect() {
$this->link = mysqli_connect($this->host, $this->username, $this->password, $this->db_name);
if(!$this->link) {
echo "Failed: " . mysqli_error($this->link);
}
}
Now $this->link may be used in your select function:
public function select($query){
$result = mysqli_query($this->link, $query) or die("didn't work: " .mysqli_error($this->link));
if(mysqli_num_rows($result) > 0) {
return $result;
}
else{
return false;
}
}
I suggest you read the PHP OOP documenentation (at least the first chapters) to get a better understanding.

mysqli Object Oriented Programming

I'm trying to make my login homepage work. At the first I built my query with mysql but I always got the error "query is empty" so I decided to change over to mysqli. I'm now getting the error "Warning: mysqli_query() expects at least 2 parameters".
how can I call the first parameter "$db" in my "mysqli_query($db, $string)" from the method "connect()" in the class "database2" to make it work?
I tried with " $result = $this->cxn->query($query)" but then i got the error "Fatal error: Call to undefined method Database2::query()
<?php
class Login
{
private $username;
private $password;
private $cxn; // Database object.
function __construct($username, $password)
{
// Set data
$this->setData($username, $password);
// connect to db
$this->connectToDb();
//get Data
$this->getData();
}
private function setData($username, $password){
$this->username = $username;
$this->password = $password;
}
private function connectToDb(){
include 'models/database2.php';
$vars = "include/vars.php";
$this->cxn = new Database2($vars);
}
private function getData(){
$query ="SELECT 'username', 'password' FROM 'users' WHERE 'username' = '$this->username'
AND 'password' = '$this->password'";
$result = mysqli_query($query) or die(mysql_error());
$num_row = mysqli_num_rows($result);
if ($num_row>1) {
return TRUE;
}else{
throw new Exception("The query was not successful!");
}
}
function close(){
$this->cxn->close_connect();
}
}
?>
Database2 class:
<?php
class Database2{
private $host;
private $user;
private $password;
private $database;
function __construct($filename){
if(is_file($filename)){
include $filename;
}else{
throw new Exception("Error Processing Request");
}
$this->host = $host;
$this->user = $user;
$this->password =$password;
$this->database =$database;
$this->connect();
}
public function connect(){
// connect to the server.
$db = new mysqli($this->host, $this->user, $this->password);
if ($db->connect_errno) {
die("We are sorry, you could not be connected to the server,
plaese check your connection setting!");
}else{
echo "You are connected to the database";
}
}
public function close_connect(){
mysql_close();
}
}
?>
i appreciate any help
If you use procedural style, you have to set and use a "$db" variable in the database2 class.
Set the variable in the connect function:
$this->db = new mysqli($this->host, $this->user, $this->password);
And then, you can use the $db in the database2 object
$result = mysqli_query($this->cxn->db, $query);

PHP code convert to PHP/MySQLi OOP

today i tried to convert my code to PHP/MySQLi OOP code.
class Database
{
private $host;
private $user;
private $password;
private $db;
private $mysqli;
function __construct()
{
$this->host = "*****";
$this->user = "*****";
$this->password = "******";
$this->db = "*****";
$this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);
if (mysqli_connect_errno()):
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
endif;
}
}
This is a script for the query's:
include_once("WD_Config/database.php");
class Adressen_Db
{
function __construct()
{
$this->database = new Database();
}
public function selecteer()
{
$query = "SELECT * FROM wd_adressen WHERE verborgen = 0 ORDER BY naam ASC";
$result = $this->database->mysqli->query($query);
return $result;
}
}
And this is how i call it.
$adressen = new Adressen_Db;
$adressen_result = $adressen->selecteer();
echo "<p>";
while ($row = $adressen_result->fetch_assoc()):
echo "<a href='http://maps.google.com/?q=".$row['voladres']."' target='_blank'>".$row['naam']."</a> woonachtig op <i>".$row['voladres']."</i><br>";
endwhile;
echo "</p>";
I alway get a "Call to a member function query() on a non-object". Doesn't matter what i trie ...
Can somebody tell me why that is?
Thanks!
The $mysqli variable in class Database is declared private.
You can access it only through setters and getters.
I think while you definitely need to have $mysqli as public so it can be accessed in the other method, there might be something else, as the error would be something like
trying to access private property in database class
or something like that, whereas your script throws a non-object call error
I think your new Adressen_Db; lacks the parenthesis:
$adressen = new Adressen_Db();
You can replace your code with this:
Config.php
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "your_database_name");
Now include this file in your database file
require_once 'config.php';
Class Database {
public $host = DB_HOST;
public $user = DB_USER;
public $pass = DB_PASS;
public $dbname = DB_NAME;
public $link;
public $error;
public function __construct() {
$this->getConnection();
}
private function getConnection() {
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
if (!$this->link) {
$this->error = "Connection failed" . $this->link->connect_error;
return false;
}
}
// for only select query
public function select($query) {
$result = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($result->num_rows > 0) {
return $result;
} else {
return false;
}
}
// for insert, delete and update
public function myquery($query) {
$myquery = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($myquery) {
return $myquery;
} else {
return false;
}
}
}
Now, make your queries like this:
<?php
require_once './lib/Database.php';
?>
<?php
class Admin {
private $db;
public function __construct() {
$this->db = new Database();
}
public function getData(){
$query = "SELECT * FROM admin";
$result = $this->db->select($query);
if($result != false){
while($row = $result->fetch_assoc()){
// do your thing
}
}
}
public function insert(){
$query = "INSERT INTO admin(admin_name) VALUES('$admin_name')";
$result = $this->db->myquery($query);
if($result){
$msg = "User has been added successfully.";
return $msg;
} else {
$msg = "Error while adding user. Please try again.";
return $msg;
}
}
}
Do this.

Error while adding PDO to my code

I have connection.php file where i am initializing PDO in the $db.
And i want to check this validation in the User.php which i include after connection.php.
but it is giving me error .
try {
$db = new PDO("mysql:dbname=$db_name;host=$db_host", $db_username,$db_password);
echo "PDO connection object created";
}
catch(PDOException $e){
echo $e->getMessage();
}
How can i validate this code by executing PDO.
How i will pass the PDO to the User Class..
Fatal error: Call to a member function query() on a non-object in /var/www/youngib/rahul/yapi/user.php on line 41
$sql="select * from users where email='$this->email'";
$rs=$db->query($sql);
if(mysql_num_rows($rs)>0){
$msg=geterrormsg(4);
//email already exist
echo $msg= "{ 'success': 'false','msg':'$msg' ,'error_code':'4' }";
return false;
}
Please Help.
Thanks .
Inject it in to the class or make a singleton DB class like...
Injection:
class User
{
protected $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
public function getDb()
{
return $this->db;
}
public function isUser($email)
{
$stmt = $this->getDb()->prepare('select count(email) as user_exists from users where email = :email');
return (bool) $stmt->execute(array(':email' => $email))->fetchColumn();
}
}
Singleton:
class Database {
protected $pdo;
protected static $instance;
protected function __construct($dsn, $user, $password)
{
$this->pdo = new PDO($dsn, $user, $password);
}
public static function getInstance()
{
if(!self::$instance)
{
// normally you would load the dsn, user, and password from a config file
$db = Config::get('db');
self::$instance = new self($db['dsn'], $db['user'], $db['password']);
}
return self::$instance;
}
public function getDb()
{
return $this->pdo;
}
}
class User
{
protected $db;
public function __construct(PDO $db = null)
{
if(null !== $db)
{
$this->db = $db;
}
}
public function getDb()
{
if(!$this->db)
{
$this->db = Database::getInstance()->getDb();
}
return $this->db;
}
public function isUser($email)
{
$stmt = $this->getDb()->prepare('select count(email) as user_exists from users where email = :email');
return (bool) $stmt->exectute(array(':email' => $email))->fetchColumn();
}
}
I hate to say this, but try just adding
global $db;
before your $db->query($sql); line. It might work, depending on exactly where the $db was created.
That said, prodigitalson's answer is a vastly improved approach, it just involves fixing your entire design, which involves more up front work :)

Categories