I am storing an USER object inside a session by serialize first, than I am trying to use it on the same page to test it however it doesn't retrieve the data that was initialize everything is blank.
$user = new User();
echo '<br/>' . $user->getUsername(); // Gives me corerct data
userSession(serialize($user)); // Stored into session
$userObj = unserialize($_SESSION['userObj']); // Still get an object of type User
echo $userObj->getUsername(); // This returns blank unlike the first call
If anyone can assist me it will be greatly appreciated, thanks!
userSession Code
function userSession($userObj){
session_start();
$_SESSION['userObj'] = $userObj;
}
USER CLASS
class User{
protected $pdo;
private $id, $username, $banned, $email, $first_name, $last_name, $mobile_phone, $city, $address, $postal_code, $user_type, $active;
// Create a user
public function __construct(){
$con = new Connection();
try{
$this->pdo = $con->getConnection();
}catch (PDOException $e){
echo $e->getMessage(); // Store to file
}
}
Instead of serializing the full User class, try serializing just the data and using the same data to create a new object after.
Basically, what you'd do is add a User->getData() and User->setData() where one would return all the data that is relevant in a format you can save (JSON, serializable Array) and the other would allow you to create a new User object and load this data back in.
Related
I am not very experienced in php oop. Moreover, when mysqli comes with php oop, it make me more confused about using it in best efficient way. Anyway, first look at my connection class:
<?php
//connectionclass.php
class connection{
public $conn;
public $warn;
public $err;
function __construct(){
$this->connect();
}
private function connect(){
$this->conn = # new mysqli('localhost', 'sever_user', 'user_password');
if ($this->conn->connect_error) {
$this->conn = FALSE;
$this->warn = '<br />Failed to connect database! Please try again later';
}
}
public function get_data($qry){
$result = $this->conn->query($qry);
if($result->num_rows>=1){
return $result;
}else{
$this->err = $this->conn->error;
return FALSE;
}
$result->free();
}
public function post_data($qry){
$this->conn->query($qry);
if($this->conn->affected_rows>=1){
return TRUE;
}else{
$this->err = $this->conn->error;
return FALSE;
}
}
}
?>
Now please structure of a php page which uses mysql database to store and get data:
<?php
//login.php
include('/include/connectionclass.php');
$db = new connection();
$query = "SELECT * FROM USERS WHERE user_country='India'";
$data = $db->get_data($query);
if($data){
while($row=$data->fetch_assoc()){
echo 'User Name: ':.$row["user_name"].' Age: '.$row["age"];
}
}
?>
So my login.php uses connection class to get data about users. All the things are running well. But one things made me confused. In connectionclass.php $this->conn is itself an object as it calls new mysqli. So this is an object inside another object $db. Moreover, When I am using $data = $db->get_data($query);, a result set is created inside object $db by method get_data, then this result set is copied into a variable $data inside login.php page.
So according to me, actually two result sets/data sets are creating here, one inside db object and one inside login page. Is it right way to use mysqli and php to get dataset from mysql database? Will it use more memory and server resources when the dataset is larger (when have to get large amount of data for many users)?
If it is not right way, please explain your points and please give me code which can be used efficiently for php oop and mysqli.
suppose I have the class named as User and user is an object of that class,
now I call a function named as storevalues from user(an object of class User).
In the storevalues function,__construct function is called which assign the value to the class member.$this->name,$this->email,$this->password.
finally I try to store these values in DATABASE through PDO.
$conn = new PDO(DB_DSN,DB_USERNAME,DB_PASSWORD);
$sql="insert into user_info(name,email,password)values(:name,:email,:password)";
$st=$conn->prepare($sql);
$st->bindValue(":name",$this->name,PDO::PARAM_STR);
$st->bindValue(":email",$ths->email,PDO::PARAM_STR);
$st->bindValue(":password",$this->password,PDO::PARAM_STR);
$st->execute();
But the above code is not working.The connection is successfull made to the database but query is not executed.I want to know what mistake I have done in this code.
When I try assigning the class members value to the new variable then it works.The code below shows that method
$name=$this->name;
$email=$this->email;
$password=$this->password;
$conn = new PDO(DB_DSN,DB_USERNAME,DB_PASSWORD);
$sql="insert into user_info(name,email,password)values(:name,:email,:password)";
$st=$conn->prepare($sql);
$st->bindParam(":name",$name,PDO::PARAM_STR);
$st->bindParam(":email",$email,PDO::PARAM_STR);
$st->bindParam(":password",$password,PDO::PARAM_STR);
$st->execute();
I am a beginner in php and pdo and I know that my code is inefficient.Help me in finding the mistake in first method and identifying my mistakes.
User class
class User
{
public $name=null;
public $email=null;
public $password=null;
public function __construct($data=array())
{
if(isset($data['name']))
$this->name=$data['name'];
if(isset($data['email']))
$this->email=$data['email'];
if(isset($data['password']))
$this->password=$data['password'];
}
public function storevalues($result=array())
{
$this->__construct($result);
$conn = new PDO(DB_DSN,DB_USERNAME,DB_PASSWORD);
$sql="insert into user_info(name,email,password)values(:name,:email,:password)";
$st=$conn->prepare($sql);
$st->bindParam(":name",$this->name,PDO::PARAM_STR);
$st->bindParam(":email",$this->email,PDO::PARAM_STR);
$st->bindParam(":password",$this->password,PDO::PARAM_STR);
$st->execute();
}
}
You may catch the SQL error after the execute:
if ( ! $st->execute) {
Throw new exception('Mysql Error - ' . implode(',', $st->errorInfo()));
}
I'm building a class to login users, so everything works great on localhost, but when i upload the files to the server, the code doesn't work as espected...
I checked this question Value return when no rows in PDO but i couldn't make it work...
My goal is to be able to retrieve the data from the Database and then check either the password is correct or not. I need 3 feedbacks:
User Doesn't exist
Pass/User combination doesn't match.
All good, proceed and login the user.
First I call the class:
$a = $login->login_user_admin($_POST['user']);
Then I get the result: Updated full class & connection
class Database extends PDO
{
private $dbname = "xxx";
private $host = "localhost";
private $user = "xxx";
private $pass = "xxx";
private $port = 5432;
private $dbh;
public function __construct()
{
try {
$this->dbh = parent::__construct("pgsql:host=$this->host;port=$this->port;dbname=$this->dbname;user=$this->user;password=$this->pass");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function close_con()
{
$this->dbh = null;
}
}
class Users
{
private $con;
public function __construct()
{
$this->con = new Database();
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$this->con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function login_user_admin($user)
{
try{
$stmt = $this->con->prepare("SELECT name,salt,pass FROM users.users_admin WHERE name=? LIMIT 1");
$stmt->execute(array($user));
$this->con->close_con();
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
Finally I process:
$data = [];
if ($a!=true) {
$data['success'] = false;
$data['message'] = 'User doesn't exist';
}else{
//All good proceed to chk the password.
}
I tried with empty and isset... didn't work on server either, they all work on local tough. I also try using fetchAll() and checking the empty string but i couldn't make it.
I went to check on the PHP versions on the server and local and they both running on 5.5 so I run out of ideas for now and I will appreciate some help on this.
Update!
I upload a file with only this code to check if I am getting any result from the database and I realize I am not,
include '../functions/functions.php';
$login = new Users();
$a = $login->login_user_admin("emirocast");
print_r($a);
var_dump($a);
The only user in the database right now is "emirocast" so i should get the result but i get a bool(false) instead.
The other thing I noticed is that the server is running Postgresql 8.4 and I am running 9.1 locally. Can this be the problem here?
I'm trying to accomplish the same ends as outlined in this question but my application of that answer just does not work. I get blank white screens when attempting to perform any operation involving the database class.
This should be simple-- a user inputs a username and password into a form. If both are received by the controller, I query the database and compare a hash of the submitted password with the hash on file. The problem is, my page does not load once I start making database calls.
I have a controller and two classes. One class is a database connector, the other is an authentication module that depends on the database connector.
Database connector class:
class inquiry
{
protected $pdo;
// Set up the initial db connection
function __construct()
{
try
{
$this -> pdo = new PDO('mysql:host=127.0.0.1;dbname=mysqlserver','mydatabase','ffffffffffffffff');
$this -> pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this -> pdo -> setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
$this -> pdo -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this -> pdo -> exec('set names "utf8"');
}
catch (PDOException $e)
{
echo $e -> getMessage();
}
}
}
Then, the authentication class:
class auth
{
private $username;
private $password;
private $db;
function __construct(inquiry $db)
{
$this -> db = $db;
}
function login($username, $password)
{
$this -> username = $username;
$this -> password = $password;
// Query database, get hashed password for username
$this -> db -> query('select password from users where username="bob";');
// Data needs to be fetched but PHP does not process anything past this point anyway
return true;
}
}
Then, in the controller:
require_once '../inc/class.inquiry.php';
require_once '../inc/class.auth.php';
if (isset($_POST['username']) && isset($_POST['password']))
{
// Probably doing something wrong here
$dbconnect = new inquiry();
$user = new auth($dbconnect);
$authorized = $user -> login($_POST['username'], $_POST['password']);
if ($authorized == true)
{
// Send user to index page
header('Location: index.php');
exit();
}
}
I've commented the sections where I think I'm going wrong, but I don't know what to actually do about it. Any tips would be appreciated!
All of your code is wrong on many levels. Starting from code standards where class should start with uppercase letter, formatting the code, finishing to calling a non-existent method.
First of all, your inquiry class does not have the desired query() method. It seems you try to give us a code you have not written by yourself, to debug.
Second, your class is completely USELESS. Even though it does not have a custom wrapping query method, you still could use PDO's method for querying and execute a query. However, even you are assigning value of object of type PDO to your protected $pdo you have absolutely NO ACCESS to this $pdo outside the class i.e. from auth class. You should write an accessor for $pdo, so you can use something like
$this->db->getPdo()->prepare("SELECT ......");
I have an issue that I can't figure out. I have a class Database which if I use it directly I connect to db regularly. I have another class Categories and I want to call a Database object. The problem is that if I call $db->connect in categories does not work. I tried call mysql_connect directly in Categories and it works fine!
Why can't I use $db->connect (the error is Access denied for user 'user'#'0.0.0.0' (using password: YES).
My code in class Database is:
public function connect($new_link=false){
$this->link_id = #mysql_connect($this->server,$this->user,$this->pass,$new_link);
echo "<br/>link_id = ".$this->link_id;
if (!$this->link_id){//open failed
$this->oops("Could not connect to server: <b>$this->server</b>.");
}
else{
echo "Connected to server <br/>";
}
if(!#mysql_select_db($this->database, $this->link_id)){//no database
$this->oops("Could not open database: <b>$this->database</b>.");
}
else{
echo "Database opened <br/>";
}
// unset the data so it can't be dumped
$this->server='';
$this->user='';
$this->pass='';
$this->database='';
}#-#connect()
My code in class Category is:
public static function selectAll() { // SELECT All Function
$db = Database::obtain();
// connect to the server
$db->connect();
$sql = "SELECT * FROM productCategory";
$rows = $db->fetch_array($sql);
return $rows;
}
Database::obtain code
public static function obtain($server=null, $user=null, $pass=null, $database=null){
if (!self::$instance){
self::$instance = new Database($server, $user, $pass, $database);
}
return self::$instance;
}#-#obtain()
Am I doing sth wrong, that I can't see?
Well, the error message is "Access denied for user 'user'#'0.0.0.0'"
That means when you instantiate your class with $db = Database::obtain(); You don't set the values for server, user, pass, database. Probably the class Database implements a singleton pattern, and the method obtain() just returns the instance without any properties set.