Referencing a SESSION() in a query - php

I am trying to reference a variable stored in a SESSION() from a SESSION() controller and I'm having a bit of trouble with the code. What I have are two tables, one for articles and one for authors. The author id of the current user logged in is stored in my $id variable via a SQL query in access.inc.php in function databaseContainsAuthor($email, $password, &$id), then referenced in function userIsLoggedIn() and stored in $_SESSION['id']
includes>access.inc.php
<?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;
}
}
Now that I have the variable $id, which contains the current user's id, stored in $_SESSION['id'], I would like to use the SESSION() in a SQL query in my index.php to insert the author's id along with their articles in my article table so the author and the article the author submits are linked. I'm just having a bit of trouble implementing the correct code to reference $_SESSION['id'] in my SQL query for index.php
articles>index.php
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
include $_SERVER['DOCUMENT_ROOT'] .
'/includes/access.inc.php';
if (isset($_GET['add']))
if (!userIsLoggedIn())
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/login.inc.html.php';
exit();
}
else
{
$pagetitle = 'New Article';
$action = 'addform';
$text = '';
$authorid = '';
$id = '';
$button = 'Add article';
include 'form.html.php';
exit();
}
if (isset($_GET['addform']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
$text = mysqli_real_escape_string($link, $_POST['text']);
$id = $_SESSION['id'];
$sql = "INSERT INTO article SET
articletext='$text',
articledate=CURDATE(),
authorid= '$id'";
if (!mysqli_query($link, $sql))
{
$error = 'Error adding submitted article: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
$result = mysqli_query($link, 'SELECT id, articletext FROM article');
if (!$result)
{
$error = 'Error fetching articles: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$articles[] = array('id' => $row['id'], 'text' => $row['articletext']);
}
include 'articles.html.php';
?>
The SESSION() I'm trying to reference is under if (isset($_GET['addform'])), but I;m unsure if this is the rite syntax to use to do so. Any help would be greatly appreciated!

The code seems fine.Check if $id has the value you expect it to be just before the query because if it is returning zero every time your authorid must have some default value which always show up,zero in this case.

Related

Facing problem in if- else statement. It always redirect to 1st condition

Here is my PHP code. In the If-else statement when I login it always goes to the 1st php page. It does not go to the other. Suppose If I type username 'tamluk' it redirects to 'welcomemoyna.php'. I want when username match it will redirect to the definite page.
I am trying it online. 000webhost for PHP and PHPMyAdmin for the database.
<?php
session_start();
$message = "";
if (count($_POST) > 0) {
$con = mysqli_connect('localhost', 'id8401317_new', 'Deba#212', 'id8401317_abc') or die('Unable To connect');
$result = mysqli_query($con, "SELECT * FROM login WHERE username='" . $_POST["username"] . "' and password = '" . $_POST["password"] . "'");
$row = mysqli_fetch_array($result);
if (is_array($row)) {
$_SESSION["id"] = $row[id];
$_SESSION["username"] = $row[username]; {
if (isset($_POST["username"]) == 'moyna') {
header("Location:welcomemoyna.php");
} elseif (isset($_POST["username"]) == 'ramtarak') {
header("Location:welcomeramtarak.php");
} elseif (isset($_POST["username"]) == 'tamluk') {
header("Location:welcometamluk.php");
} elseif (isset($_POST["username"]) == 'bagnan') {
header("Location:welcomebagnan.php");
}
}
} else {
$message = "Invalid Username or Password!";
}
// }
}
?>
I want that when I type for 'username' like tamluk it will redirect to welcometamluk.php and so on.
your user values now in a session.try this.i hope it will help.
<?php
session_start();
$message="";
if(count($_POST)>0) {
$con = mysqli_connect('localhost','id8401317_new','Deba#212','id8401317_abc') or die('Unable To connect');
$result = mysqli_query($con,"SELECT * FROM login WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysqli_fetch_array($result);
if(is_array($row)) {
$_SESSION["id"] = $row[id];
$_SESSION["username"] = $row[username];
if (isset($_SESSION['username']['id'])) {
if($_SESSION["username"]=='moyna') {
header("Location:welcomemoyna.php");
}
elseif($_SESSION['username']=='ramtarak') {
header("Location:welcomeramtarak.php");
}
elseif($_SESSION['username']=='tamluk') {
header("Location:welcometamluk.php");
}
elseif($_SESSION['username']=='bagnan') {
header("Location:welcomebagnan.php");
}
}
else {
$message = "Invalid Username or Password!";
}
}
}
?>

about session maintaining with php

Here's my login_check php file and login_done php file.
Before I had put in my Session functions, it worked well.
but after I had inserted some Session functions, it had stopped working and keeps resulting in "invalid login" even with a VALID ID and PASSWORD.
'login_check.php'
<?php
session_start();
include_once ('../config.php');
$mysqli = new mysqli($DB['host'], $DB['id'], $DB['pw'], $DB['db']);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
extract($_POST);
$q = "SELECT * FROM ap_member WHERE id='$user_id'";
$result = $mysqli->query($q);
if($result->num_rows==1) {
$encrypted_pass = sha1($user_pass);
$row = $result->fetch_array(MYSQLI_ASSOC);
if( $row['pw'] == $encrypted_pass ) {
header("Location: http://sovereign-recipe.com/member/login_done.php");
exit();
}
else {
echo 'wrong password';
}
}
else {
echo 'ID does not exist or invalid approach. Try again.';
}
if( $row['pw'] == $encrypted_pass ) {
$_SESSION['is_logged'] = 'YES';
$_SESSION['user_id'] = $user_id;
header("Location: http://sovereign-recipe.com/member/login_done.php");
exit();
}
else {
$_SESSION['is_logged'] = 'NO';
$_SESSION['user_id'] = '';
header("Location: http://sovereign-recipe.com/member/login_done.php");
exit();
}
?>
'login_done.php'
<?php
session_start();
$is_logged = $_SESSION['is_logged'];
if($is_logged=='YES') {
$user_id = $_SESSION['user_id'];
$message = $user_id . 'login success. session would continue with your logged-in info. start your surf.';
}
else {
$message = 'your log-in is invalid. please, try again.';
}
var_dump($_SESSION);
?>
<html>
<head>
<title>login result</title>
<meta charset="utf-8" >
</head>
<body>
<?php
echo $message;
?>
</body>
</html>
Try this approach in your login_check.php
session_start();
include_once ('../config.php');
$mysqli = new mysqli($DB['host'], $DB['id'], $DB['pw'], $DB['db']);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
extract($_POST);
$q = "SELECT * FROM ap_member WHERE id='$user_id'";
$result = $mysqli->query($q);
if ($result->num_rows == 1) {
$encrypted_pass = sha1($user_pass);
$row = $result->fetch_array(MYSQLI_ASSOC);
if ($row['pw'] == $encrypted_pass) {
$_SESSION['is_logged'] = 'YES';
$_SESSION['user_id'] = $user_id;
} else {
$_SESSION['is_logged'] = 'NO';
$_SESSION['user_id'] = '';
//echo 'wrong password';
}
} else {
$_SESSION['is_logged'] = 'NO';
$_SESSION['user_id'] = '';
echo 'ID does not exist or invalid approach. Try again.';
}
//You can to use here your redirect, then remove the previous
header("Location: http://sovereign-recipe.com/member/login_done.php");
exit();
I hope this help you.

Can't fetch data from MySQL (php) (Re-edited)

I have realized why i can't actually access userdata (after i am logged) old way to find the username is $_SESSION['username']; (assuming there is a row as 'username' in MySQL database)
So as i have a test account as "good25" (reason to choose numbers was to see if Alphanumeric inputs works fine.. its just checkup by me.. nevermind)
Problem :
assuming, i have rows in a table as 'username' and all of his information.. such as 'password', 'email', 'joindate', 'type' ...
On net i found out how to snatch out username from Session
<?php session_start(); $_SESSION('username'); ?>
successful!!
i had an idea to check if session is actually registering or no??
after a log on start.php i used this code
if(isset($_SESSION['username'])) { print_r($_SESSION['username']); }
the result was "1" (while i logged in using this username "good25")
any suggestions?
index.php (lets say, index.php just holds registration + Login form + registration script.. in login form, action='condb.php')
<?php
require 'condb.php';
if (isset($_POST['btn-signup']))
{
//FetchInputs
$usern = mysqli_real_escape_string($connection,$_POST['username']);
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$repassword = mysqli_real_escape_string($connection,$_POST['repassword']);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
//SearchUser
$searchusr = "SELECT username FROM $user_table WHERE username='$usern'";
$usersearched = mysqli_query($connection, $searchusr);
$countuser = mysqli_num_rows($usersearched);
//SearchEmail
$searcheml = "SELECT email FROM $user_table WHERE email='$email'";
$emlsearched = mysqli_query($connection, $searcheml);
$counteml = mysqli_num_rows($emlsearched);
//RegisteringUser
if ($countuser == 0)
{
if ($counteml == 0)
{
$ctime = time();
$cday = date("Y-m-d",$ctime);
$aCode = uniqid();
$adduser = "INSERT INTO $user_table(username, email, password, realname, activationcode, verified, joindate, type, points) VALUES ('$usern','$email','$password','$name','$aCode','n','$cday','Free',$signPoints)";
if (mysqli_query($connection, $adduser))
{
?><script>alert('You have been registered');</script><?php
}
else {
?><script>alert('Couldnt Register, please contact Admin<br><?mysqli_error($connection);?>');</script><?php
}
} else {
?><script>alert('Email already exists!');</script><?php
}
} else {
?><script>alert('Username already exists!');</script><?php
}
}
?>
condb.php
$connection = mysqli_connect($db_server, $db_user, $db_pass);
mysqli_select_db($connection, $db_name);
if(!$connection) {
die ("Connection Failed: " . mysqli_connect_error);
}
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($connection,$_POST['uname']);
$upass = mysqli_real_escape_string($connection,$_POST['upass']);
//FindUser
$finduser = "SELECT * FROM $user_table WHERE username='$uname' AND password='$upass'";
$findinguser = mysqli_query($connection,$finduser);
$founduser = mysqli_num_rows($findinguser);
//ConfirmPassword
if ($founduser > 0)
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['username'] = true;
if ($findinguser != false)
{
while ($fetchD = mysqli_fetch_array($findinguser, MYSQLI_ASSOC))
{
$fetchD['username'] = $usernn;
$fetchD['email'] = $email;
$fetchD['userid'] = $uid;
$fetchD['realname'] = $rlnm;
$fetchD['points'] = $pts;
$fetchD['type'] = $membertype ;
}
header("Location: start.php");
} else {
echo mysqli_error();
}
} else {
header("Location: index.php");
?><script>alert('Wrong details, please fill in correct password and email');</script><?php
}
}
I am not asking you to build a script.. just little help please? (Thank you so so so so so much, as i am a self-learner, you don't have to say everything.. just a clue is enough for me)
may be you can try this code
<?php
require_once 'require.inc.php';
//session_start();
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($_POST['uname']);
$upass = mysqli_real_escape_string($_POST['upass']);
$search = mysqli_query($connection, "SELECT username, userid, password from $user_table WHERE username='$uname' AND password='$upass'");
$match = mysqli_fetch_assoc($search);
if ($match == 1 and $match['password'] == md5($upass))
{
$_SESSION['username'] = $match['userid'];
} else {
?>
<script>alert('Password or E-mail is wrong. If you havent registered, Please Register');</script>
<?php
}
}
if (isset($_SESSION['username']) or isset($match['userid'])){
header("Location:start.php");
}
if (isset($_POST['btn-signup']))
{
$name = mysqli_real_escape_string($_POST['name']);
$usern = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$repassword = mysqli_real_escape_string($_POST['repassword']);
$name = trim($name);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
$query = "SELECT email FROM $user_table WHERE email='$email'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
$querytwo = "SELECT username FROM $user_table WHERE username='$usern'";
$resulttwo = mysqli_query($connection, $querytwo);
$counttwo = mysqli_num_rows($resulttwo);
if ($count == 0 AND $counttwo == 0)
{
if ($password == $repassword) {
if (mysqli_query($connection, "INSERT INTO $user_table(username, email, password, realname) VALUES ('$usern','$email','$password','$name')"))
{
?>
<script> alert ('Successfully registered'); </script>
<?php
}
}else {
?>
<script> alert ('The Password you entered, doesnt match.. Please fill in the same password'); </script>
<?php
}
}
else {
?>
<script> alert('Username or E-mail already exist'); </script>
<?php
}
}
?>
and this is for require.inc.php
<?php
global $username;
//require 'dconn.php';
session_start();
$_SESSION["username"] = $username;
$connection = mysqli_connect("localhost","root","", "test") or die(mysqli_error());
// Check Login
if (isset($_SESSION['username']) and isset ($match['userid']))
{
$Selection = "SELECT * FROM $user_table WHERE username='$username'";
$selectQuery = mysqli_query($connection, $Selection);
if ($selectQuery != false)
{
while ($fetchD = mysqli_fetch_assoc($selectQuery))
{
$usernn = $fetchD['username'];
$email = $fetchD['email'];
$uid = $fetchD['userid'];
}
} else {
echo mysqli_error();
}
}
?>
#suggestion, create session after user login and authorized then for each page start session and take session which you created and perform SQL queries using that session variable.
for example :
$_SESSION['user_name']=$row['username'];
for each page:
session_start();
$user_name=$_SESSION['user_name'];
SQL query
mysqli_query($con,"SELECT * FROM users where column_name='$user_name'");
I think you need to include dconn.php file in all files where you want to perform the mysql operation. If you have included it only in require.inc.php then you you it in all your other files.

Question about proper queries

I have a table author with 4 columns (id, name, email, password)
CREATE TABLE author (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255),
password CHAR(32),
UNIQUE (email)
) DEFAULT CHARACTER SET utf8;
In my php, I am trying to run a query to grab the id from author then another query to insert it in table article, under authorid.
SQL :
CREATE TABLE article (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
articletext TEXT,
articledate DATE NOT NULL,
authorid INT NOT NULL
) DEFAULT CHARACTER SET utf8;
index.php :
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
include $_SERVER['DOCUMENT_ROOT'] .
'/includes/access.inc.php';
if (isset($_GET['add']))
if (!userIsLoggedIn())
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/login.inc.html.php';
exit();
}
else
{
$pagetitle = 'New Article';
$action = 'addform';
$text = '';
$authorid = '';
$id = '';
$button = 'Add article';
include 'form.html.php';
exit();
}
if (isset($_GET['addform']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
$text = mysqli_real_escape_string($link, $_POST['text']);
$authorid = mysqli_real_escape_string($link, $_SESSION['id']);
$sql = "INSERT INTO article SET
articletext='$text',
articledate=CURDATE(),
authorid= '$authorid'";
if (!mysqli_query($link, $sql))
{
$error = 'Error adding submitted article: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
$result = mysqli_query($link, 'SELECT id, articletext FROM article');
if (!$result)
{
$error = 'Error fetching articles: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$articles[] = array('id' => $row['id'], 'text' => $row['articletext']);
}
include 'articles.html.php';
?>
access.inc.php :
<?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))
{
include 'db.inc.php';
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$sql = "SELECT id FROM author
WHERE email = '{$_SESSION['email']}'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_assoc($result);
$_SESSION['id'] = $row['id'];
$_SESSION['password'] = $password;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['id']);
unset($_SESSION['password']);
$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['id']);
unset($_SESSION['password']);
header('Location: ' . $_POST['goto']);
exit();
}
session_start();
if (isset($_SESSION['loggedIn']))
{
return databaseContainsAuthor($_SESSION['email'], $_SESSION['password']);
}
}
function databaseContainsAuthor($email, $password)
{
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);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
function userHasRole($role)
{
include 'db.inc.php';
$email = mysqli_real_escape_string($link, $_SESSION['email']);
$role = mysqli_real_escape_string($link, $role);
$sql = "SELECT COUNT(*) FROM author
INNER JOIN authorrole ON author.id = authorid
INNER JOIN role ON roleid = role.id
WHERE email = '$email' AND role.id='$role'";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Error searching for author roles.';
include 'error.html.php';
exit();
}
$row = mysqli_fetch_array($result);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
?>
I left some of the code out, I can't get the authorid column in article table to return anything but 0. I am wondering if this has something to do with the fact that id column in the author table has a PRIMARY KEY attribute as well as the email column which I have set to UNIQUE. Should I be running different queries that better reference columns with PRIMARY KEY and UNIQUE attributes?
mysqli_query returns a result resource (a pointer to the result set buffer in memory).
That's what you assigned to $id.
You have to fetch the row(s) from that result, and use the desired column of each row.
$sql = "SELECT id FROM author
WHERE email = '{$_SESSION['email']}'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_assoc($result);
$_SESSION['id'] = $row['id'];

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