PDO self prepare returns an empty string - php

I connected to the DB via this.
public static function connect() {
try {
self::$db_handle = new PDO("mysql:host=".SERVER.";dbname=".DBNAME,USER, PASSWORD);
self::$db_handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo "Successful connected to DB<br/>";
}
catch(PDOException $e) {
echo "Conncection failed: " . $e->getMessage();
exit();
}
}
It echoes Successful Connection. So am guessing, there is no issue with the connectivity.
Now I use the following code to query the DB.
$sql=func_get_arg(0);
$params=array_slice(func_get_args(), 1);
$statement=self::$db_handle->prepare($sql);
echo "<br/>Stat: ".$statement."</br>"; //Just for testing purposes
if($statement===false){
echo "False";
return false;
}
if(count($params)==0){
$results=$statement->execute();
}
else
$results=$statement->execute($params);
if($results===false)
return false;
else{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
I have no clue why it echoes False. The statement which I tried to echo is an empty string.
$sql =
"SELECT * FROM `users` where $key = ?"
and $params is the email address itself.
I am unable to detect my fault. Kindly help. Thanks :)

change it to this
public static function connect()
{
self::$db_handle = new PDO("mysql:host=".SERVER.";dbname=".DBNAME,USER, PASSWORD);
self::$db_handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
self::$db_handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

$PDO = <yourclass>::connect();
$statement = $PDO->prepare("SELECT * FROM users WHERE key=?");
$statement->execute(array(1));
echo $PDO->lastInsertId();

Related

How to simplify the following PHP PDO connection codes?

class ActionWires{
public static function _checkExistDate($array){
try{
$sql = "SELECT id FROM wires WHERE fdate = ?";
$state = pdoConnect::_connect() ->prepare($sql);
$state->execute($array);
return $state->fetch()?true:false;
}catch(PDOException $e){
echo "database connection fail".$e->getMessage();
exit();
}
}
public static function _showWires($array){
try{
$sql = "SELECT id,wname,fdate,fname,fpath,caption,category FROM wires WHERE fdate = ?";
$state = pdoConnect::_connect() ->prepare($sql);
$state->execute($array);
return $state->fetchAll();
}catch(PDOException $e){
echo "database connection fail".$e->getMessage();
exit();
}
}
There are lot of codes are the same. The main difference is sql query and return value. Are there any suggestion to minimize the same codes.
It'll be hard to minimise this completely because of the different return types.
From a quick glance, I think about the best you can do is have a shared function which accepts the SQL string and parameter array, and runs the prepare and execute commands, and returns the result object. For example:
class ActionWires
{
public static function _checkExistDate($array){
try{
$sql = "SELECT id FROM wires WHERE fdate = ?";
$state = self::runSQL($sql, $array);
return $state->fetch()?true:false;
}catch(PDOException $e){
echo "database connection fail".$e->getMessage();
exit();
}
}
public static function _showWires($array){
try{
$sql = "SELECT id,wname,fdate,fname,fpath,caption,category FROM wires WHERE fdate = ?";
$state = self::runSQL($sql, $array);
return $state->fetchAll();
}catch(PDOException $e){
echo "database connection fail".$e->getMessage();
exit();
}
}
private static function runSQL($sql, $paramList)
{
$state = pdoConnect::_connect() ->prepare($sql);
$state->execute($paramList);
return $state;
}
}
But it only saves you a couple of lines.

Function that check if value exists in sql server

Hei,
I need a function in php that checks if a value entered by form is already in database (sql - server -- PDO), and return TRUE or FALSE.
I tried to do this, but I got stuck and didn't found a solution on internet.
could you give me a hint on how to threat the above condition ?
function check_code($code) {
GLOBAL $handler;
$code = check_input($code);
try{
$query2 = $handler -> prepare("SELECT code from stock where code = :code");
$query2 -> execute(array(
':code' => $code
));
return >???<
}
catch(PDOException $e){
echo $e -> getMessage();
} }
return something like row_count(result) > 0
I've never work with sql-server before but I had worked with PDO many times, basically this is how would check in pdo
<?php
function check_code($code)
{
GLOBAL $handler;
$code = check_input($code);
try {
$query2 = $handler->prepare("SELECT code from stock where code = :code");
$query2->execute(array(':code' => $code));
$results = $query2->fetchColumn();
if (count($results) > 0) {
echo "exists";
} else {
echo "does not exist";
}
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
?>
NB: Avoid using the Global var... Stop using `global` in PHP

How to get out of a function in php

I have the following function:
function authenticate($req, $resp, $args) {
$credentials = json_decode($req->getBody());
$sql = "SELECT usr_password FROM ict_users WHERE usr_username='".$credentials->username."'";
try {
$db = DB_Connection();
$stmt = $db->query($sql);
$password = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
if (password_verify($credentials->password, $password[0]->usr_password)) {
echo 'Valid password !';
} else {
echo 'Invalide password !.';
}
}
If I put return; after $db = null; will it stop executing my function? Or is there a better way to stop the function when an error is caught?
You have an try {}catch(){} block, why not throw new Exeption(); instead of return null. And return null is not done if you want "stop the function when an error is caught", you just returning null from the function.

Mysql adds new row instead of updating it

I have integrated google loing to my website. It's working fantastic. When someone logs in via google for the firs time, then a new entry is stored in the database.
But, when he logs in again..only the last login (a column on the table) should be updated...but instead, mysql adds a new row.
What am I doing wrong here?
public function trigger_registration_from_google($fname,$lname,$email)
{
global $conn;
try
{
if(useremailexists($email))
{
$date = date('Y-m-d');
//run update query
//user already exists, only update
try
{
$s = $conn->prepare("UPDATE users set last_login = :last_login where emailid = :email ");
$s->bindParam(':last_login',$date);
$s->bindParam(':email',$email);
$s->execute();
$s->closeCursor();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{
//insert
//insert now..since he is a new user
$date = date('Y-m-d');
$v=1;
$r="google";
try
{
$s = $conn->prepare("INSERT INTO users(fname,lname,emailid,registeredby,registeredon,last_login,verified) values (:fname,:lname,:emailid,:registeredby,:registeredon,:last_login,:verified)");
$s->bindParam(':fname',$fname);
$s->bindParam(':lname',$lname);
$s->bindParam(':emailid',$email);
$s->bindParam(':registeredby',$r);
$s->bindParam(':registeredon',$date);
$s->bindParam(':last_login',$date);
$s->bindParam(':verified',$v);
$s->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Edit
useremailexists
function useremailexists($email)
{
//check if the email exists
global $conn;
try
{
$s = $conn->prepare("SELECT * from users where emailid = :email");
$s->bindParam(':email',$email);
$s->execute();
if($s->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Validate if the function useremailexist return true or false , we can't help you without this piece of code.

PHP using PDO to store session in DB doesnt produce the errors i expected

SOLVED :
answer is in the 2nd post
i try to store session in DB using PDO, but it doesn't produce errors i expected, please read my code.
here's the code for my session handler class:
class MySessionHandler implements SessionHandlerInterface
{
protected $conn = NULL;
public function open($savePath, $sessionName)
{
if(is_null($this->conn))
{
$dsn = 'mysql:host=localhost;dbname=php_advanced';
$username = 'root';
$password = 'password';
try
{
$this->conn = new PDO($dsn, $username, $password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in open function ' . $e->getMessage());
}
}
return TRUE;
}
public function close()
{
echo '<p>close</p>';
$this->conn = NULL;
return TRUE;
}
public function read($id)
{
echo '<p>read</p>';
$query = 'SELECT data FROM session_table WHERE session_id = :id';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':id', $id);
$pdo->execute();
// Kalo query berhasil nemuin id..
if($pdo->rowCount() == 1)
{
list($sessionData) = $pdo->fetch();
return $sessionData;
}
return FALSE;
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in read function => ' . $e->getMessage());
}
}
public function write($id, $data)
{
echo '<p>write</p>';
$query = 'REPLACE INTO session_table(session_id, data) VALUES(:id, :data)';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':id', $id);
$pdo->bindValue(':data', $data);
$pdo->execute();
// return the value whether its success or not
return (bool)$pdo->rowCount();
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in write function => ' . $e->getMessage());
}
}
public function destroy($id)
{
echo '<p>destroy</p>';
$query = 'DELETE FROM session_table WHERE session_id = :id LIMIT 1';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':id', $id);
$pdo->execute();
$_SESSION = array();
return (bool)$pdo->rowCount();
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in destroy function => ' . $e->getMessage());
}
}
public function gc($maxLifeTime)
{
echo '<p>garbage collection</p>';
$query = 'DELETE FROM session_table WHERE DATE_ADD(last_accessed INTERVAL :time SECOND) < NOW()';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':time', $maxLifeTime);
$pdo->execute();
return TRUE;
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in gc function => ' . $e->getMessage());
}
}
}
$SessionHandler = new MySessionHandler();
session_set_save_handler($SessionHandler);
session_name('my_session');
session_start();
i remove the session_write_close on purpose. This probably sounds stupid, but i want to get the session error to learn more..
here's session script(using the book's code):
require('session_class.php');
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DB Session Test</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
// Store some dummy data in the session, if no data is present:
if (empty($_SESSION)) {
$_SESSION['blah'] = 'umlaut';
$_SESSION['this'] = 3615684.45;
$_SESSION['that'] = 'blue';
// Print a message indicating what's going on:
echo '<p>Session data stored.</p>';
} else { // Print the already-stored data:
echo '<p>Session Data Exists:<pre>' . print_r($_SESSION, 1) . '</pre></p>';
}
// Log the user out, if applicable:
if (isset($_GET['logout'])) {
session_destroy();
echo '<p>Session destroyed.</p>';
} else { // Otherwise, print the "Log Out" link:
echo 'Log Out';
}
// Reprint the session data:
echo '<p>Session Data:<pre>' . print_r($_SESSION, 1) . '</pre></p>';
// Complete the page:
echo '</body>
</html>';
// Write and close the session:
// session_write_close() <<<<<--- I REMOVE THIS ON PURPOSE TO GET ERROR
?>
but i dont get any error, then i try to use book's mysqli script to connect db and it produces error i expected because i removed the session_write_close()..
can anyone explain why if im using PDO it doesn't generate error? i'm even dont use
register_shutdown_function('session_write_close');
in my session class destructor (on purpose)
NOTE : I'm doing this on purpose because i want to learn more.
the error im expecting is like when im using mysqli connection(connection closed by php at the end of script then session try to write and close but no connection available) :
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 66
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 66
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 67
Warning: mysqli_close() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 33
update 1
i recently figured it out that mysqli needs database connection everytime it uses mysqli_real_escape_string() and mysqli_query and because of but what im thinking is my pdo also needs db connection when the script ends -> db connection closed -> MySessionHandler will try to write and close, but there's no db connection since pdo has been closed by php, but no error produced..
update 2
i just tried to pass session_set_save_handler function callback and it produces the errors
<?php
$conn = NULL;
function open_session()
{
echo '<p>open session</p>';
global $conn;
$_dsn = 'mysql:host=localhost;dbname=php_advanced';
$_username = 'root';
$_password = 'password';
$conn = new PDO($_dsn, $_username, $_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return TRUE;
}
function close_session()
{
echo '<p>close session</p>';
global $conn;
$conn = NULL;
return TRUE;
}
function read_session($sid)
{
echo '<p>read session</p>';
global $conn;
$query = 'SELECT data FROM session_table WHERE session_id = :sid';
$pdo = $conn->prepare($query);
$pdo->bindValue(':sid', $sid, PDO::PARAM_STR);
$pdo->execute();
if($pdo->rowCount() == 1)
{
list($session_data) = $pdo->fetch();
echo '<pre>';
print_r($session_data);
echo '</pre>';
return $session_data;
}
else
{
return '';
}
}
function write_session($sid, $data)
{
echo '<p>write session</p>';
global $conn;
$query = 'REPLACE INTO session_table(session_id, data) VALUES(:sid, :data)';
$pdo = $conn->prepare($query);
$pdo->bindValue(':sid', $sid, PDO::PARAM_STR);
$pdo->bindValue(':data', $data, PDO::PARAM_STR);
$pdo->execute();
return $pdo->rowCount();
}
function destroy_session($sid)
{
echo '<p>destroy session </p>';
global $conn;
$query = 'DELETE FROM session_table WHERE session_id = :sid';
$pdo = $conn->prepare($query);
$pdo->bindValue(':sid', $sid, PDO::PARAM_STR);
$pdo->execute();
// clean the session array;
$_SESSION = array();
return (bool)$pdo->rowCount();
}
function clean_session($expire)
{
echo '<p>clean session</p>';
global $conn;
$query = 'DELETE FROM session_table WHERE DATE_ADD(last_accessed, INTERVAL :expire SECOND) < NOW()';
$pdo = $conn->prepare($query);
$pdo->bindValue(':expire', $expire, PDO::PARAM_INT);
$pdo->execute();
return $pdo->rowCount();
}
session_set_save_handler('open_session', 'close_session', 'read_session', 'write_session', 'destroy_session', 'clean_session');
session_name('my_session');
session_start();
but still when im passing MySessionHandler class , it doesn't produce error because of no connection.
SOLUTION
sorry guys my mistake actually its a pretty easy answer why MySessionHandler class doesnt produce error wihtout session_write_close() in the end of script,
session_set_save_handler() by default will register session_write_close() to register_shutdown_function()
so if u want to make your own shutdown function for session then use :
session_set_save_handler($SessionClass, FALSE) , if u do this then u must provide session_write_close() in your class destructor
source : http://php.net/manual/en/function.session-set-save-handler.php
thanks for the tips and your attention

Categories