How do I query MySQL by this class and SET time_zone after every query? I'm having some trouble about where to place the timezone command in the following code block:
class MyDB {
private $connection;
public $last_query;
private $magic_quotes_active;
private $real_escape_string_exists;
function __construct(){
$this->open_connection();
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exists = function_exists("mysql_real_escape_string");
}
public function open_connection(){
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$this->connection){
die("Database connection failed: " . mysql_connect());
} else {
$db_select = mysql_select_db(DB_NAME, $this->connection);
if(!$db_select){
die("Database selection failed: " . mysql_error());
}
}
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
public function query($sql) {
$this->last_query = $sql;
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
return $result;
}
public function escape_value($value){
if($this->real_escape_string_exists){ // PHP v.4.3.0 or higher
//undo any magic quote effects so mysl_real_escape_string can do the work
if($this->magic_quotes_active){
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
} else { // before PHP v.4.3.0
// if magic quotes aren't already on then add slashes manually
if(!$this->magic_quotes_active) {
$value = addslashes($value);
}
// if magic quotes are active, then the slashes already exist
}
return $value;
}
public function fetch_array($result_set){
return mysql_fetch_array($result_set);
}
public function num_rows($result_set){
return mysql_num_rows($result_set);
}
public function insert_id($result_set){
return mysql_insert_id($this->connection);
}
public function affected_rows($result_set){
return mysql_affected_rows($this->connection);
}
private function confirm_query($result){
if(!$result){
$output = "Database query failed: " . mysql_error() . "<br /><br />";
$output .= "Last SQL query: ". $this->last_query;
die($output);
}
}
}
$database = new MyDB();
$db =& $database;
You could set it on the fly like this:
date_default_timezone_set('America/New_York');
Related
Is it possible to get different output when you run the exact same query from PHP vs. PHPMyAdmin? When I run
$sql = "SELECT IF(PersonA=200, PersonB, PersonA) AS Person
FROM People
WHERE PersonA=200 OR PersonB=200;";
I get the correct output from PHPMyAdmin but a different (incorrect) result from my PHP code above. The following is my SQL class I use.
<?php
class SQLQueryExecutor {
private $queryString;
private $conn;
private $db;
private $host;
private $username;
private $password;
public function __construct($queryString, $db, $host, $username, $password) {
$this->queryString = $queryString;
$this->conn = NULL;
$this->db = $db;
$this->host = $host;
$this->username = $username;
$this->password = $password;
}
// make connection to mysql database
public function makeConnection() {
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->db);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
// execute query
public function executeQuery() {
if ($this->conn != NULL)
{
$result = mysqli_query($this->conn, $this->queryString);
$rows = Array();
if ($result !== False) // resource returned?
{
while($row=mysqli_fetch_assoc($result))
{
$rows= $row;
}
return $rows;
}
}
return NULL;
}
// close sql connection
public function closeConnection() {
mysql_close($this->conn);
}
} // class
?>
I call this class as follows...
$user = $_GET['User_ID'];
$sql = "
SELECT IF(PersonA=$user, PersonB, PersonA) AS Person
FROM People
WHERE PersonA=$user OR PersonB=$user;";
$newSQLQueryExecutor = new SQLQueryExecutor($sql, "blah","blah", "blah", "blah");
$newSQLQueryExecutor->makeConnection();
$rows = $newSQLQueryExecutor->executeQuery();
$friends = Array("friends" => $rows);
$newSQLQueryExecutor->closeConnection();
print_r($friends);
The PHPMyAdmin prints all the correct rows but the PHP only prints the very last row.
Here is your issue, a mistake in the executeQuery() method
public function executeQuery() {
if ($this->conn != NULL) {
$result = mysqli_query($this->conn, $this->queryString);
$rows = Array();
if ($result !== False) { // resource returned?
while($row=mysqli_fetch_assoc($result)) {
$rows[] = $row;
// amended ^^
}
return $rows;
}
}
return NULL;
}
I want to ask help for my MySQLI OOP. My MySQLI Class look like this:
Class DB {
Private $connection;
Public Function __construct($host = "localhost", $user = "root", $password = "", $db = "social_network") {
$this->host = $host;
$this->db = $db;
$this->user = $user;
$this->password = $password;
$this->connection = #new mysqli($this->host, $this->user, $this->password);
$this->connection->set_charset("UTF-8");
if($this->connection->connect_errno > 0){
die('Tietokantapalvelimeen ei saada yhteyttä [' . $this->connection->connect_error . ']');
} else {
if(!$this->connection->select_db($db)) {
die('Tietokantaan ei saada yhteyttä: ' . $this->connection->error);
}
return $this->connection;
}
}
Public Function connect() {
if(!$this->connection){
return $this->connection;
}
return true;
}
Public Function disconnect() {
if($this->connection){
$this->connection->kill($this->connection->thread_id);
$this->connection->close();
}
return true;
}
Public Function query($sql) {
return $this->connection->query($sql);
}
Public Function result($sql) {
$query = $this->connection->query($sql);
if($query){
$result = array();
$i = 0;
while($row = $query->fetch_object()){
$result[$i] = $row;
$i++;
}
return $result;
} else {
return print $this->connection->error;
}
}
Public Function escape_string($sql) {
return $this->connection->real_escape_string($sql);
}
Public Function __destruct() {
$this->disconnect();
}
}
Example result:
$DB = new DB($_CONFIG['host'], $_CONFIG['user'], $_CONFIG['password'], $_CONFIG['db']);
$row = $DB->result("SELECT username, password FROM users WHERE username = T0niiiiii LIMIT 1");
print $row['username'];
I get error "Unknown column 'T0niiiiii' in 'where clause' ".
So what is wrong? How i fix that? Or anyone know ready MySQLI OOP?
If you don't wrap the value with apostrophes, MYSQL will 'think' you're referencing a column.
This should be your code:
$DB->result("SELECT username, password FROM users WHERE username = 'T0niiiiii' LIMIT 1");
You didn't even need to ask in here, the error message says it all.
And about retrieving the row, you could do this:
$query = $DB->query("SELECT username, password FROM users WHERE username = 'T0niiiiii' LIMIT 1");
foreach ($query->result() as $row)
{
echo $row->username;
echo $row->password; //Never echo the password, this is just for testing :P
}
I am making a module in which I am fetching users from Database Using OOP.
But due to some reason , records are not fetching, and there is no mysql error.
Here is my Code:
dbsetup_class.php :
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
/* echo "<pre>";
var_dump($this->dbc);
*/
//echo $sql;
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
And here is my index.php:
<?php
require_once("dbsetup_class.php");
$connection = new mySQL();
$connection->connect('localhost', 'admin', 'admin', 'oop_test');
//die('success');
$myquery = "SELECT * FROM users";
$query = $connection->query($myquery);
$array = $connection->fetch($query);
while($array)
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
What I am doing here?
Your fetch method expects SQL query, and not the result of a query. You should redefine it as (assuming that the client code is what you want as an interface):
public function fetch($resource)
{
$array = mysqli_fetch_array($resource);
return $array;
}
Also if you have results, your while will be infinite.
class MySQLDatabase {
private $connection;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$this->connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if(!$this->connection){
die("Database connection failed: ". mysql_error());
}
else {
$db_select = mysql_select_db(DB_NAME,$this->connection);
if(!$db_select){
die("Database connection failed: ". mysql_error());
}
}
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
public function query($sql){
$result = mysql_query($sql,$this->connection);
$this->confirm_query($result);
return $result;
}
public function fetch_array($result_set){
return mysql_fetch_array($result_set);
}
public function num_rows($result){
return mysql_num_rows($result);
}
public function affected_rows(){
return mysql_affected_rows($this->connection);
}
private function confirm_query($result){
if(!$result){
die("Database query failed: ". mysql_error());
}
}
}
$db = new MySQLDatabase();
this is the other bit {read.php}
require_once("db.php");
class Read{
private $table_name= "real_estate";
private $column_name = "Property_type";
function __construct(){
}
public function pro_type() {
global $db;
var_dump($db);
echo "<select name='".$this->column_name."'>";
$sql = sprintf("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s' AND COLUMN_NAME = '%s'",$this -> table_name,$this ->column_name);
$result = $db-> query($sql);
$row = $db->fetch_array($result);
$enumList = explode(",", str_replace("'", "", substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE'])-6))));
foreach($enumList as $value)
echo "<option value=$value>$value</option>";
echo "</select>";
}
}
link.php
require_once("read.php");
$link = new Read();
index.php
<?php
include '../inc/link.php';
$link -> pro_type();
?>
Every thing seems perfect, but it gives an error message saying that a query is being called on a non object. I actually called $db in another script, but nothing seems to be working.
What does the call in your other script look like? Should be something like this:
require_once('includes/mysql.php'); // Where your MySQLDatabase class resides
if(class_exists('MySQLDatabase')) {
$db = new MySQLDatabase();
// Should work from here
$db->query("SELECT * FROM `table` WHERE 1");
} else {
die('Unable to load class.');
}
I'm fairly new at PHP and so maybe this is a simple question. This is a class I use to update a database. The problem is that it keeps giving me an error at the line marked * because it can't find $con, which is clearly in the function openconn(). It seems I can't pass the connection to another function. Am I doing something wrong?Thanks
class retreats {
public $retreat_name = '';
function openconn() {
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("PHPTest", $con);
}
function closeconn(){
mysql_close($con);
}
function add_retreat(){
openconn();
$sql="INSERT INTO tbl_retreats (retreat_name) VALUES ('".$this->retreat_name."')";
if (!mysql_query($sql,$con)) *******
{
die('Error: ' . mysql_error());
}
echo "Record Successfully Added";
closeconn();
}
}
$con is a local variable for the function openconn. Try to change your code in this way:
class retreats {
public $retreat_name = '';
private $con;
function openconn() {
$this->con = mysql_connect("localhost","root","root");
if (!$this->con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("PHPTest", $this->con);
}
function closeconn(){
mysql_close($this->con);
}
function add_retreat(){
openconn();
$sql="INSERT INTO tbl_retreats (retreat_name) VALUES ('".$this->retreat_name."')";
if (!mysql_query($sql,$this->con))
{
die('Error: ' . mysql_error());
}
echo "Record Successfully Added";
closeconn();
}
}
A Simple PDO port of your code...
<?php
class pdoDB{
//PDO Connect
function connect($host,$db,$user,$pass){
$this->dbh = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass);
}
function query($query){
$this->retreat_name = $query;
$this->prepare();
}
function prepare(){
/* Execute a prepared statement by binding PHP variables */
$this->sth = $this->dbh->prepare('INSERT INTO tbl_retreats (retreat_name) VALUES (:value)');
$this->sth->bindParam(':value', $this->retreat_name);
$this->execute();
}
function execute(){
$this->sth->execute();
}
function result(){
if ($this->sth->rowCount() > 0) {
return 'Record Successfully Added';
}else{
return 'Record Not Inserted';
}
}
function close(){
$this->sth = null;
}
}
$db = new pdoDB();
$db->connect('localhost','PHPTest','root','pass');
$db->query('Barcelona'); //or $db->query($_POST['retreat_name']);
echo $db->result();
$db->close();
?>
You need to first declare the $con in the class. Just put it after the public $retreat_name = '';
put
public $retreat_name = '';
private $con;
after that, you can use it in other functions using the $this keyword.
mysql_close($this->con);
it turns out you need to do this
$this->openconn();
instead of just
openconn();