So I'm working on a simple user class in php, which has a class variable which contains the mysqli object, however I keep getting the error:
Fatal error: Call to a member function real_escape_string() on a non-object in */classes/user.php on line X
I've checked everything, it should work, but it doesn't. Somehow. This is my code:
namespace bibliotheek;
class user
{
private $mysql;
private $logged_in = false;
private $user_data = null; //ARRAY: user_id, e-mail, password, bevoegdheid, naam, achternaam, adres, postcode, stad
function __construct(\mysqli $mysql, $salt)
{
$this->mysql = $mysql;
}
public function login($email, $pass, $hash = false)
{
$email = $this->mysql->real_escape_string($email);
if($hash == false)
$pass = sha1($this->salt.$pass);
$query = "SELECT *
FROM gebruikers
WHERE gebruikers.email = '$email' AND gebruikers.password = '$pass'";
$result = $this->mysql->query($query);
$user_data = $result->fetch_assoc();
if($user_data == null)
return;
$this->logged_in = true;
$this->user_data = $user_data;
$this->create_cookies($email, $pass);
}
}
And this is how the mysqli object gets passed to the class:
$mysql = new mysqli($cfg['mysql_server'], $cfg['username'], $cfg['password'], $cfg['database']);
$user = new bibliotheek\user($mysql, $cfg['salt']);
the mysql login data is correct, I've made sure of that.
I must be missing something really obvious here, but I just can't see it. Any help is greatly appreciated. Thanks!
And this is how it should be
error_reporting(E_ALL);
$mysql = new mysqli($cfg['mysql_server'], $cfg['username'], $cfg['password'], $cfg['database']);
if ( !$mysql )
{
throw new Exception(mysqli_connect_error()));
}
$user = new bibliotheek\user($mysql, $cfg['salt']);
I'm really f-ing stupid, I compacted my code a bit when I posted it on here and I left out this part:
$this->mysql = $mysql;
$this->mysql = $salt;
Kill me now.
Related
I am new and still lerning php and Im trying to set values that Im retrieving from postgresql database, but Im having problems with my code that i cant figure out and I hope someone here can help me. :)
This is the code:
public function __construct($username, $password)
{
$config = new Config();
$dbconn = pg_connect($config->getDbDsn()); // getDbDsn contains all the information that is needed to connect to the database.
$query = "SELECT username, password, id FROM user.member WHERE username = '$username'";
$result = pg_query($dbconn, $query);
$db = pg_fetch_all($result);
if($db)
{
foreach($db as $d)
{
if( $d['username'] == $username && $d['password'] == $password)
{
$this->verified = true;
$this->id = $d['id']; //save id does not work
$this->user = $d['username']; // save username does not work
}
else
{
$this->verified = false;
}
}
}
else
{
$this->verified = false;
}
}
Okay, this is what im trying to do. First im asking the database to give me the informationen from the table, that is a match to my users username and password. I am using a bool (verified) to verify the user. That works fine. But then, when Im trying to set the values of username and id for my user, that is impossible. If im creating a set_val-function (just to test my code, to try to find my error):
private $a = "";
private function set_val($data){ $this->a = $data; }
and I use that function to set value, in my construct-function:
$this->set_val('hello');
that works fine, until I put that function in my if($db)-statment, then it doesnt work anymore. (it works fine if I put it outside my if($db)-statement, like directly under $db = pg_fetch_all($result);).
$db = pg_fetch_all($result);
$this->set_val('hello'); // This works fine
if($db)
{
$this->set_val('hello'); // This does not work at all
foreach($db as $d)
$this->set_val('hello'); // And not this
}
For my get_val I have this code:
public function get_val(){
return $this->a;
}
(I also have the same get-functions for id and username)
And here Im trying to echo my value, which works fine, if I put the set_val-function outside my if-statement (and foreach-statement):
public function echo_val(){
echo $this->get_val();
}
I have a form that is passing array values to create_parts.php, then I am trying to pass those values to the parts class to insert into the database. At this point I am just lost... The form passes to create_parts.php, I can echo the results of the of the array. However in my class I cant get any values thus, my insert into the database is just a bunch of NULL.
<?php
include_once '../config/database.php';
include_once '../objects/parts_object.php';
$database = new Database();
$db = $database->getConnection();
$parts= new parts($db);
$parts->est_part_idArr=$_POST['est_part_id'];
$parts->part_qtyArr=$_POST['part_qty'];
$parts->part_numArr=$_POST['part_num'];
$parts->part_discArr=$_POST['part_disc'];
$parts->part_costArr=$_POST['part_cost'];
$parts->create();
I am able to to echo out the results here and get
{"est_part_idArr":["123","124"],"part_qtyArr":["4","6"],"part_numArr":
["2334","3344"],"part_discArr":["part","parts"],"part_costArr":["56","33"]
and echo the $stmt
{"queryString":"INSERT INTO \r\n partsT\r\n SET \r\n est_part_id=:est_part_id, part_qty=:part_qty, part_num=:part_num, part_disc=:part_disc, part_cost=:part_cost"}
However in part_object.php I cant get anything to work. I can it to insert to the database but it is all NULL.
class parts{
private $conn;
private $table_name = "partsT";
public $est_part_idArr;
public $part_qtyArr;
public $part_numArr;
public $part_discArr;
public $part_costArr;
public function __construct($db){
$this->conn = $db; }
function create(){
$query = "INSERT INTO
" . $this->table_name . "
SET
est_part_id=:est_part_id, part_qty=:part_qty, part_num=:part_num, part_disc=:part_disc, part_cost=:part_cost";
$stmt = $this->conn->prepare($query);
if(!empty($this->$est_part_idArr)){
for ($i = 0; $i < count($this->$est_part_idArr); $i++) {
if(!empty($this->$est_part_idArr[$i])){
$est_part_id = $this->$est_part_idArr[$i];
$part_qty = $this->$part_qtyArr[$i];
$part_num = $this->$part_numArr[$i];
$part_disc = $this->$part_discArr[$i];
$part_cost = $this->$part_costArr[$i];
$stmt->execute(array(
':est_part_id' => $est_part_id,
':part_qty' => $part_qty,
':part_num' => $part_num,
':part_disc' => $part_disc,
':part_cost' => $part_cost));
}
}
}
$this->est_part_idArr=htmlspecialchars(strip_tags($this->est_part_idArr));
$this->part_qtyArr=htmlspecialchars(strip_tags($this->part_qtyArr));
$this->part_numArr=htmlspecialchars(strip_tags($this->part_numArr));
$this->part_discArr=htmlspecialchars(strip_tags($this->part_discArr));
$this->part_costArr=htmlspecialchars(strip_tags($this->part_costArr));
$stmt->bindParam(":est_part_id", $this->est_part_idArr[0]);
$stmt->bindParam(":part_qty", $this->part_qtyArr[0]);
$stmt->bindParam(":part_num", $this->part_numArr[0]);
$stmt->bindParam(":part_disc", $this->part_discArr[0]);
$stmt->bindParam(":part_cost", $this->part_costArr[0]);
if($stmt->execute()){
return true;
}else{
return false;
}
}
At this point I know
public $est_part_idArr;
public $part_qtyArr;
public $part_numArr;
public $part_discArr;
public $part_costArr;
is wrong I just cant get anything to work.
You are missing some $this in front of your variables to access your public class members. Let us take this line for example:
$est_part_id = $est_part_idArr[$i];
which in my opinion should look like this:
$est_part_id = $this->est_part_idArr[$i];
On the other hand when you bind your parameters some lines down the code you're using something like this:
$stmt->bindParam(":est_part_id", $this->est_part_id);
Which I believe should be
$stmt->bindParam(":est_part_id", $this->est_part_idArr);
or
$stmt->bindParam(":est_part_id", $this->est_part_idArr[0]);
I hope you could help me with this problem:
I tried to implement a pattern MVC in php + HTML5 + css. Now, apart the model, i have a problem when i try to instantiate an PHP object in one of my Controller.
In particular, i have to print the data about the authenticated user, stored in one object, $userObject, that i tried to instantiate with the DataBase data.
So I declared it, i initialized it at Null and, after, i tried to instantiate it with his constructor.
After, when i try to use it, PHP tells me: " Call to a member function getEmail() on a non-object in C:\Users\1USER\Documents\EasyPHP-DevServer-14.1VC11\data\localweb\projects\ammPHP\PHP\Controller\LoginController.php on line 99"
I show you the extract of codes about the problems:
/**the function handle_input rappresent the core of my controller, that popolates the variables of the master.PHP to make a virtual page and to visualize the user's profile.**/
private function handle_input(&$request, &$session)
{
$userObject = null;
$mysqli = new mysqli();
//login module: it verify the user data and modify the $_SESSION's array
//It makes also an object of class AuthenticatedUser that full with the database Data about the logged user.
if(isset($request["userid"]) && isset($request["password"]))
{
if($this->login($request["userid"], $request["password"]))
{
$session["loggedIn"] = true;
$mysqli->connect("localhost", "root", "password", "database");
$userid = $request["userid"];
$password = $request["password"];
$query = "SELECT * FROM loggeduser WHERE (userID = '$userid') AND (passwd = '$password');";
$result = $mysqli->query($query);
//errors checking salted
while($user = $result->fetch_object())
{
$userObject = new AuthenticatedUser($userid, $password, $user -> email, $user -> nome, $user -> cognome, $user -> dataNascita, $user -> città , $user -> CAP, $user -> indirizzo, $user -> cellulare);
}
}//user is logged-in
else if(isset($request["logout"]))
{
$this->logout();
}
//Master.php dedicated module: It verify that user is logged-in, then initialize
//the variables to popolate the master PHP and to make the virtual page of the profile's user.
if(isset($_SESSION["loggedIn"]) && $_SESSION[ "loggedIn"])
{
//CONTROLLO SULLE PAGINA RICHIESTE
if ($request["subpage"] == "profile")
{
$style = "PHP/view/LoggedUserStyle.php";
$header = "PHP/view/Header.php";
$loginFormContent = "PHP/view/loggedUserMenu.php"; //modificato col menù per utenti autenticati
$slideshow = null;
$userProfile = "PHP/view/userProfile.php";
**$user = $userObject -> getEmail(); //Here the problem, PHP tells me that $userObject is not an object! :/**
$payments = null;
$orders = null;
$notFoundContent ="PHP/view/content-not-found.php";
$footer="PHP/view/footer.php";
include("master.php");
}
[...]
}//closing function handle_input
I have been turning and twisting this to the best of my non-existing PDO knowledge, but still without any luck.
the code:
function write($id, $data) {
global $dbcon;
$id = mysql_real_escape_string($id);
$data = mysql_real_escape_string($data);
$sql = $dbcon->exec("INSERT INTO `sessions`
(`session_id`, `session_data`,
`session_expire`, `session_agent`,
`session_ip`, `session_referrer`)
VALUES
(\"".$id."\", \"".$data."\",
\"".time()."\",\"".($this->session_encryption($_SERVER['HTTP_USER_AGENT']))."\",
\"".($this->session_encryption($_SERVER['REMOTE_ADDR']))."\", \"".($this->session_encryption((isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_^~#&|=+;!,(){}[].?%*#'))))."\")
ON DUPLICATE KEY UPDATE
`session_data` = \"".$data."\",
`session_expire` = \"".time()."\"");
return true;
}
Give me the following error:
Fatal error: Call to a member function exec() on a non-object
on the
$sql = $dbcon->exec(
line.
I have been trying to solve this all evening, but without any luck.
This is my PDO connection script:
require_once(INC_PATH.'/config.php');
$dsn = "$db_type:host=$db_host;port=$db_port;dbname=$db_name;charset=$db_charset";
try{
$dbcon = new PDO($dsn, $db_user, $db_pass);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$dbcon = null; //Close database connection.
}
catch(PDOException $e){
echo $e->getMessage();
}
Hope one of you kind souls out there can help me, I would deeply appreciate it!
Thanks.
UPDATE:
I have a global.php file which looks like this:
//Load database
require_once(INC_PATH.'/database.php');
//Load session handler
require_once(INC_PATH.'/class_sessions.php');
$Sessions = new SessionManager();
session_start();
The database.php is included before the sessions class, and when I view the website, it does not give any errors on this part of the sessions class (which is before the write function:
function read($id) {
global $dbcon;
$data = '';
$id = mysql_real_escape_string($id);
$sql = $dbcon->prepare("SELECT
`session_data`
FROM
`sessions`
WHERE
`session_id` = '".$id."'");
$sql->execute();
$a = $sql->columnCount();
if($a > 0) {
$row = $sql->fetchObject();
$data = $row['session_data'];
}
return $data;
}
Are you sure your connection script is getting executed? Try checking if $dbcon is set. Also, you may be missing global $dbcon within the connection script.
By the way, since you're already using PDO, might I recommend you use placeholders in your query:
$sql = "INSERT INTO `sessions`
(`session_id`, `session_data`, `session_expire`,
`session_agent`, `session_ip`, `session_referrer`)
VALUES
(:session_id, :session_data, :session_expire,
:session_agent, :session_ip, :session_referrer)
ON DUPLICATE KEY UPDATE
`session_data` = :session_data,
`session_expire` = :session_expire";
$params = array(
':session_id' => $id,
':session_data' => $data,
':session_expire' => time(),
':session_agent' => $this->session_encryption($_SERVER['HTTP_USER_AGENT']),
':session_ip', => $this->session_encryption($_SERVER['REMOTE_ADDR']),
':session_referrer' => $this->session_encryption((isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_^~#&|=+;!,(){}[].?%*#';
);
$stmt = $dbcon->prepare($sql);
if ($stmt->execute($params) === FALSE) {
// handle error
}
First check that the global object is not being overwritten by another function. I strongly suggest you use Dependency injection instead of globals.
$Sessions = new SessionManager($dbcon);
And inside the Session Management class you can do something like
class SessionManager
{
protected $db;
public function __construct($db) { $this->db = $db; }
public function read($id)
{
$stmt = $this->db->prepare("SELECT session_data
FROM sessions
WHERE session_id = ?");
$stmt->execute(array($id));
return $stmt->fetchColumn();
}
}
And secondly, since you are using PDO, you dont need to call mysql_real_escape_string(), use prepared statements and placeholders :)
If I declare a global variable such as a database connection of $mysqli how do I use that in a class. i am trying to use it in my user class. Do i store it as a public variable in the class or as a global in the function itself. I also think there is something wrong with my following code but I may be wrong.
class USER
{
function __constructor()
{
}
/*
* adds a new user
* returns FALSE on error
* returns user id on success
*/
function add_member($name, $email, $password)
{
global $mysqli;
$query = "INSERT INTO members
SET
user_name = {'$name'},
user_email = {'$email'},
password = ['$password'}";
$success = $mysqli -> query ($query);
if (!$success || $mysqli -> affected_rows == 0)
{
echo "<p> An error occurred: you just are not tough enough!!!</p>";
return FALSE;
}
$uid = $mysqli -> insert_id;
return $uid;
}
} // end class
$uc = new USER();
?>
<?php
require_once ('includes/classes/database.php');
require_once('includes/classes/user.php');
require_once('includes/header.php');
// if user submits a new registration
if (isset($_POST['name'],$_POST['email'],$_POST['pwd'],$_POST['pwd2']))
{
// validate input fields
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['pwd'];
$password2 = $_POST['pwd2'];
// if error fall through and redisplay page with errors
// if no errors update database and redirect to homepage
if ($uc->add_member($name, $email, $password) === FALSE)
{
echo "System Error. damn if I know what to do";
}
else
{
header("location: homepage.php");
}
}
You um... don't. Instead use a variable inside of the class:
class USER
{
private $mysql;
function __constructor($mysqli)
{
$this->mysqli = $mysqli;
}
function add_member($name, $email, $password)
{
$mysqli = $this->mysqli;
/* yada yada */
Couple of issues by the way:
// You want the ' outside of the {}
$query = "INSERT INTO members
SET
user_name = '{$name}',
user_email = '{$email}',
password = '{$password}'";// there was a [ not a {
You also want to call mysqli_real_escape_string on all of those variables. Or better yet use mysqli_bind_param and a prepared statement.