I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";
Related
I am developing a website for testing with logging page with different access levels for users, the site is connected with MySQL db which have 3 columns
user | password | level(1/2)
code is filter out the particular entry from db but it didn't redirected to particular page. i tested with echo but at the $count it shows 0 . please help me to sort this out, I am going to use mysqli instead at the launching phase.
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$username = $_POST['username'];
$password = $_POST['password'];
$conn = mysql_connect('localhost','root','');
$db = mysql_select_db('udb',$conn);
$sql = "SELECT * FROM logins WHERE user ='".$username."' AND password = '".$password."'";
$result = mysql_query($sql,$conn);
echo $result;
$count = mysql_num_rows($result);
if ($count==1) {
$_SESSION['login_user']=$username;
while ($row = mysql_fetch_array($result)){
if ($row['level'] == '2') {
header("home2.php");
} else {
header("home1.php");
}
}
}
Your echo $result; will prevent any further redirect down in the code. It is due to the fact that redirects are managed using headers... but since you output some data ... headers can not be managed.
no need to give connection variable in mysql_query() and in header function u forgot to pass location
$sql = "SELECT * FROM logins WHERE user ='".$username."' AND password = '".$password."'";
$result = mysql_query($sql);
//echo $result;
$count = mysql_num_rows($result);
if ($count==1) {
$_SESSION['login_user']=$username;
while ($row = mysql_fetch_array($result))
{
if ($row['level'] == '2')
{
header("location:home2.php");
} else {
header("location:home1.php");
}
}
}
You need to use location if you want your redirects to work.
if ($row['level'] == '2') {
header("location: home2.php");
} else {
header("location: home1.php");
}
Your script is at risk for SQL Injection.
If you can, you should stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO, it's really not hard.
Finally, you should use the proper methods to hash passwords with PHP. The way that you're handling login is extremely insecure.
Place the user and password into back ticks (apostrophe marks on the left of key 1)
I'm currently struggling with a page that allows a user to complete one of two options. They can either update an existing item in the SQL database or they can delete it. When the customer deletes an option everything runs perfectly well, however whenever a customer updated an item it displays the Query failed statement from the delete function before applying the update.
It seems obvious to me that the problem must be in my IF statement and that the DeleteButton function isn't exiting if the $deleteno variable isn't set. Any help would be appreciated. Excuse the horribly messy code PHP isn't a language I am familiar with. (I have not included the connect information for privacy reasons)
function DeleteButton(){
#mysqli_select_db($con , $sql_db);
//Checks if connection is successful
if(!$con){
echo"<p>Database connection failure</p>";
} else {
if(isset($_POST["deleteID"])) {
$deleteno = $_POST["deleteID"];
}
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
$result = #mysqli_query($con,$sql);
if((!$result)) {
echo "<p>Query failed please enter a valid ID </p>";
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
}
}
}
That is the code for the delete button and the following code is for the UpdateButton minus the connection information (which works fine).
if(isset($_POST["updateID"])) {
$updateno = $_POST["updateID"];
}
if(isset($_POST["updatestatus"])) {
if($_POST["updatestatus"] == "Fulfilled") {
$updatestatus = "Fulfilled";
} elseif ($_POST["updatestatus"] == "Paid") {
$updatestatus = "Paid";
}
}
if(isset($updateno) && isset($updatestatus)) {
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result) {
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
Once again these are incomplete functions as I have omitted the connection sections.
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
Are you sure you want to execute that block if $deleteno is NOT set?
P.S. You shouldn't rely on $_POST['deleteId'] being a number. Please read about SQL injections, how to avoid them and also about using prepared statements.
I've update your code, but you need to write cleaner code ( spaces, indents, etc ) this won't only help you to learn but to find your errors easily.
<?php
function DeleteButton()
{
#mysqli_select_db($con , $sql_db);
/*
Checks if connection is successful
*/
if(!$con){
echo"<p>Database connection failure</p>";
} else {
/*
Check if $_POST["deleteID"] exists, is not empty and it is numeric.
*/
if(isset($_POST["deleteID"]) && ! empty($_POST["deleteID"]) && ctype_digit(empty($_POST["deleteID"]))
$deleteno = $_POST["deleteID"];
$sql = "delete from orders where orderID='$deleteno'";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID </p>"
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
} else {
echo "<p>Please enter a valid ID </p>" ;
}
}
}
/*
Part 2:
===========================================================================
Check if $_POST["updateID"] exists, is not empty and it is numeric.
Check if $_POST["updatestatus"] exists, is not empty and equal to Paid or Fullfilled
*/
if( isset($_POST["updateID"]) &&
! empty($_POST["updateID"]) &&
ctype_digit(empty($_POST["updateID"]) &&
isset($_POST["updatestatus"]) &&
! empty($_POST["updatestatus"]) &&
( $_POST["updatestatus"] == "Fulfilled" || $_POST["updatestatus"] == "Paid" ) )
{
$updateno = $_POST["updateID"];
$updatestatus = $_POST["updatestatus"];
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
There is an error in MySQL Syntax
$sql = "delete from orders where orderID = $deleteno;";
$deleteno after orderID must be inside single quotes.
change it to this $sql = "delete from orders where orderID = '$deleteno';";
So, I have this:
$user = $db->prepare("SELECT * FROM `users` WHERE LL_IP='" . $_SERVER['REMOTE_ADDR'] . "'");
$user->execute();
while($userDATA = $user->fetch(PDO::FETCH_ASSOC)) {
if( userDATA['LL_IP'] == $_SERVER['REMOTE_ADDR']) {
echo "Logged in";
}
else {
echo "Register / Login";
}
}
I'm trying to get it where if no $userDATA['LL_IP'] is found. Then it does the else statement, but for some reason it's not working.
I've also tried:
elseif($userDATA['LL_IP'] == false) {
echo "Register / Login";
}
But that doesn't work either.
If you just want to check if a row was found, you can replace the loop with an if statement:
if($userDATA = $user->fetch(PDO::FETCH_ASSOC))
{
echo "Logged in";
}
else
{
echo "Register / Login";
}
Your logic is faulty. You already query only for cases where LL_IP equals $_SERVER['REMOTE_ADDR']. Why would expect to EVER gat a result turned where your if conditional wouldn't match.
It seems to me that all you would need to do in this case is to check to see if the number of records returned in the result set is greater than 1.
By the way, you should at least escape $_SERVER['REMOTE_ADDR'] before using it in a query, or better yet, since you are already using a prepared statement, you could use a parametrized value.
Your logic should be something like this:
// specify maybe a primary key field in query. No need for SELECT *
$query = "SELECT COUNT(user_id) FROM `users` WHERE LL_IP = :ip_address LIMIT 1";
$user->prepare($query);
$user->bindParam(':ip_address', $_SERvER['REMOTE_ADDR'], PDO::PARAM_STR]);
$user->execute();
if('1' === $user->fetchColumn(0)) {
// logged in
} else {
// not logged in
}
I also agree with comment from #jeroen above that you really shouldn't rely on an IP address to determine any sort of login status. IP addresses can change unpredictably (particularly for mobile users).
$user = $db->prepare("SELECT * FROM `users` WHERE LL_IP='" . $_SERVER['REMOTE_ADDR'] . "'");
$user->execute();
if ($user->fetchColumn() > 0) {
// logged in
} else {
// not logged in
}
The manual (see example #2) says to use fetchColumn
Here it's I have a problem with my PHP Code + Oracle Login form.
In this PHP file, I make login function. But I have an error like this :
Warning: oci_num_rows() expects parameter 1 to be resource, string given in C:\xampp\htdocs\developers\it\session.php on line 12
Wrong
-
<?php
session_start();
include ("config.php");
$username = $_POST['username'];
$password = $_POST['password'];
$do = $_GET['do'];
if($do=="login")
{
$cek = "SELECT PASSWORD, USER_LEVEL FROM T_USERS WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = oci_parse($conn, $cek);
oci_execute($result);
if(oci_num_rows($cek)==1)
{
$c = oci_fetch_array($result);
$_SESSION['username'] = $c['username']; ociresult($c,"USERNAME");
$_SESSION['USER_LEVEL'] = $c['USER_LEVEL']; ociresult($c,"USER_LEVEL");
if($c['USER_LEVEL']=="ADMINISTRATOR")
{
header("location:supervisor.php");
}
else if($c['user_level']=="User")
{
header("location:user.php");
}
else if($c['user_level']=="Root")
{
header("location:administrator.php");
}
else if($c['user_level']=="Manager")
{
header("location:manager.php");
}
else if($c['user_level']=="Admin")
{
header("location:admin.php");
}
else if($c['user_level']=="Director")
{
header("location:director.php");
}
}
else
{
echo "Wrong";
}
}
?>
I have tried to search in google, but still don't find anything.
Someone knows, what's the problem ?
Thanks for advance.
According to your script instead of
if(oci_num_rows($cek)==1)
you should call
if(oci_num_rows($result)==1)
You probably want to use $result and not $cek when you're asking for the number of rows returned from oci_num_rows(). However, you really want to avoid using $username and $password directly in the string like that. It'll make you wide open for SQL injection attacks, so look into using oci_parse together with oci_bind_by_name.
After that you should also always call exit() after the sequence of redirects, as the script will continue running if you don't (and that might be a security issue other places).
I also got the same case, so I tricked it with a script like this, but I don't know whether there was an impact or not. because the session and validation went smoothly.
$username =$_POST['username'];
$password = $_POST['password'];
$conn = oci_connect('xxx', 'xxx', 'localhost/MYDB');
$pass_encription = md5($password);
$query = "SELECT * from *table_name* WHERE *field1*='".$username."' and *field2*='".$password."'";
$result = oci_parse($conn, $query);
oci_execute($result);
$exe = oci_fetch($result);
if ($exe > 0)
{
oci_close($conn);
oci_execute($result);
$row =oci_fetch_array($result);
$sid = $row['field_1_parameter'];
$snama = $row['field_2_parameter'];
$sjab = $row['field_3_parameter'];
$session = array (
'field_1_array' =>$sid,
'field_2_array' =>$snama,
'field_3_array' =>$sjab
);
if($sjab == 'Administrator')
{
$this->session->set_userdata($session);
redirect('redirecting_page');
}
`
I'm trying to retrieve the access level (admin/member/guest) for the currently logged in user and depending on this, show them specific content on my page. I'm trying to test this with echos right now but still cannot get anything to print out. Could anyone give any advice?
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' ";
$result = mysql_query($q, $con);
if($result == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($result == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($result == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result is a mysql resource. you need
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
$access = $row['access'];
if($access == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($access == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($access == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result as returned by mysql_query is not a string that you can compare against; it is a resource. You need to fetch the row from $result:
$row = mysql_fetch_assoc($result)
$access = $row['access'];
if($access == 'guest') {
...
}
...
A few other issues:
You have a possible SQL-injection issue in your query. You should never directly insert the values of variables into your SQL queries without properly escaping them first. You might want to use mysql_real_escape_string.
The mysql is being deprecated. You should try to use mysqli (MySQL Improved) or PDO (PHP Data Objects).
I see two issues:
1. You need to use session_start(); at the beginning. otherwise your if statement will not be executed.
2. mysql_query($q, $con) does not return a string. it returns a record set. You need to use mysql_fetch_assoc($result); which return associative array.And from the array you retrieve your desired value by:
$assoc_arr = mysql_fetch_assoc($result);
$access = $assoc_arr['access'];
now you can compare $access.