Jump to content

Trouble With Pdo


cybernet

Recommended Posts

i'm building a project for the first time with PDO

 

this is how i configured it

 

index.php

 

<?php
require_once (dirname(__FILE__) . '/inc/main.php');

userlogin();

$HTMLOUT = '';

$stmt = $db->query("SELECT row_id, name, mobile FROM location LIMIT 3");
// $stmt->execute(array($id, $name));
$stmt->setFetchMode(PDO::FETCH_OBJ);


$db = null;
$stmt = null;

?>

 

inc/main.php

 

<?php

require_once (dirname(__FILE__) . '/pdo_conn.php');
require_once (dirname(__FILE__) . '/mail/class.Mail.php');

error_reporting(E_ALL);


function userlogin() {
global $db;
unset($GLOBALS["CURUSER"]);

$ip = getip();
$nip = ip2long($ip);

$id = 0 + get_cookie('uid');


$fetch_user_details = $db->prepare("SELECT * FROM users WHERE user_id = :bitches_id LIMIT 1");
$fetch_user_details->bindParam(':bitches_id', $id, PDO::PARAM_INT);
$fetch_user_details->execute();
$fetch_user_details->setFetchMode(PDO::FETCH_OBJ);
$row = $fetch_user_details->fetch();


$user_id = $row->user_id;
$user_ip = $row->user_last_ip;
$update_user_details = $db->prepare("UPDATE users SET user_last_access = UNIX_TIMESTAMP(), user_last_ip = :last_ip WHERE user_id = :u_id LIMIT 1");
$update_user_details->bindParam(':last_ip', $user_ip, PDO::PARAM_STR, 15);
$update_user_details->bindParam(':u_id', $user_id, PDO::PARAM_INT);
$update_user_details->execute();

$GLOBALS["CURUSER"] = $row;

}

function is_logged_in() {
global $CURUSER;
if (!$CURUSER) {
header("Location: domain.net/login.php?403");
exit();
}
}

?>

 

inc/pdo_conn.php

 

<?php

$db = new PDO('mysql:host=localhost;dbname=abc;charset=UTF-8', 'abc', 'xam');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

?>

 

until a few days ago it worked, but when i starting to expand my project

i started to get this error

 

PHP Fatal error: Call to a member function prepare() on a non-object in /root/inc/main.php"

 

the error reffers to this line

$fetch_user_details = $db->prepare("SELECT * FROM users WHERE user_id = :bitches_id LIMIT 1");

Edited by cybernet
Link to comment
Share on other sites

Either the main page has lost the file that declares $db as a new PDO (have no idea why this is in a file all it's own), $db is being destroyed or changed to a different type of variable in the code between being declared as an object and being called for the prepare, some other problem is preventing $db from being declared in the first place.

 

What debugging have you done already?

 

To be fair though, none of these are the biggest problem with your code.

Link to comment
Share on other sites

 

What debugging have you done already?

 

To be fair though, none of these are the biggest problem with your code.

 

1. none :-\

2. like i said this is the first time i'm using pdo ... so i did how i thought at the moment

Don't try and force functions to use variables declared in the globals namespace, it defeats the a big part of there purpose.

 

how should i proceed ? can you please help me :confused:

 

thanks in advance :happy-04:

Link to comment
Share on other sites

first thing I would do would be to take these lines from pdo_con.php

$db = new PDO('mysql:host=localhost;dbname=abc;charset=UTF-8', 'abc', 'xam');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

and put them in the main.php just above where you are getting the error.

Link to comment
Share on other sites

if i would do that, then i have to call userlogin() on each page.

 

on a search on google i found that i should create a class to connect to database, but i really don't know how to make it secure and flawless

 

http://stackoverflow...object-php-help

 

i found some tuts online, but there are many stuff that i don't need ( at least for know )

 

this would be an example

 

http://www.tiny-thre...o-class-update/

 

i know that i sound very ... n00b and dumb also, but i really need an advice here :shrug:

 

@muddy i've checked youre blog and i saw that you have something there with classes

 

http://muddy-dev.blogspot.ro/2012/10/php-classes-simple-sample-class.html

 

but i didn't find a class that extends pdo ( mysql )

 

can you give me a tip, tutorial, something ?

Edited by cybernet
Link to comment
Share on other sites

PDO is it's self an abstraction layer class - this meens that it sits on top of the actual interface objects and provides a relativly standard way of interacting with any database that PDO has drivers to support. In my opinion, unless you commonly link to different types of storage engine it's more complicated than it ever needs to be. If your up for learning about classes, and the only engine your planning on using just now is mysql, I'd say the best thing to do would be to create your own mini abstraction layer using mysqli rather than using PDO. Alternativly, if you want to keep with PDO then you could write a class that extends PDO, and sets the PDO Attributes on construct. If you want help with either of these approaches let me know and I'll fling some more info your way.

Link to comment
Share on other sites

well, as you can see in my signature i'm a MySQL freak :tease-03:

so i would like to create a class that extends pdo and connects to mysqli

 

i want to use pdo because it's safe for queries

 

for now all i want is a class that connects to MySQL with mysqli ( it's supposed to be iMproved ), one that has a query count, and possible a way to cache queries

 

for start if you could help only with the class, and the rest i will try to figure out myself :D

 

thanks in advance :happy-03:

Edited by cybernet
Link to comment
Share on other sites

for now all i want is a class that connects to MySQL with mysqli ( it's supposed to be iMproved ), one that has a query count, and possible a way to cache queries

 

There is no connecting with Mysqli, mysqli is just a different access layer within PHP.  When it comes to talking with mysql pdo, mysqli, and mysql all use the same fundamental mysql library. The difference is the API that is exposed to PHP and what they allow you to do.  On that level, PDO and Mysqli are more or less equivalent.

 

You can extend PDO if you want, just like you can extend any other class.  I do in order to provide a bit nicer debugging features and set some initial settings.  You would still be connecting the same way though.

 

Link to comment
Share on other sites

No matter what database class you use, you need to troubleshoot why $db isn't an instance of it at the point where the error is occurring at.

 

About the only way your code could be producing that error, since the pdo db connection would be producing an exception if it is failing, assuming your connection code is actually being executed, is if you are overwriting $db somewhere in the code you didn't post.

 

What's the code for your functions getip() and get_cookie()? And any other code from the start of index.php up to the point of that error that you might have left out?

Edited by PFMaBiSmAd
Link to comment
Share on other sites

function get_cookie($name)
   {
  global $ResT_BV;

 if ( isset($_COOKIE[$ResT_BV['cookie_prefix'].$name]) AND !empty($_COOKIE[$ResT_BV['cookie_prefix'].$name]) )
 {
  return urldecode($_COOKIE[$ResT_BV['cookie_prefix'].$name]);
 }
 else
 {
  return FALSE;
 }
}

 

function getip() {
  if (isset($_SERVER)) {
 if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && validip($_SERVER['HTTP_X_FORWARDED_FOR'])) {
   $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
 } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && validip($_SERVER['HTTP_CLIENT_IP'])) {
   $ip = $_SERVER['HTTP_CLIENT_IP'];
 } else {
   $ip = $_SERVER['REMOTE_ADDR'];
 }
  } else {
 if (getenv('HTTP_X_FORWARDED_FOR') && validip(getenv('HTTP_X_FORWARDED_FOR'))) {
   $ip = getenv('HTTP_X_FORWARDED_FOR');
 } elseif (getenv('HTTP_CLIENT_IP') && validip(getenv('HTTP_CLIENT_IP'))) {
   $ip = getenv('HTTP_CLIENT_IP');
 } else {
   $ip = getenv('REMOTE_ADDR');
 }
  }
  return $ip;
}

 

i didn't include this in the 1st post because they were irrelevant to the issue i'm having

 

so does anyone have a simple class { database } to use with pdo ?

 

please :unsure:

Link to comment
Share on other sites

PDO is a class..?

$database = new PDO (...);

 

If this isn't what you meant, please expand upon your questions with some more details.

 

PS: Don't use global inside your functions, that's breaking with the idea behind using functions in the first place. Send the data as a parameter instead, like you've done with the $name.

If that's a config array, then you might want to use constants instead. They're globally accessible, and (as the name implies) constant. So once they're defined nothing can change them.

Edited by Christian F.
Link to comment
Share on other sites

i said that pdo is a class, because at the time i wrote the post, i remembered a code line that began with class XyZ extends DB { ...

 

where DB was the pdo connect thing ...

 

@Christian F, thank you for the information

you really clarified that error for me ^_^

Edited by cybernet
Link to comment
Share on other sites

Glad I could help, though I must confess I'm a bit confused as to exactly how I did that. :P

In any case, you're welcome.

 

(Thought you were asking for a class that could use PDO, when PDO is a class itself.)

 

1. Send the data as a parameter instead, like you've done with the $name.

2. yes, i was asking for a class that could use PDO

 

like this one

 

class SQL {
private static $dbh = null;
private function __construct($host, $user, $pass, $data, $table) {
$this->host = (!empty($host)) ? $host: 'localhost';
$this->user = $user;
$this->pass = $pass;
$this->data = $data;
$this->table = $table;
static::connect();
}
private function __destruct() {
static::close();
}
public static function connect() {
$dsn = 'mysql:dbname=' . $this->table . ';host=' . $this->host;
static::$dbh = new PDO($dsn, $this->user, $this->pass);
static::$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function close() {
static::$dbh = null;
}
public static function query($query) {
$sth = static::$dbh->prepare($query);
$sth->execute();
}
}

 

so now i should use :

 

function userlogin($db) {
unset($GLOBALS["CURUSER"]);
} // etc

instead of :

function userlogin() {
global $db;
unset($GLOBALS["CURUSER"]);
} // etc

 

?

Edited by cybernet
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.