I have made a database with columns Email, FirstName, LastName, Password.. etc
My login page uses email and password for logging in
I want to retrieve the name typed in LastName column in the same row as Email
I would like to know how to do so
My code looks like this:-
$query=mysql_query("SELECT * FROM Users WHERE email='$email' AND
`password`='$encrypted_pass' ");
After this, I want to be able to assign a variable to the LastName so I could create a session along with login
Then you specify the column in the column list:
SELECT LastName
FROM Users
WHERE email = '$email'
...
You then need fetch the result set to assign it to a variable.
mysql_ functions are officially deprecated and no longer maintained/safe to use.
You should use PHP's PDO instead as it is a safer and more object-oriented approach.
Just fill in DB_NAME, DB_USER_NAME, and DB_USER_PASS with your specific credentials and this code should work for you.
$database = new PDO( 'mysql:host=localhost;dbname=DB_NAME;charset=UTF-8', 'DB_USER_NAME', 'DB_USER_PASS' );
$query = $database->prepare( "SELECT * FROM Users WHERE `email` = ? AND `password` = ? " );
$query->bindValue( 1, $email );
$query->bindValue( 2, $encrypted_pass );
$query->execute();
if( $query->rowCount() > 0 ) { # If rows are found for query
$result = $query->fetch( PDO::FETCH_ASSOC );
echo $result[ 'LastName' ]; # <-- The LastName field you were looking for!
}
else { echo "No Rows Returned!"; }
For more information of PHP PDO, please see http://www.php.net/manual/en/book.pdo.php
I think this covers everything you asked for. Starts a session, checks if it is good, setup a couple of variables for our post data, do some data validation, setup the query, query the db, check results, set var lastname in session.
<?php
header('Content-type: text/html');
session_start();
if (session_id() === '') {
echo 'session_id is null!';
exit;
}
$myemail = null;
$mypassword = null;
if (isset($_POST['Submit']) == true) {
//assuming you have a db connection
//mysql_connect($host, $user, $password) || die(mysql_error());
//mysql_select_db($database) || die(mysql_error());
if ((isset($_POST["username"]) === false)||
(isset($_POST["password"]) === false)) {
echo 'Please fill in all fields';
exit;
} else {
// get the post data
$myemail = ($_POST["username"]);
$mypassword = ($_POST["password"]);
}
// check the form in database
$sql = "SELECT * FROM Users WHERE email = '".$myemail."'
AND password = '".$mypassword."'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$_SESSION['loggedin'] = false;
if ($count === 1) {
$userrecord = mysql_fetch_array($result);
$_SESSION['username'] = $userrecord['username'];
$_SESSION['password'] = $userrecord['password'];
$_SESSION['loggedin'] = true;
$_SESSION['lastname'] = $userrecord['lastname'];
// assign last name to a session var
echo 'You have been logged in successfully";
} else {
echo 'Wrong username or password';
exit;
}
} else {
echo "No form post detected.<br><br>";
}
?>
Here's some basic stuff using Mysqli since mysql_ commands are deprecated. Again, it uses some common names so adjust accordingly.
/********************************/
// using mysqli (untested but should work)
/********************************/
$mysqli = new mysqli("localhost", "dbuser", "dbpassword", "default_dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// ecsape the query params
$myemail = $mysqli->real_escape_string($myemail);
$mypassword = $mysqli->real_escape_string($mypassword);
if ($mysqli->query("SELECT * FROM Users WHERE email = '$myemail'
AND password = '$mypassword'")) {
printf("%d Rows returned.\n", $mysqli->affected_rows);
// here is where you can set the $_SESSION vars
// and do any other work you want to do on login.
}
$mysqli->close();
/********************************/
//end mysqli
/********************************/
One last thing. Get yourself a GitHub.com repository setup so you can easily rollback to a prior version. It really is a must have IMO.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I dont really know whats really happening but I cant login even I enter the right UserID and Password it still doesnt make me go to my home page. I dont really know what are the error becasue it doesnt show up it just say "incorrect Credentials". am I missing something?
here is my code:
<?php
include "includes/config.php";
session_start();
if (isset($_POST['loginbutton'])) {
$username = mysqli_real_escape_string($con, $_POST['user']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql_query = "SELECT * FROM tbl_useraccounts WHERE employee_id = '$username' AND password ='$password' LIMIT 1";
$result = mysqli_query($con, $sql_query);
$row = mysqli_fetch_array($result);
$passwordhashed = password_verify($password, $row['password']);
if ($passwordhashed) {
if ($_SESSION['usertype'] == 'Admin') {
$_SESSION['username'] = $username;
echo "<script>alert('Successfully logged in!');</script>";
header('location: HomeForAdmin.php');
die();
} elseif ($_SESSION['usertype'] == 'SuperAdmin') {
$_SESSION['username'] = $username;
echo "<script>alert('Successfully logged in!');</script>";
header('location: HomeForSuperAdmin.php');
die();
} else {
echo "<script>alert('Incorrect username and password!');document.location='login2.php'</script>";
}
} else {
echo "<script>alert('Incorrect credentials!');document.location='login2.php'</script>";
}
$_SESSION['username'] = $row['employee_id'];
$_SESSION['password'] = $row['password'];
$_SESSION['usertype'] = $row['usertype'];
$_SESSION['first_name'] = $row['FirstName'];
$_SESSION['last_name'] = $row['LastName'];
}
Prepared statements
Prepared statements are used to protect SQL queries against malicious/malformed user input.
The general layout of a prepared statement is as follows:
PDO
// Define database connection parameters
$db_host = "127.0.0.1";
$db_name = "name_of_database";
$db_user = "user_name";
$db_pass = "user_password";
// Create a connection to the MySQL database using PDO
$pdo = new pdo(
"mysql:host={$db_host};dbname={$db_name}",
$db_user,
$db_pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
]
);
// The SQL query using ? as a place holder for the variable we want to insert
$sql = "SELECT column_1, column_2, column_3 FROM table WHERE column_x = ?";
// Prepare the query structure
$query = $pdo->prepare($sql);
// Run the query binding $variable to the ?
// i.e. the query becomes:
// SELECT * FROM table WHERE column = "$variable"
$query->execute([$variable]);
// Fetch the first/next row into the $result variable
$result = $query->fetch(PDO::FETCH_ASSOC); // Access like: $result["column_1"];
// Other way to fetch data...
# $result = $query->fetch(PDO::FETCH_NUM); // Access like: $result[0];
# $result = $query->fetchAll(); // Access likeL $result[0]["column_1"];
# $result = $query->fetchObject(); // Access like: $result->column_1;
mysqli
// Define database connection parameters
$db_host = "127.0.0.1";
$db_name = "name_of_database";
$db_user = "user_name";
$db_pass = "user_password";
// Make connection to the database
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
// The SQL query using ? as a place holder for the variable we want to insert
$sql = "SELECT column_1, column_2, column_3 FROM table WHERE column_x = ?";
// Prepare the query structure
$query = $mysqli->prepare($sql);
// Bind the STRING $variable to the ? placeholder in the SQL
$query->bind_param("s", $variable);
// Run the query
$query->execute();
// Store the result
$query->store_result();
// Bind the returned values
$query->bind_result($column_1, $column_2, $column_3);
// Fetch the first/next row
$query->fetch();
//Access as a standard PHP variable...
echo $column_1;
PHP redirects
Using redirects like the following won't work because you can't output data to the page (echo) and then cause a redirect.
echo "<script>alert('Successfully logged in!');</script>";
header('location: HomeForSuperAdmin.php');
Session ifs
The following checks to see if the value in $_SESSION["usertype"] is set to Admin or SuperAdmin.
if ($_SESSION['usertype'] == 'Admin'){
// Additional code...
}
elseif ($_SESSION['usertype'] == 'SuperAdmin'){
// Additional code...
}
The issue here is that as we are only now logging in there shouldn't be a value in that variable!
There would only be a value there if the user was already logged on. In your code it should actually be written as:
if ($row['usertype'] == 'Admin'){
// Additional code...
}
elseif ($row['usertype'] == 'SuperAdmin'){
// Additional code...
}
LIMIT in your SQL
You don't need to use limit in your SQL query for two reasons:
The username field should be unique (i.e. there is only one corresponding row)
You're not accessing the row in a loop you are only taking the first row. So even if there was multiple rows returned you'd only see one.
Flow
Bear in mind that, for the most part, we don't want to have a dozen nested if statements in our programs it makes it complicated to follow and is harder to debug, maintain, etc.
if(expression a){
if(expression b){
if(expression c){
// Some extra random code...
if(expression d){
// Some code to work with...
}
else{
// Some code...
}
}
else{
// Some code...
}
}
else{
// Some code...
}
}
else{
// Some code...
}
Instead, if we streamline the code so that it runs from top to bottom then it tends to be easier to follow:
if(expression a){
// Do something...
}
if(expression b){
// Do something else...
}
Obviously this isn't always possible - sometimes it makes more sense to nest(!) - but going too many levels with if statements can be very tricky to work with.
In your case though you're using if statements to check specific conditions have been met and if they haven't then the code should stop executing and display an error or redirect...
if(username and password have not been entered){
echo "ERROR: Username and Password are empty";
exit;
}
// If the user didn't input values then we would never get this far...
if(user doesn't exist in database){
echo "ERROR: Username doesn't exist!";
exit;
}
// If the user doesn't exist in the database then we never get this far...
if(password matches){
echo "Success! The user is logged on.";
}
Adjusted code
include "includes/config.php";
session_start();
// Check to see if the user is already logged on. If they are then
// we want to redirect them to an error page.
if(isset($_SESSION["username"])){
header("location:errorpage.php?error_code=1");
exit;
}
// Assign POST variables to PHP variables. If the POST variables
// don't exist (haven't been submitted) then set the value to NULL
// so that we can use it in the IF statement easily.
$username = $_POST['user'] ?? NULL;
$password = $_POST['password'] ?? NULL;
// Check to make sure that the user has entered something into the
// username and password fields. If they haven't then we're going
// to handle them with a redirect.
if(!$username || !$password){
header("location:errorpage.php?error_code=2");
exit;
}
$user_sql = "
SELECT password, usertype, FirstName, LastName
FROM tbl_useraccounts
WHERE employee_id = ?
";
$user_query = $pdo->prepare($user_sql);
$user_query->execute([$username]);
// Get the user from the database. If the username doesn't exist then
// redirect the user to approriate error page.
if( !($user = $user_query->fetchObject() ){
header("location:errorpage.php?error_code=3");
exit;
}
// If the user does exist then we verify the password supplied by the user
// against the one stored in the database. If it doesn't match then we'll
// redirect them to an approriate error page.
if(!password_verify($password, $user->password)){
header("location:errorpage.php?error_code=4");
exit;
}
// Set the usertype and username to the sesson SUPER GLOBAL.
// You don't need to set all of the variables (name etc.)
// if you need them get them from the database at the time!
$_SESSION["usertype"] = $user->usertype;
$_SESSION["username"] = $username;
//Redirect the user to the appropriate admin page
$usertype_redirect_locations = [
"Admin" => "adminpage.php",
"SuperAdmin" => "superadminpage.php"
];
header("location:{$usertype_redirect_locations[$user->usertype]}");
I am pretty new to php but have a pretty basic understanding of it. I have just figured out how to create a session. Once a customer finishes an order I am trying to get basic information of the order into the "order table" of database for that specific logged in username. I have 2 tables in this database.
Customers: which has 4 columns. id | username | password | url
Orders: has 4 columns. id | address | user_id | cost |
How to I write a query that gets the logged in users ID from "customers" and INSERTS that id along with the session variables into the "orders" table? Hopefully someone can help!
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_query($con,"INSERT INTO orders (address, user_id) VALUES $name WHERE id = " .
$_SESSION['username']['id']);
mysqli_close($con);
?>
After trying to figure it out from tutorials and such this is the best I could come up with but I couldn't find anything that showed how to grab the id from the logged in user and insert into another table along with session variable data. Please help?
EDIT
Not sure if this is the start of the problem but I need to know how to start a session defining what the logged in users id is in the first place. Is there a way to define the id into the existing session after login is validated? Here is the login script.
<?php
//Start session
session_start();
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
// Connects to your Database
mysql_connect("localhost", "xxx", "xxx") or
die(mysql_error());
//Select database
$db = mysql_select_db("mydatabase");
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$login = clean($_POST['login']);
$password = clean($_POST['password']);
//Input Validations
if($login == '') {
$errmsg_arr[] = 'Login ID missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
//If there are input validations, redirect back to the login form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: login-form.php");
exit();
}
//Create query
$qry="SELECT * FROM customers WHERE login='$login' AND password='".($_POST['password'])."'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) == 1) {
$_SESSION['login'] = $_POST['login'];
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_ID'] = $member['id'];
$_SESSION['SESS_login'] = $member['login'];
$_SESSION['SESS_password'] = $member['password'];
session_write_close();
header("location: fullreport100_member_checkout.php");
exit();
}else {
//Login failed
header("location: login-failed.php");
exit();
}
}else {
die("Query failed");
}
?>
Correct syntax for INSERT:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Therefor when you insert, you need to you need to do something like this:
$address = 'address 1';
$user_id = 5;
mysqli_query($con,"INSERT INTO orders (address, user_id) VALUES ('". $address . "', " . $user_id . ")");
I am also not use if this is correct syntax (I never used it) : $_SESSION['username']['id'] (I assume this is multi-dim array in session)
If you have classed defined, you need to use $_SESSION['username']->id
If i enter wrong password it shows 'Wrong username or Password' but if enter wrong username and correct password it shows nothing. Why ? what should i change in the code?
<?php
$name = $_POST['username'];
$password=$_POST['pwd'];
$dbc = mysql_connect('localhost', 'username', 'password') or die();
mysql_select_db("dbname") or die();
$result = mysql_query("SELECT * FROM table WHERE uname='$name'") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
if($row['uname']==$name && $row['pword']==$password)
{
echo 'Successfully logged in <br />';
break;
}
else
{
echo 'Wrong username or password';
}
}
mysql_close($dbc);
?>
Because if you enter the wrong username the query returns nothing.
Then you don't get into the while loop.
You could change the query :
$result = mysql_query("SELECT * FROM table WHERE uname='".addslashes($name)."' and pword='".addslashes($password)."'");
Then use mysql_fetch_row() only once (remove your while loop).
EDIT
<?php
function hash_password($password){
$myVerySecretSalt = "pREkeSw2"; //don't use this string, create your own random one!
return md5($myVerySecretSalt.$password.$myVerySecretSalt);
}
$name = $_POST['username'];
$password = hash_password($_POST['pwd']);
$dbc = mysqli_connect('localhost', 'username', 'password') or die();
mysqli_select_db("dbname") or die();
$mysql_result = mysqli_query("SELECT * FROM table WHERE uname='".addslashes($name)."' and pword='".$password."'");
$result = mysqli_fetch_row($mysql_result);
mysqli_close($dbc);
if(!$result){
echo "Wrong username or password.";
}else{
var_dump($result);
echo "Successfully logged in.";
}
?>
EDITED for usage of MySQLi as mysql is deprecated since PHP 5.5
EDITED as for plaintext passwords.
It's never a very good thing to store passwords in plaintext in the database as they can be stolen in case of sql injection.
A way to protect your users password is to hash them, below is a basic implementation :
First create a function to hash a password :
function hash_password($password){
$myVerySecretSalt = "pREkeSw2"; //don't use this string, create your own random one!
return md5($myVerySecretSalt.$password.$myVerySecretSalt);
}
Then replace your third line $password = $_POST['pwd']; with this one : $password = hash_password($_POST['pwd']);
Here you go! (Just remember to use that same function on the password when you create the user account)
This should work correctly:
<?php
$name = $_POST['username'];
$password=$_POST['pwd'];
$dbc = mysql_connect('localhost', 'username', 'password') or die();
mysql_select_db("dbname") or die();
$result = mysql_query("SELECT * FROM table WHERE uname='$name'") or die(mysql_error());
$row= mysql_fetch_array($result)
if($row && $row['uname']==$name && $row['pword']==$password)
{
echo 'Successfully logged in <br />';
break;
}
else
{
echo 'Wrong username or password';
}
mysql_close($dbc);
?>
your previous code didn't show anything becasue row = mysql_fetch_array($result) were not finding any record, and so returning immediately false (and exied the while)
Seems like you enter a username that does not exist in that table.
Remove your while loop. Just say:
$result = mysql_fetch_assoc(mysql_query("SELECT * FROM table WHERE uname = '".mysql_real_escape_string($name)."' AND pword = '".mysql_real_escape_string($password)."'"));
if ($result) {
// Successfully logged in
} else {
// Login failed
}
Keep in mind that the mysql_real_escape_string is very important when accepting user input to avoid SQL injection.
Since you are authenticating a user, record must be unique.
Thus, you shouldn't be looping through anything:
Get rid of the loop and change your conditions
$row = mysql_fetch_array($result);
if($row['uname']==$name && $result){
if($row['pword']==$password){
echo 'Successfully logged in <br />';
}else{
echo 'Wrong Password';
}
}else{
echo 'No record found';
}
mysql_close($dbc);
I refactored your code for this one. I recommend use mysql_fecth_row instead mysql_fetch_array beacause you need just one row.
<?php
// get, validate and clean your input variables
$name = isset($_POST['username']) ? addslashes($_POST['username']) : '';
$password =isset($_POST['pwd']) ? addslashes($_POST['pwd']) : '';
// make your data base connection
$dbc = mysql_connect('localhost', 'root', '') or die();
mysql_select_db("test_mysql") or die();
// building the sql query and getting the result (remember filter by username and password)
$result = mysql_query("SELECT * FROM tb_usuario WHERE uname = '$name' AND pword = '$password'") or die(mysql_error());
// using mysql_fetch_row (remember that just one user must match in the data base if not something is wrong in register ...)
$row = mysql_fetch_row($result);
// remember 0 => id, 1 => uname, 2 => pword
if (is_array($row)) {
echo "Welcome {$row[1]}";
} else {
echo 'Wrong username or password';
}
// close your connection
mysql_close($dbc);
I am trying to make this script work as follows...
After a user is logged in they go to the following link index.php?id=1 (userid)
but i have tried many methods here is the following code
<?php
// Include required MySQL configuration file and functions
require_once('config.inc.php');
require_once('functions.inc.php');
// Start session
session_start();
$_SESSION['user_id']= $id;
// Check if user is already logged in
if ($_SESSION['logged_in'] == true) {
// If user is already logged in, redirect to main page
redirect('../index.php');
} else {
// Make sure that user submitted a username/password and username only consists of alphanumeric chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
(!ctype_alnum($_POST['username'])) ) {
redirect('../login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if (mysqli_connect_errno()) {
printf("Unable to connect to database: %s", mysqli_connect_error());
exit();
}
// Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// Construct SQL statement for query & execute
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// Set session variable for login status to true
$_SESSION['logged_in'] = true;
redirect('../index.php?id=' . $_SESSION['user_id']);
} else {
// If number of rows returned is not one, redirect back to login screen
redirect('../login.php');
}
}
?>
this isn't a live project or never will be its for my learning curve only.
the current code goes to the following link index.php?id=
Updated code after CD001's answer
<?php
// Include required MySQL configuration file and functions
require_once('config.inc.php');
require_once('functions.inc.php');
// Start session
session_start();
// Check if user is already logged in
if ($_SESSION['logged_in'] == true) {
// If user is already logged in, redirect to main page
redirect('../index.php');
} else {
// Make sure that user submitted a username/password and username only consists of alphanumeric chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
(!ctype_alnum($_POST['username'])) ) {
redirect('../login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if (mysqli_connect_errno()) {
printf("Unable to connect to database: %s", mysqli_connect_error());
exit();
}
// Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// Construct SQL statement for query & execute
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
$iUserId = null;
$oUser = $result->fetch_object();
//there's only 1 record but what the hey
while($oUser = $result->fetch_object()) {
$iUserId = (int) $oUser->id; // assuming the field in the user table is called `id`
}
// Set session variable for login status to true
if(!is_null($iUserId)) {
$_SESSION['logged_in'] = true;
redirect('../index.php?id=' . $iUserId);
}
//error trapping
} else {
// If number of rows returned is not one, redirect back to login screen
redirect('../login.php');
}
}
?>
when i try to login it gives me a error
\includes\login.inc.php on line 10
line 10 is this
if ($_SESSION['logged_in'] == true) {
You've got:
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// Set session variable for login status to true
$_SESSION['logged_in'] = true;
redirect('../index.php?id=' . $_SESSION['user_id']);
}
But at the top of the document you're defining:
$_SESSION['user_id']= $id;
However, $id is not actually defined at that point in time unless it's included in one of the required files at the top of the document (which I think unlikely).
You should be retrieving the user id from your database result object ($result).
Something like:
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
$iUserId = null;
$oUser = $result->fetch_object();
//there's only 1 record but what the hey
while($oUser = $result->fetch_object()) {
$iUserId = (int) $oUser->id; // assuming the field in the user table is called `id`
}
// Set session variable for login status to true
if(!is_null($iUserId)) {
$_SESSION['logged_in'] = true;
redirect('../index.php?id=' . $iUserId);
}
//error trapping
else {
//throw an Exception or something to trap the invalid user id
}
}
For the mysqli_result object, see:
http://www.php.net/manual/en/class.mysqli-result.php
Especially the methods:
http://www.php.net/manual/en/mysqli-result.fetch-assoc.php
http://www.php.net/manual/en/mysqli-result.fetch-object.php
The mysqli_result object essentially holds the whole resultset, you need to loop through it to get the individual records - though you've as you've only got 1 record you could use:
$result->data_seek(0);
$oUser = $result->fetch_object();
$iUserId = (int) $oUser->id; //assuming the user id field is called 'id'
As an aside: it's arguably better practice to just have the SQL query match on the username though and retrieve the id and password - and then evaluate the password in the application rather than the database; it further reduces the chance of injection attacks working and means you can better encrypt your password with a hashing and salting object in the application.
If no text has been written on the page with ECHO php function, then try :
header("Location: http://www.google.ca");
And you have to replace the url by whatever you need.
I'm new to PHP and programming in general, but am working on doing a login. I've got the signup page completed, and my database populates the records fine. However, when this code gets output it says I have 0 rows from the mysql_num_rows($result);... when, it should be coming back successfully showing 1 row when I input the correct username/password. Whether I put in a successful user/pass combo or not, it outputs the same.
I appreciate any help you can provide, code is listed below:
$SQL = "SELECT * FROM account WHERE username = $username AND password = md5($password)";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
echo $result;
echo $num_rows;
// CLOSE CONNECTION
mysql_close($db_handle);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $num_rows;
EDIT: Complete rewrite
Try this:
<?php
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$username = 'jack'; /* Insert $_Post [''] here with username variable you pass. You could sanitize and validate with for example filter_var (), clean (), etc */
$password_user = 'password from jack'; // same here.
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE{
$query = "SELECT * FROM account WHERE username ='$username' AND password = md5('$password_user')";
$result = mysqli_query($link, $query);
$num_rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($row) {
session_start();
$_SESSION['login'] = "1"; // pleae not that 1 is converted into a string value
$_SESSION['username'] = $username; // added username, just to test.
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $error_message;
}
// CLOSE CONNECTION
mysqli_close($link);
}
?>
Sample data:
CREATE TABLE account (
id INT auto_increment primary key,
username VARCHAR(30),
password VARCHAR(50)
);
INSERT INTO account(username, password)
VALUES
("bob", md5('password from bob')),
("jack", md5('password from jack')),
('joe', md5('password from joe'));
SQL FIDDLE DEMO
Sample page1
<?php
session_start();
$login = $_SESSION['login'];
$username = $_SESSION['username'];
echo '<h1>It WORKS, <i>'.$username.'</i>!!!</h1>';
?>
Important to note is that I have used the MYSQLI library instead of the MYSQL library. If you have more than one column in you table you should select your output per column. For example, $result['id'].
I found that you didn't escape variable in and out in you SQL statement. I have to note that I didn't debug the part below COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS. I think you can manage that on your own.
W.R.T. the santization and validation you have to do some more work. I don't know how you data is past via the user login in form. Let say you will use POST. In that case you can start at the top of you page with first retrieving all the posted variable using $_POST. Then filter them to make sure you code in is not open for SQL injection. E.g. $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);