Cannot validate right? Why? New to PDO - php

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.

Related

How to make Login in UWP using PHP and MYSQL

I want to make login and registration in my UWP app using PHP and MySQL
I use this code below to do it but it didn't work
I try many ways in internet but its so old
I make PHP and MySQL Database in a localhost xampp
I'm beginner in PHP so pleas anyone tell me the error in my code
I use this code to POST data to serve in UWP :
private async void Button_Click(object sender, RoutedEventArgs e)
{
Uri requestUri = new Uri("http://localhost/test/index.php");
HttpStringContent stringContent = new HttpStringContent
(" { \"email\": \"" + emailbox.Text + "\" , \"password\":\"" + passwordbox.Text + "\" } "
, Windows.Storage.Streams.UnicodeEncoding.Utf8
, "application/json");
//Dictionary<string, string> pairs = new Dictionary<string, string>();
//pairs.Add("email", emailbox.Text);
//pairs.Add("password", passwordbox.Text);
//HttpFormUrlEncodedContent encodedContent = new HttpFormUrlEncodedContent(pairs);
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient();
await client.PostAsync(requestUri, stringContent);
}
And This is my PHP backend code
config.php
<?php
define("DB_HOST","127.0.0.1");
define("DB_USER","root");
define("DB_PASSWORD","");
define("DB_NAME","firstdb");
?>
db_connect.php
<?php
include_once 'config.php';
class DbConnect{
private $connect;
public function __construct(){
$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($this->connect)){
echo "Unable to connect to MySQL Database: " . mysqli_connect_error();
}
}
public function getDb(){
return $this->connect;
}
}
?>
user.php
<?php
include_once 'db_connect.php';
class User{
private $db;
private $db_table = "users";
public function __construct(){
$this->db = new DbConnect();
}
public function isLoginExist($email, $password){
$query = "select * from ".$this->db_table." where email = '$email' AND password = '$password' Limit 1";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
mysqli_close($this->db->getDb());
return false;
}
public function isEmailUsernameExist($email){
$query = "select * from ".$this->db_table." where email = '$email'";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
return false;
}
public function isValidEmail($email){
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
public function createNewRegisterUser( $email, $password){
$isExisting = $this->isEmailUsernameExist($email);
if($isExisting){
$json['success'] = 0;
$json['message'] = "Error in registering. Probably the username/email already exists";
}
else{
$isValid = $this->isValidEmail($email);
if($isValid)
{
$query = "insert into ".$this->db_table." (email, password) values ('$email','$password')";
$inserted = mysqli_query($this->db->getDb(), $query);
if($inserted == 1){
$json['success'] = 1;
$json['message'] = "Successfully registered the user";
}else{
$json['success'] = 0;
$json['message'] = "Error in registering. Probably the username/email already exists";
}
mysqli_close($this->db->getDb());
}
else{
$json['success'] = 0;
$json['message'] = "Error in registering. Email Address is not valid";
}
}
return $json;
}
public function loginUsers($email, $password){
$json = array();
$canUserLogin = $this->isLoginExist($email, $password);
if($canUserLogin){
$json['success'] = 1;
$json['message'] = "Successfully logged in";
}else{
$json['success'] = 0;
$json['message'] = "Incorrect details";
}
return $json;
}
}
?>
index.php
<?php
require_once 'user.php';
$username = "";
$password = "";
$email = "";
if(isset($_POST['email'] && isset($_POST['password']))){
$email = $_POST['email'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
$userObject = new User();
// Registration
if(!empty($password) && !empty($email)){
$hashed_password = md5($password);
$json_registration = $userObject->createNewRegisterUser($email, $hashed_password);
echo json_encode($json_registration);
}
// Login
if(!empty($password) && empty($email)){
$hashed_password = md5($password);
$json_array = $userObject->loginUsers($email, $hashed_password);
echo json_encode($json_array);
}
?>
I would recommend you to use a Password Entry instead of a visible entry in your app like a PasswordBox. Try to make your request like that.
var loginUrl = "http://localhost/test/index.php";
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{ { "username", emailbox.Text }, { "password", passwordbox.Text } };
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(loginUrl, content);
string result = await response.Content.ReadAsStringAsync();
}

destroying session if not set using php pdo

I have this old code that see if session is not registered to destroy it and go back to login page:
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
//if(!session_is_registered(myusername)){
//header("location:index.html");
if(isset($_SESSION['username'])) {
echo "Page seen by " . $_SESSION['username']."<br>";
$con=mysqli_connect($host,$username,$password,$db_name);
mysqli_set_charset($con, 'utf8mb4');
}
else{
session_destroy();
header("location: index.php");
}
?>
I am trying to convert this code to pdo but I can't know how to destroy the session in this method. I just stopped after writing those lines:
<?php
session_start();
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "";
try
{
$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Plus, In the following code, always when I click on login it will take me to the next page even if the username and password are incorrect:
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "";
$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username != '' && $password!=''){
try{
session_start();
$sql = "SELECT * FROM login WHERE username = :u AND password = :p LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindValue(":u", $username);
$stmt->bindValue(":p", $password);
$exec = $stmt->execute();
$count = $stmt->fetch(PDO::FETCH_ASSOC);
if((count($count)==1)){//&& password_verify($password, $count['password']
$_SESSION['username'] = $username;
header("Location: ./pages/home.php");
}
else {
header("Location: index.php");
}
}
catch(PDOException $e) {
$sql_fail = "INSERT INTO login_attempts(username, password, date_now, time_now)
VALUES (:uf, :pf, :date, now())";
$stmt_fail = $conn->prepare($sql_fail);
$stmt_fail->bindValue(":uf", $username);
$stmt_fail->bindValue(":pf", $password);
$stmt_fail->bindValue(":date", date("y-m-d"));
$exec_fail = $stmt_fail->execute();
header("Location: index.php");
echo $e->getMessage();
}
}
}
?>
I think the key to your login is that you need some little self-contained applications (functions) to break down simple tasks. See if this works better:
/classes/class.PDOConn.php
<?php
class PDOConn
{
// Create a singleton variable to store persistent connection
private static $singleton;
// Set your database credentials here
public static function connect($DB_host = "localhost",$DB_user = "root",$DB_pass = "",$DB_name = "")
{
// first check if the connection has been already set
if(empty(self::$singleton)) {
try {
$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
self::$singleton = $conn;
return self::$singleton;
}
catch (PDOException $e) {
die("connection failed");
}
}
// Return the current connection
return self::$singleton;
}
}
/functions/function.query.php
<?php
// This function will make automatic queries to your database
// It accepts a bind array as a second parameter
function query($sql = false,$bind = false)
{
// Create connection
$conn = PDOConn::connect();
// Two ways to query, with and without a bind array
if(!empty($bind) && is_array($bind)) {
$query = $conn->prepare($sql);
$query->execute($bind);
}
else {
$query = $conn->query($sql);
}
// Loop through returned values
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
// Send back array OR send back 0 (for zero results)
return (!empty($result))? $result : 0;
}
/functions/function.write.php
<?php
// This function is the same as query(), just no return array
function write($sql = false,$bind = false)
{
$conn = PDOConn::connect();
if(!empty($bind) && is_array($bind)) {
$query = $conn->prepare($sql);
$query->execute($bind);
}
else {
$conn->query($sql);
}
}
/functions/function.check_user.php
<?php
// This will check the user.
// Do not store plain text passwords
// Instead use password_hash() and password_verify()
function check_user($username,$password)
{
$query = query("SELECT * FROM `login` WHERE `username` = :u LIMIT 1",array(":u"=>$username));
if($query == 0)
return false;
return ($query[0]['password'] == $password);
}
/functions/function.AutoloadFunction.php
<?php
// This is just an autoloader for your functions
// I use it to help cut down on bulk loading of functions
function AutoloadFunction($function = false)
{
// If input is not array, just stop
if(!is_array($function))
return false;
// Set the load folder as this folder
// (all functions should be in the same folder)
$function_dir = __DIR__.'/function.';
// Loop through the array and add the function(s)
for($i = 0; $i < count($functions); $i++) {
// Function name
$addfunction = $functions[$i];
// See if function exists
if(!function_exists($addfunction)) {
$dir = $function_dir.$addfunction.'.php';
if(is_file($dir)) {
include_once($dir);
}
}
}
}
login.php
<?php
// Session start regardless
session_start();
// Check if login attempted
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
// If user or pass is empty OR there is already a session, just stop
// You may want to do a redirect here, not sure....
if(empty($username) || empty($password) || !empty($_SESSION['username']))
return false;
// Include the autoloader function
include_once(__DIR__.'/functions/function.AutoloadFunction.php');
// Maybe look into using spl_autoload_register() to autoload classes
include_once(__DIR__.'/classes/class.PDOConn.php');
// Autoload functions
AutoloadFunction(array("check_user","write","query"));
// Verify with handy-dandy function
if(check_user($username,$password)) {
$_SESSION['username'] = $username;
$location = "./pages/home.php";
}
// Write the attempt
else {
write("INSERT INTO `login_attempts` (`username`, `password`, `date_now`, `time_now`) VALUES (:uf, :pf, :date, NOW())",array(":uf"=>$username,":pf"=>$password,":date"=>date("y-m-d")));
$location = "index.php?errror=invalid";
}
// Forward
header("Location: {$location}");
exit;
}
Use the code in this link here.
You should use fetch(PDO::FETCH_NUM) so your code will be something like this:
$result = $conn->prepare("SELECT * FROM users WHERE username= :hjhjhjh AND password= :asas");
$result->bindParam(':hjhjhjh', $user);
$result->bindParam(':asas', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($rows > 0) {
header("location: home.php");
}
else{
$errmsg_arr[] = 'Username and Password are not found';
$errflag = true;
}
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: index.php");
exit();
}

Php Login Script - Security Review and Suggestions

I write a simple php login class that only operate on php sessions to login user in the system.
My Question is that this class is secure enough to be used on production environment ?
class.login.inc.php
class Login
{
//setSessionFunction sets a login session with user id and all user details array
private function setSession($user_id,$user_details)
{
$_SESSION['user_id'] = $user_id;
$_SESSION['user_details'] = $user_details;
$_SESSION['key'] = $this->hashSession();
}
//GetIp function is used to get ip address of client
private function hashSession()
{
return sha1($_SERVER['HTTP_USER_AGENT'] . getIP());
}
//get sessions and verify them
public function getSession(){
if(isset($_SESSION['user_id']) && ($_SESSION['user_id']!== '') )
if($this->verifySessionUser($_SESSION['user_id']) === true )
if($this->hashSession() == $_SESSION['key'])
return true;
else
return false;
}
//Logout Function
public function logout(){
$_SESSION['user_id'] = null;
$_SESSION['key'] = null;
$_SESSION = array();
session_unset();
session_destroy();
}
public function verifyUser($username,$password){
$password = sha1($password);
$conn = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(!$conn) die("Connection Error To DATABASE" . mysqli_connect_errno());
$sql = "SELECT * FROM user WHERE username = ?";
$mysqli = $conn->prepare($sql);
if(!$conn) die("Query Error To DATABASE In Class Session" . mysqli_errno($conn));
$mysqli->bind_param("s",$username);
$mysqli->execute();
$result = $mysqli->get_result();
$mysqli->close();
$conn->close();
if($result->num_rows > 0)
{
$r = $result->fetch_assoc();
if($r['password'] === $password)
{
$this->setSession($r['user_id'],$r);
return true;
}else return false;
}
else
return false;
return false;
}
//Private DataBase Verification of User Credentials
private function verifySessionUser($user_id){
$conn = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(!$conn) die("Connection Error To DATABASE" . mysqli_errno());
$sql = "SELECT * FROM user WHERE user_id = ?";
$mysqli = $conn->prepare($sql);
if(!$conn) die("Query Error To DATABASE In Class Session" . mysqli_errno());
$mysqli->bind_param("d",$user_id);
$mysqli->execute();
$result = $mysqli->get_result();
$mysqli->close();
$conn->close();
if($result->num_rows > 0)
{
return true;
}
else
return false;
}
}
securepage.php
$user = new Session();
if($user->getSession() == true)
{
header("location: admin.php");
exit();
}
Is there any security measures i should consider in future ?

Fatal error: Call to undefined method User->get_fullname()

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.

Undefined variable?

I'm getting an undefined variable error for $id variable in lines 15 & 21, could someone please explain why? I can't see what the problem is.
<?php
function userIsLoggedIn()
{
if (isset($_POST['action']) and $_POST['action'] == 'login')
{
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$password = md5($_POST['password'] . 'chainfire db');
if (databaseContainsAuthor($_POST['email'], $password, $id))
{
include 'db.inc.php';
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
$_SESSION['id'] = $id;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['id']);
$GLOBALS['loginError'] = 'The specified email address or password was incorrect.';
return FALSE;
}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout')
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['id']);
header('Location: ' . $_POST['goto']);
exit();
}
session_start();
if (isset($_SESSION['loggedIn']))
{
return databaseContainsAuthor($_SESSION['email'], $_SESSION['password'], $_SESSION['id']);
}
}
function databaseContainsAuthor($email, $password, $id)
{
include 'db.inc.php';
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
$sql = "SELECT COUNT(*) FROM author
WHERE email='$email' AND password='$password'";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Error searching for author.';
include 'error.html.php';
exit();
}
$row = mysqli_fetch_array($result);
$sql = "SELECT id FROM author
WHERE email='$email'";
$id = mysqli_query($link, $sql);
if (!$id)
{
$error = 'Error searching for id.';
include 'error.html.php';
exit();
}
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
The variable $id is defined in databaseContainsAuthor($email, $password, $id), then stored in the $_SESSION['id'] session so naturally $id = mysqli_query($link, $sql); should have passed but it's not?
Variables changed (or defined) inside a function will not affect the rest of the script. For example:
<?php
function changeVariabe($person) {
$person = 'Bob';
}
$person = 'Alice';
changeVariable($person);
echo "Hello $person!"; // Outputs: Hello Alice!
This can be avoided by passing the variable by reference, like this:
<?php
function changeVariabe(&$person) {
$person = 'Bob';
}
$person = 'Alice';
changeVariable($person);
echo "Hello $person!"; // Outputs: Hello Bob!
You can also use global variables, like this:
<?php
function changeVariabe() {
global $person;
$person = 'Bob';
}
$person = 'Alice';
changeVariable();
echo "Hello $person!"; // Outputs: Hello Bob!
a few things
the variable $id should be defined (not required but good practice) before you use it
so for example
$id = NULL;
if (databaseContainsAuthor($_POST['email'], $password, $id))
also setting the $id inside the databaseContainsAuthor function doesn't mean that $id will change outside the scope of that function.
You could make it global but that is considered bad practice
also your function databaseContainsAuthor
contains this code
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
which will return TRUE or FALSE. but note that once the code returns a value, none of the code after it will be run
which means this part might as well be commented out, as it is after the return statement it will never be run
$sql = "SELECT id FROM author
WHERE email='$email'";
$id = mysqli_query($link, $sql);
if (!$id)
{
$error = 'Error searching for id.';
include 'error.html.php';
exit();
}

Categories