[SOLUTION] Serverside using join PDO PHP
[SOLUTION] Serverside using join PDO PHP
Hello That such!
Sharing source code using php pdo and join two tables
Greetings.
/CODE/
database
CREATE DATABASE data
USE data
CREATE TABLE IF NOT EXISTS city
(
id
int(11) NOT NULL AUTO_INCREMENT,
city_name
varchar(150) NOT NULL DEFAULT '',
PRIMARY KEY (id
)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
CREATE TABLE IF NOT EXISTS users
(
id
int(11) NOT NULL AUTO_INCREMENT,
name
varchar(150) NOT NULL DEFAULT '',
surname
varchar(150) NOT NULL DEFAULT '',
city_id
int(11) DEFAULT NULL,
PRIMARY KEY (id
),
KEY city_id
(city_id
)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
ALTER TABLE users
ADD CONSTRAINT users_ibfk_1
FOREIGN KEY (city_id
) REFERENCES city
(id
) ON DELETE CASCADE ON UPDATE CASCADE;
INSERT INTO city
(id
, city_name
) VALUES
(1, 'city 1'),
(2, 'city 2'),
(3, 'city 3');
INSERT INTO users
(id
, name
, surname
, city_id
) VALUES
(1, 'Jey', 'Lue', 1),
(2, 'Joe', 'Doe', 2),
(3, 'Alan', 'Beer', 3);
Replies
parametersdb.php
<?php
define('DB_NAME', 'database_name');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_PORT', '3306');
define('DB_MANAGER', 'mysql');
connection.class.php
<?php
require_once ('parametersdb.php');
class Connection {
private static $instance;
private $db;
private function construct() {
try {
$this->db = new PDO(DB_MANAGER . ':host=' . DB_HOST . ';port=' . DB_PORT . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
$this->db->exec("SET CHARACTER SET utf8");
}
catch(PDOException $e) {
throw new Exception($e->getMessage());
}
}
public function prepare($sql) {
return $this->db->prepare($sql);
}
public function query($sql) {
return $this->db->query($sql);
}
public static function getInstance() {
if (!isset(self::$instance)) {
$object = __CLASS;
self::$instance = new $object;
}
return self::$instance;
}
public function close() {
$this->db = null;
}
public function __clone() {
trigger_error('The cloning of this object is not permitted', E_USER_ERROR);
}
}
datatables.class.php
<?php
require_once ('connection.class.php');
class DataTables {
private static $instance;
private $db;
private function construct() {
$this->db = Connection::getInstance();
}
public static function getInstance() {
if (!isset(self::$instance)) {
$object = __CLASS;
self::$instance = new $object;
}
return self::$instance;
}
}
instance.php
<?php
header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');
require_once ('datatables.class.php');
$datatables = DataTables::getInstance();
$datatables->getJoinDatatables('users u', 'u.id', array('u.name', 'u.surname', 'c.city_name'), ' LEFT JOIN city c ON u.city_id = c.id ');
Thank you very much aperez21. much appreciated for your response. but my mysql query is bit complex and consists of several joining tables , let me try doing it by using ur method. thanks again.