Preparing simple query for PDO connection - mysql

I would like to prepare PDO statement and convert results to JSON in PHP. I managed to connect to database by following method:
class DB_CONNECT {
function __construct() {
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
$root = getenv("DOCUMENT_ROOT");
require_once ($root.'/db/db_config.php');
try
{
$db = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_DATABASE.';charset=utf8;port='.DB_PORT, DB_USER, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'OK';
return $db;
}
catch (PDOException $e)
{
print "Connection error!: " . $e->getMessage() . "<br/>";
die();
}
}
function close() {
$db = null;
}
PHP, where I make statements looks like this:
$root = getenv("DOCUMENT_ROOT");
require_once ($root.'/db/db_connect.php');
$db = new DB_CONNECT();
$statement=$db->prepare("SELECT name, surname FROM lecturer");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
When I run this PHP, I'm getting only OK message, that the connection went successfully. What's wrong with that query code?

What does your error log say? From your code, I can tell you that $db doesn't contain a PDO object, as you don't return anything in the constructor of DB_CONNECT. So $db is an object of type DB_CONNECT, not of type PDO, and thus doesn't have prepare as a method.
For a quick fix, change
$db = new DB_CONNECT();
to
$db = DB_CONNECT::connect();
and make connect static.

Related

getting error back from Prepared statement in case sql injection

I'm trying to test my prepared statement that is protecting one field to get the error message in case of SQL injection. I tried until now thousands of attacks, and all of the values I gave were accepted. Am I using a wrong syntax or attack? I can't see where the problem is. Here is my code:
try {
// $host = "localhost";
// $username = "root";
// $password = "root";
// $db_name = "pokemon";
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name.';', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$meldung="";
$name =$_REQUEST['name'];
$gewicht = $_REQUEST['Gewicht'];
$größe =$_REQUEST['Größe'];
$spezies = $_REQUEST['Spezies'];
$stufe =$_REQUEST['Stufe'];
$atacke =$_REQUEST['Attacke'];
$array = explode(',', $_REQUEST['Attacke']);
$stmt = $conn->prepare("INSERT INTO Pokemon (`Name`,`Gewicht`,`grosse`,`spezies`,`stufe`) VALUES (:Name, '".$gewicht."', '".$größe."', '".$spezies."', '".$stufe."')");
$stmt->bindParam(':Name', $name);
// $stmt->bindParam(':Gewicht', $gewicht);
// $stmt->bindParam(':grosse', $größe);
// $stmt->bindParam(':spezies', $spezies);
// $stmt->bindParam(':stufe', $stufe);
$stmt->execute();
}
catch(PDOException $e)
{
$meldung = "Error: " . $e->getMessage();
echo $meldung;
}
thanks

PDO in Classes: Call to a member function prepare() on a non-object

I try to work with classes and PDO but I don't know how to fix the Problem.
With the help of var_dump($pdo) in RunQuery (after $pdo = self::$pdo_conn;) i get the value "null". Can anybody please help me how i can get the pdo object there? Or am I completely wrong with it?
index.php
require_once ('assets/socialbar/defines.php');
require_once ('assets/socialbar/mysql/classes/class.socialbar.php');
$ajaxid = 1;
$getinfo = "";
$getinfo = Socialbar::getInfo($ajaxid);
print_r($getinfo);
class.socialbar.php
require_once(MYSQL_DIR . 'config/pdo_connection.php');
class Socialbar extends Connection {
function __construct(){
parent::__construct();
}
public function GetInfo ($ajaxid) {
$sql = "SELECT * FROM uploads WHERE id = :ajaxid ";
$inputs = array('ajaxid' => $ajaxid);
//$stmt = $this->RunQuery($sql, $inputs);
$stmt = parent::RunQuery($sql, $inputs);
$rowCount = $stmt->rowCount();
if($rowCount > 0){
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
return $rowCount;
}
}
}
pdo_connection.php
abstract class Connection {
protected static $pdo_conn;
private $dsn, $user, $pass;
function __construct (){
require_once MYSQL_DIR . 'pdo_config.php';
$host = $config['db']['host'];
$dbname = $config['db']['dbname'];
$port = $config['db']['port'];
$this->user = $config['db']['user'];
$this->pass = $config['db']['pass'];
$this->dsn = "mysql:host=" . $host . ";port=" . $port . ";dbname=" . $dbname;
$this->Start();
}
protected function Start(){
try {
$this->pdo_conn = new PDO($this->dsn, $this->user, $this->pass);
} catch (PDOException $e){
print_r($e);
exit(0);
}
}
function RunQuery ($sql, $inputs=null){
// $pdo = $this->pdo_conn;
$pdo = self::$pdo_conn;
if(is_null($inputs)) {
$pdo->query($sql);
} else {
try {
$stmt = $pdo->prepare($sql);
if ($stmt) {
$stmt->execute($inputs);
} else {
print_r("Unable to prepare query");
}
} catch (PDOException $e) {
print_r($e);
exit(0);
}
}
return $stmt;
}
}
pdo_config.php
$config['db'] = array(
'host' => 'localhost',
'user' => 'root',
'pass' => '',
'dbname' => 'images',
'port' => '3306',
);
IMHO problem is your understanding or misunderstanding of static variables and functions.
So if you declare:
abstract class Connection {
protected static $pdo_conn;
That means that you can access $pdo_conn even if you had not instatntiate the object of your class and did not pass the __construct so if you have not passed __construct what value holds that property? Correct - NULL ;-)
so when you try to:
function RunQuery ($sql, $inputs=null){
// $pdo = $this->pdo_conn;
$pdo = self::$pdo_conn;
What will you get? Correct $pdo = NULL. And commented line looks as correct one.
There is no reason to declare and call pdo_conn as static property.
It could be private, protected even public but not static.
Try to instantiate the object first:
$socialBarObj = new Socialbar();
$getinfo = $socialBarObj->getInfo($ajaxid);
print_r($getinfo);

Cannot connect to MySQL

I am trying to connect to MySQL server (hosted by godaddy) from php using PDO.
But I get this error :
An error occured : SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Note that this is not a database I host.
I was simply given the username and password to construct the database, create the users etc.
function ConnectToDb()
{
try{
$dns = 'mysql:host=1.1.1.1;dbname=dummyDbName';
$username = 'dummyUser';
$password = 'dummyPassword';
$LINK = new PDO($dns, $username, $password);
$LINK->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$LINK->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!$LINK){
die('Could not connect : ' .mysql_error());
}
else{
return $LINK;
}
} catch (PDOException $ex){
echo "An error occured : " .$ex->getMessage();
}
}
I know that this works on localhost.
I'm using it no problem, but as soon as I try to connect to the live database it fails.
Anyone has an hint?
Thanks
Follow this format:
$user = "username";
$pass = "password";
$host = "localhost";
$db = "yourDbname";
$dns = "mysql:host=" . $host . ";dbname=" . $db;
$dbh = new PDO($dns, $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
when you have to do a query (just an example):
$theid = 10;
$statement = $dbh->prepare('SELECT * FROM yourtable WHERE id = ? and name = ?');
$statement->execute(array($theid,'baronth'));
if you want to see if there's some errors while connecting or doing queryes (and you know how try-catch works), surround it with:
try {
all the code that you wan't to check
}
catch (PDOException $e) {
echo $e->getMessage();
}
it will echo the error.

PDO Mutiple Query execute and catch error

i need to execute three queries and find out which query is failed in PDO.
My config php
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_AUTOCOMMIT, FALSE));
My class file
class myClass
{
function lastbench()
{
try {
$q1 = "select * from user";
$code_pre = $dbh->prepare($q1);
$code_pre->execute();
if(!$code_pre)
{
throw new Exception("no table called user");
}
$q2 = "select * from userprofile";
$code_pre2 = $dbh->prepare($q2);
$code_pre2->execute();
if(!$code_pre2)
{
throw new Exception("no Profile table");
}
}
catch ( Exception $e)
{
$e->getMessage();
}
}
}
Any idea how to get the specific block is not executing..

Detecting error/invalid/illegal queries using PDO driver (MySQL + PHP)

I just changed all my code from the old mysql driver to PDO.
So far I find that a lot of basic functionalities doesn't exist! Ex. no equivalency to mysql_num_row .. and so on (but that's not the point of this post :/ )
Usually with mysql driver, I'd do:
$result = mysql_query($query);
if(!$result){
displayError(mysql_error());
}
How do you do similar thing using PDO?
Have a look at the documentation here there are 3 modes :
PDO::ERRMODE_SILENT (default)
PDO::ERRMODE_WARNING
PDO::ERRMODE_EXCEPTION
I suggest you enable the last, which causes an exception to be thrown on error :
$pdo = new PDO($dsn,$user,$pass,$options); // Example connection
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
then surround your statement in a try/catch block
try {
// your query here
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
Separate note - mysql_num_row in PDO :
$sql = "SELECT count(*) FROM `table` WHERE x = y";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn()
Use try { } catch {}
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Reference