Object Variable Remains Undefined after being Set in Constructor - php

This is the code of my class, only relevant parts of course:
class User {
public $id;
public function __construct($email, $password, $firstName, $lastName) {
$db = Connection::getInstance();
// check if user exists
$id = User::findUserByEmail($email);
if($id > 0){
// echo "User already exists!";
return -1;
}
// Create new row in users table
$stmt = $db->prepare("INSERT INTO `mapdb`.`user` (`email`, `password`, `firstName`, `lastName`)
VALUES (:email, :password, :firstName, :lastName);");
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':firstName', $firstName, PDO::PARAM_STR);
$stmt->bindParam(':lastName', $firstName, PDO::PARAM_STR);
$stmt->execute();
// check f user added successfully
$newID = User::findUserByEmail($email);
if($newID > 0){
echo "success, ID = ".$newID;
$this->$id = $newID;
// $this->$email = $email;
// $this->$firstName = $firstName;
// $this->$firstName = $firstName;
} else {
echo "failure";
return -1;
}
}
}
And where I actually call the constructor:
$user = new User($email, $password, $firstName, $lastName);
echo "<br>userid: ".$user->id; // (<-- this doesn't echo correctly)
I cannot get the value from the User object whatever I try.
At the moment I get the following error:
Notice: Undefined variable: id
What could possibly deny me access from the variable?

Problem solved, instead of
$this->$id = $newID;
I should have
$this->id = $newID;
Thank goodness for stackoverflow :D

Related

I'm having trouble to pass session variable . It is working on localhost but not on server. (PHP 7.4) [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
This is the login.php,
with the local host my web site is working properly. However, on server it is not working.
The web site is conecting with DB and checking the user, email, password, but the session is not starting.
I have checked already the PHP version from both, localhost and server. They are the same version php 7.4.
I have no Idea how to fix this problem, if you know how to fix it, I have already paid some people with more experience to fix it. but they didn't fix. so if you can help me to solve it please contact me and we can negotiate it.
thanks all
require_once 'php/dbconfig.php';
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function register($fname, $mname, $lname, $uname, $dob, $pnumber, $streetname, $number, $city, $state, $postcode, $country, $umail, $upass, $usertype )
{
try
{
$new_password = password_hash($upass, PASSWORD_DEFAULT);
$stmt = $this->conn->prepare("INSERT INTO customers(FName,MName, LName, UserName, DOB, PNumber, StreetName, Number, City, State, PostCode, Country, Email, Password, UserType)
VALUES(:fname, :mname, :lname, :uname, :dob, :pnumber, :streetname, :number, :city, :state, :postcode, :country, :umail, :upass, :usertype)");
$stmt->bindparam(":fname", $fname);
$stmt->bindparam(":mname", $mname);
$stmt->bindparam(":lname", $lname);
$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":dob", $dob);
$stmt->bindparam(":pnumber", $pnumber);
$stmt->bindparam(":streetname", $streetname);
$stmt->bindparam(":number", $number);
$stmt->bindparam(":city", $city);
$stmt->bindparam(":state", $state);
$stmt->bindparam(":postcode", $postcode);
$stmt->bindparam(":country", $country);
$stmt->bindparam(":umail", $umail);
$stmt->bindparam(":upass", $new_password);
$stmt->bindparam(":usertype", $usertype);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function doLogin($uname,$umail,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT CustomerID, UserType, UserName, FName, LName, Email, Password FROM customers WHERE UserName=:uname OR Email=:umail");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail,));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(password_verify($upass, $userRow['Password']))
{
$_SESSION['user_session'] = $userRow['CustomerID'];
$_SESSION['user_name']= $userRow['UserName'];
$_SESSION['user_fname']= $userRow['FName'];
$_SESSION['user_lname']= $userRow['LName'];
$_SESSION['user_usertype']= $userRow['UserType'];
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function is_loggedin()
{
if(isset($_SESSION['user_session']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function doLogout()
{
session_destroy();
unset($_SESSION['user_session']);
return true;
}
}
?>
Add session_start(); start of the page.
<?php
session_start(); //add this line
require_once 'php/dbconfig.php';

Updating MySQL table with a PHP script

I am developing an android application, where I want to insert the address of the user to the database calling a PHP script on a website.
In the first try, it has to insert the address into the database and after that, it has update the same tuple.
This is the PHP script I have, but it gives an error in line number 36 (Call to a member function bind_param()).
Nevertheless, insertion is working perfectly fine.
class DbOperations1{
private $con;
function __construct(){
require_once dirname(__FILE__).'/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
public function createUser ($name, $email, $password) {
if($this->isUserExist($name, $email))
{
return 0;
}else{
$password = md5($password);
$stmt = $this->con->prepare("INSERT INTO `test` (`id`,`name`, `email`, `password`) VALUES (NULL, ? , ? , ? );");
$stmt->bind_param ("sss", $name, $email, $password);
if ($stmt->execute()){
return 1;
} else {
return 2;
}
}
}
public function Address($id_user, $address, $road, $city, $country) {
if($this->isAddressExist($id_user, $address))
{
$stmt = $this->con->prepare("UPDATE address a, users u SET `address`=$address,`road`=$road,`city`=$city,`country`=$country WHERE a.id_user=u.id");
$stmt->bind_param("ssss", $address, $road, $city, $country);
if ($stmt->execute()){
return 2;
} else {
return 3;
}
}else{
$stmt = $this->con->prepare("INSERT INTO `address` (`id_address`, `id_user`,`address`, `road`, `city`, `country`) VALUES (NULL, ?, ? , ? ,? ,? );");
$stmt->bind_param ("sssss", $id_user, $address, $road, $city, $country);
if ($stmt->execute()){
return 0;
} else {
return 1;
}
}
}
public function userLogin($email, $password){
$password = md5($password);
$stmt = $this->con->prepare("SELECT id FROM users WHERE email = ? AND password = ?");
$stmt->bind_param("ss",$email,$password);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
public function getUserByemail($email){
$stmt = $this->con->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s",$email);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
private function isUserExist($name, $email){
$stmt = $this->con->prepare("SELECT id FROM test WHERE name = ? OR email = ?");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
private function isAddressExist($id_user){
$stmt = $this->con->prepare("SELECT id_address FROM address WHERE id_user = ?");
$stmt->bind_param("s", $id_user);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
}
According to your comments, the error is because of call to prepare failing.
Following code will allow to get more info:
if($this->isAddressExist($id_user, $address))
{
$stmt = $this->con->prepare("UPDATE address a, users u SET `address`=$address,`road`=$road,`city`=$city,`country`=$country WHERE a.id_user=u.id");
if($stmt != False) {
$stmt->bind_param("ssss", $address, $road, $city, $country);
if ($stmt->execute()){
return 2;
} else {
return 3;
}
} else {
// this line will give an insight into an error message
echo $this->con->error;
}
}
After getting the error message from MySQL:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'road=Sarak,city=Khost,country=Afghanistan WHERE a.id_user= 10' at line 1
we locate exact error location and there is $address variable used, while it shall be ?! Such statement can't be prepared.
Using following update statement should fix it:
$stmt = $this->con->prepare("UPDATE address a, users u SET `address`=?,`road`=?,`city`=?,`country`=? WHERE a.id_user=u.id");
public function Address($id_user, $address, $road, $city, $country) {
if($this->isAddressExist($id_user))
{
$stmt = $this->con->prepare("UPDATE address SET `address`=?,`road`=?,`city`=?,`country`=? WHERE id_user= ?");
if($stmt != False) {
$stmt->bind_param("ssss", $address, $road, $city, $country,$id_user);
if ($stmt->execute()){
return 2;
} else {
return 3;
}
} else {
// hopefully this line will give an insight into an error message
echo $this->con->error;
}
} else{
$stmt = $this->con->prepare("INSERT INTO `address` (`id_address`, `id_user`,`address`, `road`, `city`, `country`) VALUES (NULL, ?, ? , ? ,? ,? );");
$stmt->bind_param ("sssss", $id_user, $address, $road, $city, $country);
if ($stmt->execute()){
return 0;
} else {
return 1;
}
}
}
This should work. When it comes to parameter binding you have to use ? (question mark ) instead of the parameter name and bind the parameters by name in the correct order in bind_param function.
$stmt = $this->con->prepare("UPDATE address SET `address`=$address,`road`=$road,`city`=$city,`country`=$country WHERE a.id_user=u.id");
try to update one table

PDO: How to make checks

I create this class but i'm newbie in PHP OOP & PDO and i don't know how and where i must to make check to username is valid , email is valid and e.t.c..
This is my code
Class Users {
private $db;
public function __construct(Database $datebase) {
if (!$database instanceOf Database) {
throw new Exeption();
}
$this->db = $datebase;
}
public function userRegistration($username, $password, $email) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$regdate = date('d.m.Y');
$query = $this->db->prepare("INSERT INTO `users` (`username`, `password`, `email`, `regdate`) VALUES (?, ?, ?, ?) ");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->bindValue(3, $email);
$query->bindValue(4, $regdate);
return ($query->execute()) ? true : false ;
}
}
If you want to check something, use Respect/Validation. For example:
$usernameValidator = v::alnum()->noWhitespace()->length(1,15);
$usernameValidator->validate($_POST['username']); //true or false
$passwordValidator = v::alnum()->length(10, null);
$passwordValidator->validate($_POST['password']); //true or false
v::email()->validate($_POST['email']); //true or false
To check if the username or email exist in your database you can use SQL to search the email or username.
$query = $this->db->prepare("SELECT * FROM users WHERE email = ? ");
$query->bindValue(1, $email);
If the query returns a value than the email or username already exist in your database. From there you can show your own validation.
To check check if user or email exist you don't need another class, just add another method called userExist or emailExist and run a query and then check if you get a result.
public function emailExist($email){
$query = $this->db->prepare("SELECT * FROM users WHERE email = ? ");
$query->bindValue(1, $email);
try{
$query->execute();
//use the if statement and $query->rowCount() to check if there is a result
$rows = $query->rowCount();
if($rows === 1){
return true;
} else {
return false;
}
}catch (PDOException $e) {
die($e->getMessage());
}
}

PHP insert into mysql database with dates

I would like to be able to add children into a database, which are connected to their parents (who has a member id MID). I believe that the error lies within the date format (atleast that's what I believe), I have also tried to use strtotime($dob), however this didn't change anything.
$name = htmlspecialchars($_GET['Name']);
$dob = $_GET['DOB'];
$newDOB = date("Y-m-d", $dob);
$mid = $_GET['mid'];
if(isset($_GET['Name'], $_GET['DOB'], $_GET['mid']))
$alert = true;
if(!empty($name) && !empty($newDOB) && !empty($mid))
add_family_member($mid, $newDOB, $name);
The function that adds the member:
function add_family_member($mid, $dob, $name)
{
global $con;
$sql = "INSERT INTO Children(MID, DOB, Name) VALUES(?, ?, ?)";
$stmt = $con->prepare($sql);
if($stmt)
{
$b = $stmt->bind_param("iss", $mid, $dob, $name);
if($b)
{
$e = $stmt->execute();
if($e)
return true;
}
}
return false;
}
function add_family_member($mid, $dob, $name)
{
global $con;
$sql = "INSERT INTO Children(MID, DOB, Name) VALUES(:mid, :dob, :name)";
$stmt = $con->prepare($sql);
if($stmt)
{
return $stmt->execute(array(
'mid' => $mid,
'dob' => $dob,
'name' => $name
));
}
return false;
}
see http://www.php.net/manual/en/pdostatement.execute.php for more examples
Try...
function add_family_member($mid, $dob, $name)
{
global $con;
$sql = "INSERT INTO Children(MID, DOB, Name) VALUES(:mid, :dob, :name)";
$stmt = $con->prepare($sql);
$stmt->bindParam(':mid', $mid);
$stmt->bindParam(':dob', $dob);
$stmt->bindParam(':name', $name);
if ($stmt->execute()) {
return true;
}
return false;
}

Something breaks while including a php class in ajax

I am having a problem while including a php class with ajax.
Basically I have index.php which loads with ajax example.php. example.php includes init.php, which in turn includes a bunch of classes. I narrowed it down to users.php class, which I pasted below. I also put init.php under it just in case.
The file simply will not load with ajax. It works fine if i go directly to it.
<?php
class Users{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function update_user($first_name, $last_name, $gender, $bio, $image_location, $id){
$query = $this->db->prepare("UPDATE `users` SET
`first_name` = ?,
`last_name` = ?,
`gender` = ?,
`bio` = ?,
`image_location`= ?
WHERE `id` = ?
");
$query->bindValue(1, $first_name);
$query->bindValue(2, $last_name);
$query->bindValue(3, $gender);
$query->bindValue(4, $bio);
$query->bindValue(5, $image_location);
$query->bindValue(6, $id);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}
public function change_password($user_id, $password) {
global $bcrypt;
/* Two create a Hash you do */
$password_hash = $bcrypt->genHash($password);
$query = $this->db->prepare("UPDATE `users` SET `password` = ? WHERE `id` = ?");
$query->bindValue(1, $password_hash);
$query->bindValue(2, $user_id);
try{
$query->execute();
return true;
} catch(PDOException $e){
die($e->getMessage());
}
}
public function recover($email, $generated_string) {
if($generated_string == 0){
return false;
}else{
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email` = ? AND `generated_string` = ?");
$query->bindValue(1, $email);
$query->bindValue(2, $generated_string);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
global $bcrypt;
$username = $this->fetch_info('username', 'email', $email); // getting username for the use in the email.
$user_id = $this->fetch_info('id', 'email', $email);// We want to keep things standard and use the user's id for most of the operations. Therefore, we use id instead of email.
$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$generated_password = substr(str_shuffle($charset),0, 10);
$this->change_password($user_id, $generated_password);
$query = $this->db->prepare("UPDATE `users` SET `generated_string` = 0 WHERE `id` = ?");
$query->bindValue(1, $user_id);
$query->execute();
mail($email, 'Your password', "Hello " . $username . ",\n\nYour your new password is: " . $generated_password . "\n\nPlease change your password once you have logged in using this password.\n\n-Example team");
}else{
return false;
}
} catch(PDOException $e){
die($e->getMessage());
}
}
}
public function fetch_info($what, $field, $value){
$allowed = array('id', 'country', 'money', 'flag', 'email'); // I have only added few, but you can add more. However do not add 'password' eventhough the parameters will only be given by you and not the user, in our system.
if (!in_array($what, $allowed, true) || !in_array($field, $allowed, true)) {
throw new InvalidArgumentException;
}else{
$query = $this->db->prepare("SELECT $what FROM `users` WHERE $field = ?");
$query->bindValue(1, $value);
try{
$query->execute();
} catch(PDOException $e){
die($e->getMessage());
}
return $query->fetchColumn();
}
}
public function confirm_recover($email){
$username = $this->fetch_info('username', 'email', $email);// We want the 'id' WHERE 'email' = user's email ($email)
$unique = uniqid('',true);
$random = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'),0, 10);
$generated_string = $unique . $random; // a random and unique string
$query = $this->db->prepare("UPDATE `users` SET `generated_string` = ? WHERE `email` = ?");
$query->bindValue(1, $generated_string);
$query->bindValue(2, $email);
try{
$query->execute();
mail($email, 'Recover Password', "Hello " . $username. ",\r\nPlease click the link below:\r\n\r\nhttp://www.example.com/recover.php?email=" . $email . "&generated_string=" . $generated_string . "\r\n\r\n We will generate a new password for you and send it back to your email.\r\n\r\n-- Example team");
} catch(PDOException $e){
die($e->getMessage());
}
}
public function user_exists($username) {
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
$query->bindValue(1, $username);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch (PDOException $e){
die($e->getMessage());
}
}
public function email_exists($email) {
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email`= ?");
$query->bindValue(1, $email);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch (PDOException $e){
die($e->getMessage());
}
}
public function register($username, $password, $email, $country, $timezone, $dst){
global $bcrypt; // making the $bcrypt variable global so we can use here
$date = date( 'Y-m-d' );
$ip = $_SERVER['REMOTE_ADDR']; // getting the users IP address
$email_code = $email_code = uniqid('code_',true); // Creating a unique string.
$password = $bcrypt->genHash($password);
$query = $this->db->prepare("INSERT INTO `users` (`username`, `password`, `email`, `country`, `timezone`, `dst`, `ip`, `regdate`, `email_code`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->bindValue(3, $email);
$query->bindValue(4, $country);
$query->bindValue(5, $timezone);
$query->bindValue(6, $dst);
$query->bindValue(7, $ip);
$query->bindValue(8, $date);
$query->bindValue(9, $email_code);
try{
$query->execute();
mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.touringlegends.com/register.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
public function activate($email, $email_code) {
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email` = ? AND `email_code` = ? AND `accountlevel` = ?");
$query->bindValue(1, $email);
$query->bindValue(2, $email_code);
$query->bindValue(3, 0);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
$query_2 = $this->db->prepare("UPDATE `users` SET `accountlevel` = ? WHERE `email` = ?");
$query_2->bindValue(1, 1);
$query_2->bindValue(2, $email);
$query_2->execute();
return true;
}else{
return false;
}
} catch(PDOException $e){
die($e->getMessage());
}
}
public function email_confirmed($email) {
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email`= ? AND `accountlevel` >= ?");
$query->bindValue(1, $email);
$query->bindValue(2, 1);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch(PDOException $e){
die($e->getMessage());
}
}
public function login($email, $password) {
global $bcrypt; // Again make get the bcrypt variable, which is defined in init.php, which is included in login.php where this function is called
$query = $this->db->prepare("SELECT `password`, `id` FROM `users` WHERE `email` = ?");
$query->bindValue(1, $email);
try{
$query->execute();
$data = $query->fetch();
$stored_password = $data['password']; // stored hashed password
$id = $data['id']; // id of the user to be returned if the password is verified, below.
if($bcrypt->verify($password, $stored_password) === true){ // using the verify method to compare the password with the stored hashed password.
return $id; // returning the user's id.
}else{
return false;
}
}catch(PDOException $e){
die($e->getMessage());
}
}
public function userdata($id) {
$query = $this->db->prepare("SELECT * FROM `users` WHERE `id`= ?");
$query->bindValue(1, $id);
try{
$query->execute();
return $query->fetch();
} catch(PDOException $e){
die($e->getMessage());
}
}
public function get_users() {
$query = $this->db->prepare("SELECT * FROM `users` ORDER BY `time` DESC");
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
return $query->fetchAll();
}
}
init.php:
<?php
session_start();
require($_SERVER['DOCUMENT_ROOT'].'/core/connect/database.php');
require($_SERVER['DOCUMENT_ROOT'].'/core/classes/users.php');
require($_SERVER['DOCUMENT_ROOT'].'/core/classes/general.php');
require($_SERVER['DOCUMENT_ROOT'].'/core/classes/bcrypt.php');
require($_SERVER['DOCUMENT_ROOT'].'/core/classes/garage.php');
// error_reporting(0);
$users = new Users($db);
$general = new General();
$bcrypt = new Bcrypt(12);
$errors = array();
if ($general->logged_in() === true) {
$user_id = $_SESSION['id'];
$user = $users->userdata($user_id);
}
ob_start();
Here is the js loading the files (its a bit weird because its reloading jscrollpane, but working fine with html and php that dosent need external classes):
// Ajax
$(function () {
var api = $("#garagecontent").jScrollPane().data('jsp');
var reinitialiseScrollPane = function()
{
api.reinitialise();
}
// attaching click handler to links
$(document).on('click', '#garagecontainer a[href]', function (e) {
// cancel the default behaviour
e.preventDefault();
// get the address of the link
var href = $(this).attr('href');
// getting the desired element for working with it later
var $wrap = $('#garagecontent');
$wrap
// removing old data
api.getContentPane()
// load the remote page
.load(href, reinitialiseScrollPane , function (){
}
);
});
});
I have narrowed it down to users.php because it will work when I remove it from the includes (and its functions in init.php).
Can anyone spot what is breaking my code?
The solution to this question was using an autoloader. The page was breaking because of duplicate classes being called. My fault for having errors disabled i guess.

Categories