PDA

View Full Version : خطا در Call to a member function prepare() php pdo



Sepax1
شنبه 29 فروردین 1394, 22:32 عصر
سلام یه همه دوستان .
من یه قطعه کد دارم که به وسیله pdo به دیتابیس وصل میشه ولی الان یه ایرادی داره .



<?php

class DB_Functions {

// private $db;

//put your code here
// constructor
function __construct() {
// require_once 'db_conncet.php';
// // connecting to database
// $this->db = new DB_Connect();
// $this->db->connect();
require_once 'config.php';


$username = 'netshope_sepehr';
$password = 'sepax963258';
// connecting to mysql
try {
$db = new PDO('mysql:host=localhost;dbname=netshope_login',$ username , $password);
$db->setAttribute(PDO::ATR_ERRMODE , PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {
echo "Error" . $e->getMessage() ;

}






}

// destructor
function __destruct() {

}

/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt


// $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at)
// VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");


try {


$stmt = $db->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at)
VALUES(:uuid, :name, :email, :encrypted_password, :salt, NOW())");
$stmt->execute(array(
':uuid' => $uuid,
':name' => $name,
':email' => $email,
':encrypted_password' => $encrypted_password,
':salt' => $salt
));




if($stmt->rowCount() > 0){
$uid = mysql_insert_id();


$result = $db->prepare("SELECT * FROM users WHERE uid = :uid");
$result->execute(array(
':uid' => $uid
));


return $result->fetchAll();


} return false ;





} catch (PDOException $e) {
echo 'ERROR: ' . $e->getMessage();

}




}





} // destructor function __destruct() { } /** * Storing new user * returns user details */ public function storeUser($name, $email, $password) { $uuid = uniqid('', true); $hash = $this->hashSSHA($password); $encrypted_password = $hash["encrypted"]; // encrypted password $salt = $hash["salt"]; // salt
// $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) // VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
try {
$stmt = $db->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(:uuid, :name, :email, :encrypted_password, :salt, NOW())"); $stmt->execute(array( ':uuid' => $uuid, ':name' => $name, ':email' => $email, ':encrypted_password' => $encrypted_password, ':salt' => $salt ));

if($stmt->rowCount() > 0){ $uid = mysql_insert_id();
$result = $db->prepare("SELECT * FROM users WHERE uid = :uid"); $result->execute(array( ':uid' => $uid ));
return $result->fetchAll();
} return false ;

} catch (PDOException $e) { echo 'ERROR: ' . $e->getMessage(); }

}[/PHP]

وقتی از تو index.php میخوام یه از این کلاس استفاده کنم نمیشه و ارور زیر رو میده :
Fatal error</b>: Call to a member function prepare() on a non-object

index.php



<?php

/**
* File to handle all API requests
* Accepts GET and POST
*
* Each request will be identified by TAG
* Response will be JSON data
* check for POST request
*/
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];

// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// response Array
$response = array("tag" => $tag, "error" => FALSE);

// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];

// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
} else if ($tag == 'register') {
// Request type is Register new user
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];

// check if user is already existed
if ($db->isUserExisted($email)) {
// user is already existed - error response
$response["error"] = TRUE;
$response["error_msg"] = "User already existed";
echo json_encode($response);
} else {
// store user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Error occured in Registartion";
echo json_encode($response);
}
}
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknow 'tag' value. It should be either 'login' or 'register'";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter 'tag' is missing!";
echo json_encode($response);
}
?>

Sepax1
یک شنبه 30 فروردین 1394, 21:23 عصر
مسینمیتونه کمکی بکنه

-سیّد-
یک شنبه 30 فروردین 1394, 22:03 عصر
<?php

class DB_Functions {

// private $db;

//put your code here
// constructor
function __construct() {
// require_once 'db_conncet.php';
// // connecting to database
// $this->db = new DB_Connect();
// $this->db->connect();
require_once 'config.php';


$username = 'netshope_sepehr';
$password = 'sepax963258';
// connecting to mysql
try {
$db = new PDO('mysql:host=localhost;dbname=netshope_login',$ username , $password);
$db->setAttribute(PDO::ATR_ERRMODE , PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {
echo "Error" . $e->getMessage() ;

}






}

// destructor
function __destruct() {

}

/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt


// $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at)
// VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");


try {


$stmt = $db->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at)
VALUES(:uuid, :name, :email, :encrypted_password, :salt, NOW())");
$stmt->execute(array(
':uuid' => $uuid,
':name' => $name,
':email' => $email,
':encrypted_password' => $encrypted_password,
':salt' => $salt
));




if($stmt->rowCount() > 0){
$uid = mysql_insert_id();


$result = $db->prepare("SELECT * FROM users WHERE uid = :uid");
$result->execute(array(
':uid' => $uid
));


return $result->fetchAll();


} return false ;





} catch (PDOException $e) {
echo 'ERROR: ' . $e->getMessage();

}




}


}

وقتی از تو index.php میخوام یه از این کلاس استفاده کنم نمیشه و ارور زیر رو میده :
Fatal error</b>: Call to a member function prepare() on a non-object

index.php



<?php

/**
* File to handle all API requests
* Accepts GET and POST
*
* Each request will be identified by TAG
* Response will be JSON data
* check for POST request
*/
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];

// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// response Array
$response = array("tag" => $tag, "error" => FALSE);

// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];

// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
} else if ($tag == 'register') {
// Request type is Register new user
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];

// check if user is already existed
if ($db->isUserExisted($email)) {
// user is already existed - error response
$response["error"] = TRUE;
$response["error_msg"] = "User already existed";
echo json_encode($response);
} else {
// store user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Error occured in Registartion";
echo json_encode($response);
}
}
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknow 'tag' value. It should be either 'login' or 'register'";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter 'tag' is missing!";
echo json_encode($response);
}
?>



سلام
اول چند تا نکته بگم: توی این سایت، کد PHP رو اگه توی بخش PHP (دکمه‌ای که روش نوشته php) بذارید خیلی بهتر از اینه که توی Code (دکمه‌ای که علامت # داره) بذارید، چون syntax highlight می‌کنه و فهمش برای یکی مثل من راحت‌تر می‌شه.
دوم این که یه بخشی از کدتون به هم ریخته بود.
سوم هم این که اون پیغام خطایی که بهتون می‌ده، یه شماره خط هم معمولاً می‌ده که بتونید بفهمید (و بفهمیم!) خطا از کدوم بخش بوده.

حالا بریم سر اصل مطلب:
به پیغام خطایی که می‌ده دقت کنید:

Fatal error</b>: Call to a member function prepare() on a non-object
می‌گه شما تابع مخصوص کلاس (member function) با نام prepare رو روی یه متغیری صدا زدید که شیء نبوده. یعنی انتظار داره وقتی می‌گید:

$db->prepare(...)
متغیر db یه شیئی از یه کلاس باشه، که نیست.
خوب این تابع رو کجا صدا زدید؟ توی تابع storeUser کلاس، که دو بار تابع prepare رو روی متغیر db صدا زدید.
چه اتفاقی افتاده؟ اتفاقی که افتاده اینه که این متغیر اصلاً توی این تابع تعریف نشده. شما توی constructor متغیری به نام db تعریف کردید و مقداردهی کردید. ولی این متغیر توی یه تابع دیگه شناخته شده نیست. یعنی وقتی توی constructor می‌گید

$db = ...
این می‌شه یه متغیر محلی (local) توی اون تابع، نه یه متغیر توی کلاس. اگه می‌خواین این متغیر داخل کلاس تعریف بشه، اولاً باید این بخش:

// private $db;
رو از کامنت در بیارید تا این متغیر توی کلاس تعریف بشه. و بعد که می‌خواین مقداردهیش بکنید، به این صورت عمل کنید:

$this->db = new PDO('mysql:host=localhost;dbname=netshope_login',$ username , $password);
(همون طور که چند خط بالاترش هست و کامنت شده).
یعنی هر جا بگید db$ ، چیزی که PHP می‌فهمه اینه که شما منظورتون یه متغیر محلی داخل scope همون تابع هست. اگه می‌خواین به متغیرهای کلاس دسترسی پیدا کنید، باید از <-this$ استفاده کنید.

توجه کنید که توی استفاده‌ی بعدی (یعنی تابع storeUser) هم از <-this$ استفاده کنید!

Sepax1
دوشنبه 31 فروردین 1394, 01:15 صبح
خیلی ممنون دوست عزیز که این قدر با حوصله جواب دادین .
واقعا" ممنونم :لبخندساده: