Display error message PHP Mysql - php

i am unable to get the last 2 echos to work, even if the update query fails it still displays success. If anyone has any suggestions on this code to be improved on any line, please do!
<?php
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;
}
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
}
?>
Thanks in advance!

mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'") or die(mysql_error()."update failed");
and use
mysql_affected_rows()
Returns the number of affected rows on success, and -1 if the last query failed.

use try catch and try to get the error enable error reporting in php also
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;}
try{
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>"; }
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
}catch(Exception $e){
print_R($e);
}
}

use or die(mysql_error()) as it will display mysql error if there is an error with your query.
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'") or die(mysql_error());

Try this:
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'");
if(!idfetch){
die(mysql_error());
}
Do the same for all other queries too.

try this, first count the row count value its great 1 then proceed the login process.
<?php
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$count= mysql_num_rows($idfetch);
if($count>0){
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;
}
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
} } ?>

Use
if(mysql_num_rows($updatequery) > 0) {
// success
} else {
// error
}
$updatequery will always be true (not NULL), until there is an error in your query

Related

If i login with a user it logs in with any password

<?php
require 'includes/common.php';
$email=$_POST['email'];
$password=$_POST['password'];
$email= mysqli_real_escape_string($con, $email);
$password= mysqli_real_escape_string($con, $password);
//md5($password);
$select_user_query="select id , email from users where email='$email' and password= $password";
//removed 'email' to email//
$select_user_result= mysqli_query($con, $select_user_query) or die (mysqli_error($con));
if (mysqli_num_rows($select_user_result==0))
{
echo 'There no such user ';
}
else
{
$row=mysqli_fetch_array($select_user_result);
$_SESSION['email']=$email;
$_SESSION['id']= $row[0];
header('location:products.php');
}
?>
here is the code
**
here i am geting
email and password from post method
From my login page
i think most of the code is right
If i login with a user it logs in with any password
**
Your error is not in the query. it is on your condition
if(mysqli_num_rows($select_user_result) == 0){
echo 'No User found';
}else{
echo 'oK';
}
You ca try this way. I think your error is you inserted the ==0 inside the mysqli_num_rows() it must be outside.
I'm assuming password is a string..
$select_user_query="select id , email from users where email='$email' and password= $password";
is what you wrote,
you've maybe forgotten to put single quotes around $password here.
Please verify this code:
I use this code for login:
if user provides the Correct Credentials-- If part will work,
if not then else part will be work
<?php
// Grab User submitted information
$user = $_POST["username"];
$pass = $_POST["password"];
//$uc_id=$_GET["user_check_id"];
// Connect to the database
$con = mysqli_connect("localhost","root","pass123");
// Make sure we connected successfully
if(! $con)
{
die('Connection Failed'.mysql_error());
}
// Select the database to use
mysqli_select_db($con, "login");
//$query ="SELECT user_check_id from loginpage where username='$user' and password='$pass'";
$query ="SELECT * from loginpage where username='$user' and password='$pass'";
//echo $query;
if ($query)
{
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
if($row["username"]==$user && $row["password"]==$pass)
{
echo "Welcome Admin";
}
else
{
echo"Please Enter the Correct Username/Password...!!";
}
}
?>
Put single quotes around $password in your query and then try.

php header not working online but working on my localhost.....why?

This works perfectly well on my localhost but when i hosted online, it does not logon and it echo logged on successful and error free. Pls what can be the cause for this?
<?php
session_start();
$_SESSION['user_logged']=$user;
$_SESSION['user_password']=$password;
$user = $_POST["username"];
$password = $_POST["password"];
include("include/connect.php");
$msg = array();
if(isset($_POST['submit'])){
foreach($_REQUEST as $key=>$val){
$$key=$val;
}
if(count($msg)==0){
$sql="SELECT username, password FROM admin WHERE username='$username' && password='$password'";
$res=mysql_query($sql) OR die(mysql_error());
if(mysql_fetch_array($res)>0){
$_SESSION['user_logged']= $user;
$_SESSION['user_password']=$password;
header("location:dashboard.php");
echo "You looged in Successfully";
} else{
$msg[]='Incorrect username/password';
}
}
}
?>
Below is the dashboard.php which its suppose to redirect to.
<?php
include('include/connect.php');
include('include/function.php');
if(isset($_REQUEST['mode']) )
{
$mode=$_REQUEST['mode'];
if($mode == 1)
{
$id=$_REQUEST['id'];
$sql="DELETE FROM enquiry WHERE id='$id'";
$result=mysql_query($sql);
}
}
$msg=array();
if(isset($_POST['submit'])){
$title=$_POST['news'];
$news_item=$_POST['news'];
if(empty($news_item)){
$msg[]='You must enter news in the column!';
}
if(empty($title)){
$msg[]='News Title must not be empty!';
}
else {
$sql = "SELECT * FROM news_file WHERE title='$title' ";
$res = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($res);
if($result > 0){
$msg[] = 'News with the same title has been added already';
} else {
$sql = "INSERT INTO news_file (title,news,date) VALUES ('$title','$news_item',Now())";
$result = mysql_query($sql);
$msg[]='News was successfully added';
}
}
}
?>
Try this.
<?php
session_start();
/*
These should be the other way round, as you are setting
the session variables with variables which have not been
initialised yet
*/
$user = $_POST["username"];
$password = $_POST["password"];
$_SESSION['user_logged']=$user;
$_SESSION['user_password']=$password;
include("include/connect.php");
$msg = array();
if(isset($_POST['submit'])){
foreach($_REQUEST as $key=>$val){
$key=$val; // Removed Erroneous double $
}
if(count($msg)==0){
$sql="SELECT
username,
password
FROM
admin
WHERE
username='$username'
AND
password='$password'";
// MySql does not accept && as a comparison operator.
$res=mysql_query($sql);
if(!$res)
{
var_dump(mysql_error());
exit;
}
else
{
if(mysql_fetch_array($res)>0)
{
$_SESSION['post'] = $_POST;
while(mysql_fetch_array($res)>0)
{
$_SESSION['user_logged']= $user;
$_SESSION['user_password']=$password;
header("location:dashboard.php");
echo "You logged in Successfully";
}
}
else
{
msg[]='Incorrect username/password';
}
}
?>
Looking at the code you have provided for dashboard.php, you are expecting there to be $_POST data, for a page which you have redirected to. Where you have redirected to the page, there will be no $_POST data for you to retrieve from the server.
I have amended my script above, to store the $_POST data in the session, so using that, you should be able to call your news items by calling $_SESSION['post']['news'], or if this is too long winded, simply re-assign the POST data once inside your dashboard.php script like so.
$post = $_SESSION['post'];
Then you can call it by using $post['news'].

PHP: else condition is not working in php

I have designed a admin login page. The if condition is working but else condition is not. After putting wrong username or password it shows blank on the same page.
if(isset($_POST['submit']))
{
$userid = $_POST['userid'];
$pass= $_POST['pass'];
$sql = mysqli_query($DBCONNECT, "SELECT * FROM admin WHERE userid='$userid' and pass='$pass'") or die(mysql_error());
//$count=mysql_fetch_array($sql);
$count = mysqli_num_rows($sql) or die(mysql_error());
if($count == 1)
{
$_SESSION['userid'] = $userid;//$_POST['userid'];
echo "hiii";
//header("Location:add_menu.php");
}
else
{
echo "Wrong Username or Password";
}
}
You used mysql_error(); which is causing the error of blank page.
Use the below code will fix your problem.
$sql = mysqli_query($DBCONNECT,$query);
$count = mysqli_num_rows($sql);
Remove or die(mysqli_error($link)) from your code that will work fine for you.
Note: mysqli_num_rows can be used for Procedural style only not for object oriented style.
Can you try with this code? Difference is putting if($count) instead of if($count==1)
if(isset($_POST['submit']))
{
$userid = $_POST['userid'];
$pass= $_POST['pass'];
$sql = mysqli_query($DBCONNECT, "SELECT * FROM admin WHERE userid='$userid' and pass='$pass'") or die(mysql_error());
//$count=mysql_fetch_array($sql);
$count = mysqli_num_rows($sql) or die(mysql_error());
if($count)
{
$_SESSION['userid'] = $userid;//$_POST['userid'];
echo "hiii";
//header("Location:add_menu.php");
}
else
{
echo "Wrong Username or Password";
}
}
Mysqli Also make result as object so you can do this :
$sql = mysqli_query($con, "SELECT * FROM users WHERE userid='$userid' and pass='$pass'") or die(mysqli_error());
your mysqli_error only will show if statement wrong and i don't think you will put wrong statement but good in development.
then you can check if statement works by if and put this :
echo $sql->num_rows;
can put in variable :
$count = mysqli_num_rows($sql) to $count = $sql->num_rows
or
if($sql->num_rows == 0) {
// here your blank result for error
} else {
// show result here.
}
Link : Check PHP Site Mysqli Num Rows Result

PHP Session not holding values

After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;

Storing multiple variables in a single $_SESSION(PHP)

How would I make this work, I asked before and didn't get a correct answer. This code is the user login, so when they log in I want username and avatar to be trackable through out the site. So far I just have username. I have tried methods and have failed every time.
$username = $_POST['username'];
$password = sha1($_POST['password']);
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count=mysqli_num_rows($result);
if ($count == 1)
{
$row = mysqli_fetch_array($result);
while ($_SESSION['username'] = $row['username'])
{
session_start();
header('Location: index.php');
}
}
else
{
echo 'Invalid Logins';
}
mysqli_close($conn);
?>
Supposing you have avatar stored in the avatar field in the database:
if ($count == 1)
{
session_start();
$row = mysqli_fetch_array($result);
$_SESSION['username'] = $row['username'];
$_SESSION['avatar'] = $row['avatar'];
header('Location: index.php');
}
else
{
echo 'Invalid Logins';
}

Categories