I have problem with get data from database.
This is my function:
public function get_fullname($uid)
{
$result = mysql_query("SELECT name FROM users WHERE uid = $uid");
var_dump(mysql_result($result));
if(mysql_result($result)>0){
//$user_data = mysql_fetch_array($result);
echo $user_data['name'];
}
else{
print_r('chuj');
}
}
and this is my function call:
$uid = $_SESSION['uid'];
$user = new User();
$register = $user->get_fullname($uid);
What is wrong with my code?
Full class in file Functions.php:
include_once 'config.php';
class User
{
//Połączenie z bazą danych
public function __construct()
{
$db = new DB_Class();
}
//Rejestracja
public function register_user($name, $username, $password, $email)
{
$password = md5($password);
$sql = mysql_query("SELECT uid from users WHERE username = '$username' or email = '$email'");
$no_rows = mysql_num_rows($sql);
if ($no_rows == 0)
{
$result = mysql_query("INSERT INTO users(username, password, name, email) values ('$username', '$password','$name','$email')") or die(mysql_error());
return $result;
}
else
{
return FALSE;
}
}
//Logowanie
public function check_login($emailusername, $password)
{
$password = md5($password);
$result = mysql_query("SELECT uid from users WHERE email = '$emailusername' or username='$emailusername' and password = '$password'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if ($no_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
var_dump($_SESSION);
return TRUE;
}
else
{
return FALSE;
}
}
//Pobieranie imienia
public function get_fullname($uid)
{
$result = mysql_query("SELECT * FROM users WHERE uid ='".$uid."'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if($no_rows>0){
$user_data = mysql_fetch_array($result);
//echo $user_data['name'];
return $user_data['name'];
}
else{
print_r('chuj');
return FALSE;
}
}
//Sesja
public function get_session()
{
return $_SESSION['login'];
}
//Wylogowanie
public function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}
}
?>
Fatal error: Call to undefined method User->get_fullname()
Rizier123's comment is correct, but not the cause of your problem.
I tried to reproduce the error but failed. That means that probably you're using an old version somewhere. If you're using FTP or the like, are you sure you uploaded the User class since you added the function?
Also, make sure that the most recent User class is included in the file where you're using it.
Related
When i try to verify user data by verify_user method
<?php
public static function verify_user ($username , $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$query = "SELECT * FROM users WHERE username = '{$username}' and password = '{$password}' LIMIT 1";
$result_array = self::find_this_query($query);
if (!empty($result_array)) {
$result_array = array_shift($result_array);
return $result_array;
} else {
return false;
}
}
here also my find_this_query method
public static function find_this_query ($enter_here_your_sql_query)
{
global $database;
$result = $database->query($enter_here_your_sql_query);
return $result;
}
and try to login a user here also my login.php code
<?php
if($session->is_signed_in()) {
redirect("index.php");
}
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
}
//method to check db user
$user_found = User::verify_user($username , $password);
if ($user_found) {
$session->login($user_found);
redirect("index.php");
} else {
$the_message = "<p class='alert alert-warning' style='color: grey'>Your password or username is incorrect</p>";
$username = "";
$password = "";
}
?>
i get that error on login page
Warning: array_shift() expects parameter 1 to be array, object given in /admin/includes/User.php on line 189
here line 189 from user.php class
$result_array = array_shift($result_array);
What i do wrong here?
$database->query() does not return an array, it returns an object. Try using $database->fetch_array().
The mysqli::query() function doesn't return an array, it returns a mysqli_result object.
mysqli_result implements the Traversable interface, which allows you to use some array operations on it like foreach, but most other array operations don't work. In particular, you can't use array_shift() on this object.
Instead of
$result_array = array_shift($result_array);
return $result_array;
use:
$row = $result_array->fetch_assoc();
return $row;
i solve that issue by the Help give me Barmar.
Here my updated verify_user function
public static function verify_user ($username , $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$query = "SELECT * FROM users WHERE username = '{$username}' and password = '{$password}' LIMIT 1";
$result_array = self::find_this_query($query);
if (!empty($result_array)) {
$result_array = $result_array->fetch_array();
return $result_array;
}else{
return false;
}
}
and here my updated login.php
if($session->is_signed_in()) {
redirect("index.php");
}
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
}
//method to check db user
$user_found = User::verify_user($username , $password);
$user = User::instantiation($user_found);
$user_id = $user->id;
if ($user_id){
$session->login($user);
redirect("index.php");
} else {
$the_message = "<p class='alert alert-warning' style='color: grey'>Your password or username is incorrect</p>";
$username = "";
$password = "";
}
Okay so heres the issue, I am trying to making a fancy login system that stores the users data in a php class so it is easy to access. However when I try to call the function that will build the user data it throws this exception.
Fatal error: Uncaught Error: Call to a member function buildUserData() on string in C:\xampp\htdocs\cfgs\submit\login.php:38 Stack trace: #0 {main} thrown in C:\xampp\htdocs\cfgs\submit\login.php on line 38
Here is the userData class code
<?php
class userData {
public $accId = null;
public $username = null;
public $rank = null;
public $vip_rank = null;
public $email = null;
public $auth = null;
function buildUserData($id) {
$result = $db->query("SELECT * FROM users WHERE id = '$id'");
while ($row = $result->fetch_assoc()) {
$this->accId = $id;
$this->username = $row['username'];
$this->rank = $row['rank'];
$this->vip_rank = $row['rank_vip'];
$this->email = $row['mail'];
$this->auth = $row['auth'];
}
}
}
?>
This is the login.php code
<?php
require_once '../../global.php';
if(!isset($_POST['submit'])) {
header("Location: ../../index");
return;
} else {
$user = $db->escapestring($_POST['user']);
$pass = $db->escapestring($_POST['pass']);
if (empty($user) || empty($pass)) {
$_SESSION['logError'] = "Both fields must be filled!";
header("Location: ../../index");
return;
} else {
$result = $db->query("SELECT * FROM users WHERE username = '$user'");
$result = $db->getrows($result);
if ($result < 1) {
$_SESSION['logError'] = "Username does not exist!";
header("Location: ../../index");
return;
} else {
$pass = md5($pass);
$result = $db->query("SELECT * FROM users WHERE username = '$user' AND password = '$pass'");
$result = $db->getrows($result);
if ($result < 1) {
$_SESSION['logError'] = "Details do not match!";
header("Location: ../../index");
return;
} else {
$result = $db->query("SELECT * FROM users WHERE username = '$user' AND password = '$pass'");
while($row = $result->fetch_assoc()){
$username = $row['username'];
$id = $row['id'];
}
$user->buildUserData($id);
$_SESSION['logError'] = "Hello ". $user->username;
header("Location: ../../index");
return;
}
}
}
}
?>
This is the global.php code
<?php
session_start();
require_once 'cfgs/class.database.php';
require_once 'cfgs/class.user.php';
$user = new userData; // I don't want to build data just yet
$db = new database;
$db->conn = $db->connect();
?>
And finally my database handler
<?php
class database {
public $host = "_";
public $user = "_";
public $pass = "_";
public $db = "_";
public $conn = null;
function connect() {
return mysqli_connect($this->host, $this->user, $this->pass, $this->db);
}
function query($sql) {
return mysqli_query($this->conn, $sql);
}
function escapestring($string){
return mysqli_real_escape_string($this->conn, $string);
}
function getrows($sql){
return mysqli_num_rows($sql);
}
}
?>
I did search for a solution myself but it turns out to be one of those specific things that is difficult to find the answer you're looking for.
while you initialise $user just fine:
$user = new userData;
you later overwrite the variable:
$user = $db->escapestring($_POST['user']);
one of the 2 needs a new name,
I want the user to login automatically after registration, been trying this for hours but nothing has worked so far.
The code on index.php that creates the session:
<?php
session_start();
require("inc/user.functions.php");
$sessionkey = "";
if(isset($_SESSION['sessionkey']))
$sessionkey = $_SESSION['sessionkey'];
$account = new Account($sessionkey);
user.funtions.php: (login, registration etc.)
<?php
require("config.php");
require("global.functions.php");
class Account {
public $LoggedIn = false;
public $Username;
public $level;
public $uid;
public $Avatar;
public $admin;
public $Email;
public $Bio;
public function __construct($sessionkey) {
if($sessionkey != "" && $this->session_check($sessionkey) == true) {
$this->LoggedIn = true;
}
}
private function session_check($sessionkey) {
global $mysql;
$query = $mysql->query("SELECT * FROM table_users WHERE sessionkey = '$sessionkey'");
$check = $query->num_rows;
if($check > 0) {
while($row = $query->fetch_assoc()) {
$this->uid = $row['uid'];
$this->Username = $row['username'];
$this->level = $row['level'];
$this->Avatar = $row['avatar'];
$this->admin = $row['admin_access'];
$this->Email = $row['email'];
$this->Bio = $row['bio'];
}
return true;
}
return false;
}
}
function login_account($username, $password) {
global $mysql;
$query = $mysql->query("SELECT * FROM table_users WHERE username = '$username' OR email = '$username'");
$check = $query->num_rows;
if($check > 0) {
while($row = $query->fetch_assoc()) {
$uid = $row['uid'];
$hash = $row['password'];
}
if(verifyPassword($password, $hash) == true) {
UpdateSession($uid);
return true;
} else
return false;
} else
return false;
}
function register_account($firstname, $lastname, $gender, $email, $username, $password) {
global $mysql;
//If email is not in correct format e.g example#example.com
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return "Vääränlainen sähköpostiosoite!";
}
//If email exists in the database
if(email_exists($email) == true) {
return "Sähköposti on jo rekisteröity!";
}
//If username exists in the database
if(username_exists($username) == true) {
return "Käyttäjänimi on jo rekisteröity!";
}
$date = date("Y-m-d H:m:s");
//Create a row into table_users
$mysql->query("INSERT INTO table_users (username, password, email, fullname, gender, level, avatar, admin_access, views, date_registered) VALUES ('$username', '".hashPassword($password)."', '$email', '$firstname $lastname', '$gender', 0, 'default.png', 0, 0, '$date') ");
return "Käyttäjätilisi on nyt rekisteröity!";
}
function email_exists($email) {
global $mysql;
$query = $mysql->query("SELECT * FROM table_users WHERE email = '$email'");
$check = $query->num_rows;
if($check > 0)
return true;
return false;
}
function username_exists($username) {
global $mysql;
$query = $mysql->query("SELECT * FROM table_users WHERE username = '$username'");
$check = $query->num_rows;
if($check > 0)
return true;
return false;
}
function hashPassword($password) {
return password_hash($password, PASSWORD_BCRYPT, [ 'cost' => 15 ]);
}
function verifyPassword($password, $hash) {
if (password_verify($password, $hash))
return true;
else
return false;
}
function UpdateSession($uid) {
global $mysql;
$sessionkey = base64_encode(randomString(35));
$_SESSION['sessionkey'] = $sessionkey;
$query = $mysql->query("UPDATE table_users SET sessionkey = '$sessionkey' WHERE uid = '$uid'");
}
function sessionkey_check($sessionkey) {
global $mysql;
$query = $mysql->query("SELECT * FROM table_users WHERE sessionkey = '$sessionkey'");
if($query->num_rows > 0)
return true;
return false;
}
?>
Use the $inseted_id=$mysqli->insert_id to get inserted id and all other information you have before. Now create the user SESSION and header location change
I have defined a function to check user credentials and would like it to return true if the auth passed and false if it failed. my function is defined as follows:
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
return $logged_in;
}
the problem I am running into is this, when I call the function and try to use what should be the returned value I get an error that the variable is not defined.
_userLogin($username, $password);
if ($logged_in == True){
'do something';
} else {
'do something else'
}
what am I doing wrong?
You are trying to use the variable $logged_in that is defined in function _userLogin outside the block. Assign the return value that is returned by the function like,
$logged_in = _userLogin($username, $password)
if ($logged_in == True){
'do something';
} else {
'do something else'
}
Also you will always receive TRUE because you are accessing variables $salt, $password outside the if block where they are being retrieved thus the fields not being assigned properly.
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in = false;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
$dbpass = '';
$salt = '';
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
}
}
return $logged_in;
}
PLEASE NOTE: I did not perform any logic checks other than fix your syntax
Replace your branching (where you use the function) with the simpler:
if( _userLogin($username, $password) ){
//success
}else{
//failure
}
I cant seem to validate right when i have an empty field or when the username is wrong or doesnt match. please any help or pointing me would be very helpful. I tried (empty but it doesnt seem to work when i fill in one field and the other is empty its says all fields are empty. and for the wrong credentials its not working at all.
INDEX.PHP
<?php
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
$log = $_SESSION['uid'];
if ($user->get_session($log)){
header("Location: profile.php?uid=".$log."");
}
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if(!empty($login)){
if($emailusername != $login){
if($password != $login){
if ($login) {
// Registration Success
$log_id = $_SESSION['uid'];
header("location: profile.php?uid=".$log_id."");
}
}else
echo "Incorrect Password";
}else
echo "Incorrect Email";
}else
echo "Fill in fields";
}
?>
USERS.PHP
<?php
include "db_config.php";
class User{
public $db;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$sql2="SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
session_start();
$emaildb == $_SESSION['uemail'];
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return true;
}
else{
return false;
}
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
Based on what you have, this is what you would need.
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
// You need a conditional incase this session isn't set
$log = (isset($_SESSION['uid']))? $_SESSION['uid']:false;
if($log !== false && $user->get_session($log)){
header("Location: profile.php?uid=".$log."");
exit;
}
if(isset($_POST['submit'])) {
// This function should be validating your login so you don't need
// any comparisons after the fact.
$login = $user->check_login($_POST['email'], $_POST['password']);
if($login !== false)
header("location: profile.php?uid=".$log_id."");
exit;
else {
foreach($user->error as $kind => $err) {
echo '<h2>'.$kind.'</h2>'.'<p>'.$err.'</p>';
}
}
}
Your user class: You can throw error reporting into this class if you want to.
class User{
public $db;
public $error;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
$this->error['db'] = "Error: Could not connect to database.";
echo $this->error['db'];
exit;
}
}
/*** for login process ***/
public function check_login($emailusername='', $password=''){
// Validate that your email is a real one
if(filter_var($emailusername,FILTER_VALIDATE_EMAIL) !== false) {
$password = md5($password);
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql2 = "SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
$emaildb == $_SESSION['uemail'];
// this login var will use for the session thing
$_SESSION['username'] = $user_data['uemail'];
// $_SESSION['uemail'] = $user_data['uemail'];
$_SESSION['uid'] = $user_data['uid'];
$_SESSION['login'] = true;
}
else
$this->error['account'] = 'ERROR: Invalid Username/Password';
}
else
$this->error['email'] = 'ERROR: Invalid Email Address';
return (!isset($_SESSION['uemail']))? false:true;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
$login is a boolean variable, while $emailusername and $password are strings, why you compare them.