Question about proper queries - php

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'];

Related

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.

MySQL `UPDATE` statement with an `IF` condition

I'm trying to create a MySQL UPDATE statement with an IF condition.
I would like to update the user's particulars if the email and username are not duplicate or found in database.
I'm stuck with this code:
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
//Check Email in Database
$query = mysqli_query($con,"SELECT username, email from `user` where id_user = '$id'");
$result = mysqli_fetch_object($query);
if (strtolower(trim($query->email)) == strtolower(trim($em))
|| strtolower(trim($user->username)) == strtolower(trim($user))
) {
//next to condition username
} else {
$data_email = mysqli_query($con,"select email from user where em='".$em."'");
$total_email = mysqli_num_rows($data_email);
if($total_email > 0) {
echo "Email Not Available";
} else {
//next to condition username
}
}
//Check Username in Database
$data_us_user = mysqli_query($con,"select username from user where id_user='".$id."'");
$us_user = mysqli_fetch_object($data_us_user);
if (strtolower(trim($us_user->username))==strtolower(trim($user))) {
//next to query update
} else {
$data_username = mysqli_query($con,"select username from user where username='".$em."'");
$total_username = mysqli_num_rows($data_username);
if($total_username > 0) {
echo "Username Not Available";
} else {
//next to query update
}
} else {
//Finally Query Update
mysqli_query($con,"update user set username='".$user."',em='".$em."' where id_user='".$id."' ");
echo "OK";
}
The following PHP script will check for
IF the user's updated email and updated username are the same
IF the user's new email and username is already in use by another user
IF both conditions are not met, the user's details will be updated
PHP code:
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
//Getting user' details in database
$query = mysqli_query($con, "SELECT username, email from `user` where id_user = '$id'");
$result = mysqli_query($query);
//Query to find if email exists
$query2 = mysqli_query($con,"SELECT `email` from `user` WHERE em = '$em'");
$result2 = mysqli_num_rows($query2);
//Query to find if username exists
$query3 = mysqli_query($con,"SELECT `email` from `user` WHERE id_user = '$user");
$result3 = mysqli_num_rows($query3);
while ($row = mysqli_fetch_row($result)){
list($userfromdb, $emfromdb) = $row;
}
if (strtolower(trim($userfromdb)) == strtolower(trim($user))){
//will return true if user's username is the same before updating
echo 'Username cannot be the same!';
} else if(strtolower(trim($emfromdb)) == strtolower(trim($em))) {
//will return true if user's email is the same before updating
echo 'Email cannot be the same!';
} else if($result2 > 0) {
echo "Email Not Available";
} else if($result3 > 0) {
echo "Username Not Available";
} else {
//Finally Query Update
mysqli_query($con, "UPDATE `user` set username = '$user',em = '$em' WHERE id_user = '$id'");
//check if row updated successfully
$result4 = mysqli_affected_rows($con);
if ($result4 > 0) {
echo "Updated details successfully";
} else {
echo "An error occurred while updated details.";
}
}
?>
This should work, thanks!
If specifying column related message is not the concern,
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
$data_us_em = mysqli_query($con,"select count(email) as count from user where id_user='".$id."' OR em='".$em."' OR username='".$em."'");
if($data_us_em)
{
$us_em = mysqli_fetch_assoc($data_us_em);
$count=$us_em['count'];
if($count)
{
echo 'Can not update';
}else
{
mysqli_query($con,"update user set username='".$user."',em='".$em."' where id_user='".$id."' ");
echo "OK";
}
}
?>
$data_user= mysqli_query($con,"select email,username from user where id_user='".$id."'");
$userdetail = mysqli_fetch_object($data_user);
if (strtolower(trim($userdetail->email))==strtolower(trim($em)) || strtolower(trim($userdetail->username))==strtolower(trim($user)))
{
return "error message";
}else{
//your update method here
}

Insert data (only 1 time) in while loop using PHP

I have the PHP code as below:
<?php
if(isset($_POST["tbn_submit"])){
$userName = $_POST["text_username"];
$pass = $_POST["text_password"];
//$sql = "SELECT * FROM tbluser WHERE username='".$userName."' AND password='".$pass."'";
$sql = "SELECT * FROM tbluser";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res)>0){
while($row= mysql_fetch_array($res)){
$username=$row['username'];
$userpas = $row['password'];
$user_id=$row['userId'];
$user_role=$row['possition'];
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if($userName == $username && $pass == $userpas){
if($user_role=="Admin"){
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}else{
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else if($userName == $username && $pass != $userpas){
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
else if($userName != $username && $pass != $userpas){
//In this point I got insert multi time so I want it insert only 1 time to database
$query = "INSERT INTO tbluser(userId,username,password,possition,user_status) VALUES('','".$userName."','".$pass."','',1)";
$result = mysql_query($query) or die(mysql_error());
$id = mysql_insert_id();
if($result){
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
}
}else {
echo "re";
}
}
?>
This is my login page submission. When the user inputs their username and password, if the username and password are already in the database it will go to test some case like in code, but if the username is in the database but the password does not match it should display wrong password..
If the username and password don't exist in the database, the program should create username and password and go to other page. I have an error with this last case - I have inserted a lot of records in the database with the same data. I know it's because I wrote these entries in a while loop in my code but I don't know any other way of doing this. How can I populate my database with individual records and not write duplicate entries in my while loop?
All your logic is wrong:
there's no need to retrieve ALL the users to check if the user exists,
tbluser should restrict username to be UNIQUE to avoid duplicated entries,
passwords should be hashed,
the INSERT query uses unescaped variables,
inserting non matching user names will lead to have typos stored at the db,
mysql_* family of functions are deprecated
Using PDO
Login user
<?php
$dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
if (isset($_POST["login"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
$statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
$statement->bindParam(':user',$user);
$statement->execute();
/**
* Returns FALSE in case nothing is found
*/
$res = $statement->fetch(PDO::FETCH_ASSOC);
if ($res) {
$username = $res['username'];
$password = $res['password'];
$user_id = $res['userId'];
$user_role = $res['possition'];
if ($pass == $password) {
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if ($user_role == "Admin") {
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}
else {
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
}
}
Register user
<?php
$dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
if (isset($_POST["register"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
$check = $_POST["passcheck"];
$statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
$statement->bindParam(':user',$user);
$statement->execute();
/**
* Returns FALSE in case nothing is found
*/
$res = $statement->fetch(PDO::FETCH_ASSOC);
if ($res) {
echo "<span style='text-align:center;color:red;'>Username exists.</span>";
}
else if ($pass != $check) {
echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
}
else {
$statement = $dbh->prepare("INSERT INTO tbluser (userId, username, password, position, user_status) VALUES ('', :user, :pass, '' , 1)");
$statement->bindParam(':user',$user);
$statement->bindParam(':pass',$pass);
$statement->execute();
echo "<span style='text-align:center;color:red;'>Username registered.</span>";
}
}
Using mysql_query (deprecated)
To validate any user:
<?php
if (isset($_POST["login"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
/**
* This line had the right idea!
*/
$sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
$username = $row['username'];
$password = $row['password'];
$user_id = $row['userId'];
$user_role = $row['possition'];
if ($pass == $password) {
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if ($user_role == "Admin") {
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}
else {
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
}
}
To register some user:
<?php
if (isset($_POST["register"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
/**
* Ask the user to type its password twice
*/
$check = $_POST["passcheck"];
$sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
$res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
if (mysql_num_rows($res) > 0) {
echo "<span style='text-align:center;color:red;'>Username exists.</span>";
}
else if ($pass != $check) {
echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
}
else {
$query = "INSERT INTO tbluser (userId, username, password, possition, user_status) VALUES ('','".mysql_real_escape_string($user)."','".mysql_real_escape_string($pass)."','',1)";
$res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
echo "<span style='text-align:center;color:red;'>Username registered.</span>";
}
}

Referencing a SESSION() in a query

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.

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