I'm sorry if this has been asked, but I have no idea what to search for to find an answer.
I'm just starting to learn PHP and am doing a simple tutorial where I'm "logging into" a data base (just checking to see if the email and password match what is stored no actual session is being created).
I have this code:
<?php
include("connectToDb.php");
$loginEmail = $_POST['loginEmail'];
$loginPassword = $_POST['loginPassword'];
$query = mysqli_query($dbc, "SELECT * FROM users WHERE email='$loginEmail'");
$numrows = mysqli_num_rows($query);
if($numrows != 0)
{
while($row = mysqli_fetch_array($query))
{
$dbemail = $row['email'];
$dbpassword = $row['password'];
$dbfirstname = $row['firstName'];
}
if($loginEmail == $dbemail)
{
if ($loginPassword == $dbpassword)
{
echo "Hi ".$row['firstName'].", you are now logged in.";
}
else
{
echo "login failed.";
}
}
}
mysqli_close($dbc);
?>
But the $row['firstName'] in the echo statement prints as a blank string: "Hi , you are now logged in.". If I use the exact same code but repalce $row['firstName'] with $dbfirstname in the echo statement, I get a properly formatted message "Hi Jason, you are now logged in.".
Those two variables are supposed to be the same... why does one work while the other does not?
Check the control flow:
You have the while loop while($row = mysqli_fetch_array($query)) - so you assign a new value to $row and test it. If it evaluates to false (i.e. no more rows), you break the loop.
This implies, that after the loop $row no longer has valid content. Your stored values (e.g. $dbfirstname) are from the previous iteration of the loop and thus contain valid data.
Related
Hi i have an slight problem i'm trying top geht tow Results of My pdo query and Print Them but No such luck i've probably just Made a Stupid mistake i'm Not seeing The query seems to be finde so it does make a difference if the name is in the database (and it makes a difference if you put it in quotes) probably the variables are getting a null value or something...
$username="xxx";
$firstname="xxx";
$check=0;
if (isset($_GET['u'])){
$username=strip_tags(#$_GET['u']);
if (ctype_alnum($username)){
$check=$stmt=$link->prepare("SELECT * FROM
users WHERE username = ?");
$stmt->execute(array($username));
$check=$stmt->fetchAll();
if(count($check)==1){
$get=$stmt->fetch(PDO::FETCH_BOTH);
echo "$get";
$username =$get["username"];
$firstname = $get["first_name"];
}else{
echo "<h2> User does not exist!</h2>";
exit();
}
}
}
?>
<h2>Profilepage for: <?php echo "$username"; ?></h2>
<h2>First name: <?php echo "$firstname"; ?></h2
$stmt->fetchAll() is fetching all the results of the query. Once this is done, there are no more results available for $stmt->fetch() to fetch. You should get the data from the $check array.
if (count($check) == 1) {
$get = $check[0];
$username = $get["username"];
$firstname = $get["first_name"];
} else {
echo "<h2> Username does not exist </h2>";
exit();
}
Or you could just replace the fetchAll with fetch.
$stmt->execute(array($username));
$get = $stmt->fetch(PDO::FETCH_ASSOC);
if ($get) {
$username = $get["username"];
$firstname = $get["first_name"];
} else {
echo "<h2> Username does not exist </h2>";
exit();
}
Also, echo "$get" makes no sense. $get is an array, you can't echo it, you need to use print_r($get) or var_dump($get).
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
I am new to php trying to learn something.I'm trying to write a script which allow users to reset password after they verify their personal info. Everything is working good except this php script. This script receives data from form input fields. The program was supposed to output:
echo $e.'&u='. $us .'&er='.$err.'&o='. $bulls3 .'&r='.$bulls4;
exit();
which can be sent to ajax as respondText.
The problem is this php script is not working as expected and giving me following error msg. Is there anyone who can help me out. Any help will be very much appreciated. Thank you in advance for help..
Error Output Message:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\myGenius\identityverify.php on line 119
contact
<?php
// AJAX CALLS THIS CODE TO EXECUTE
if(isset($_POST["bd"])){
$bad= preg_replace('#[^0-9-]#i', '', $_POST['bd']);
//Connect to database
include_once("php_includes/connect_to_mysqli.php");
$e = mysqli_real_escape_string($db_conx,$_POST['e']);
$c= preg_replace('#[^a-z ]#i', '', $_POST['c']);
$post= preg_replace('#[^a-z0-9]#i', '', $_POST['pst']);
$user= preg_replace('#[^a-z0-9]#i', '', $_POST['us']);
$odd= preg_replace('#[^a-z0-9]#i', '', $_POST['od']);
if($e =="" || $bad =="" || $c=="" ||$post==""){
echo "empty";
exit();
}else if($user=="" || $odd==""){
echo "no_exist";
exit();
}else{
$sql = "SELECT id, username FROM user WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$u = $row["username"];
//Encrypted values to check with user input passed from hidden fields
//Check codes
$bull= value1;
$bull2= value2;
$bull3= value3;
$bull3=value4;
$us= value5;
$err= value6;
}
if($user==$us && $odd==$err){
$sql = "SELECT country, birthday, postal FROM useroptions WHERE email='$e' AND username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$con = $row["country"];
$bday = $row["birthday"];
$poost = $row["postal"];
}
if($c == $con && $bad == $bday && $post==$poost){
// encoded value using some type of encryption for passing data to another web page based on user information data
$bulls= value1;
$bulls2= value2;
$bulls1=value3;
$bulls3= value4;
$bulls4= value5;
$bulls3=value6;
$bulls4=value7;
echo $e.'&u='. $us .'&er='.$err.'&o='. $bulls3 .'&r='.$bulls4;
exit();
}else{
echo "wrong";
exit();
}
}else {
echo "contact";
exit();
}//user option not set
}else{
echo "no_exist";
exit();
}//end code comparison and send to error page
}else{
echo "no_exist";
exit();
}
exit();
}}
?>
I always use two queries rather than making a server return everything that matches
select count(*) from database where condition='expected';
Perform a second query based on an if() clause validating the initial result.
This affords a precaution against injection since my main query hasn't been executed.
Try replacing
if(isset($_POST["bd"])){
With
if(!empty($_POST["bd"])){
I have a html page with the form log-in with username and password. When people enter the correct password, it will take them to the php page with their bills. If the password is incorrect, it will display the error message and then exit the program. I got the log-in function to work. However, it's also effecting my other program. Now every time i try to write something in the item/amount row, it also display the error message and exit the program. I know it has something to do with the $numresult>0 condition. When i took that condition out, my amount/item rows work, but the log-in page also allow blank entry in username/password to log in. Any idea how i can make sure that people have to enter the correct password (not a blank entries) to log in, at the same time, get my item/amount rows in the second page behave as normal? My codes are below. Sorry it's a little long.
</head>
<body style="font-family: Arial, Helvetica, sans-serif; color: black;" onload=>
<h1>My Bills</h1>
<form method=post>
<?php
//*************************************************
//Connect to Database
//*************************************************
//*************************************************
//Verify password and username
//*************************************************
$password = $_POST['password']; //retrieve variables for password and userId
$userid = $_POST['userid'];
$query = "SELECT * FROM valid_logon WHERE userid = '$userid' AND
password='$password'"; //get query from database
$result = mysql_query($query);
$numresults = mysql_num_rows($result); //get row number
$row = mysql_fetch_array($result); //get array into variable
$dbuserid = $row['userid'];
$dbpassword = $row['password'];
if ($numresults>0)
{
if ($userid == $dbuserid && $password == $dbpassword)
{
process();
}
}else{
err_msg();
}
//*************************************************
//Error message.
//*************************************************
function err_msg()
{
print "The username and/or password you have entered are invalid.";
print "</body>";
print"</html>";
exit;
}
//*************************************************
//Write out records with data if they exist.
//*************************************************
function process()
{
print "<table>";
print "<tr><th>Item</th><th>Amount</th></tr>";
$action = $_POST['action'];
if ($action == 'update')
{
$write_ctr = 1;
// Delete all rows in the table
$query = "DELETE FROM n1417_expenses ";
$result = mysql_query($query);
if (mysql_error()) {
echo("<br>MySQL Error - Cannot delete from table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
// Loop through table and insert values into the database
while (true)
{
$item_name = 'item'."$write_ctr";
$item_value = $_POST[$item_name];
$amount_name = 'amount'."$write_ctr";
$amount_value = $_POST[$amount_name];
if (empty($item_value))
{
break;
}
// Insert an item to the table
if(!is_numeric($amount_value))
{
print "<font color=red>I'm sorry, amount \"".$amount_value."\" is not a valid number.</font><br>\n";
}else{
$query = "INSERT INTO n1417_expenses (item, amount)
VALUES('".$item_value."','".$amount_value."') ";
$result = mysql_query($query);
}
if (mysql_error())
{
echo("<br>MySQL Error - Cannot insert a row into table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
$write_ctr++;
}
}
//*************************************************
//Now Select from table and Display
//*************************************************
$err_cnt = 0;
$read_ctr = 1;
$query = "SELECT item, amount FROM n1417_expenses ";
$result = mysql_query($query);
if (mysql_error()) {
echo("<br>MySQL Error- Cannot select from table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
if (!empty($result))
{
$rowresults = mysql_num_rows($result);
if ($rowresults > 0)
{
for ($read_ctr=1; $read_ctr<=$rowresults; $read_ctr++)
{
$row = mysql_fetch_array($result);
$item_value = $row['item'];
$item_name = 'item'."$read_ctr";
$amount_value = $row['amount'];
$amount_name = 'amount'."$read_ctr";
print "<tr>";
print "<td><input type=text name=$item_name value='$item_value'></td>\n";
print "<td><input type=text name=$amount_name value='$amount_value'></td>\n";
print "<td>";
print "</tr>";
$total_amt = $total_amt + $amount_value;
}
}
}
//*************************************************
//Now write the blank lines
//*************************************************
for ($i = $read_ctr; $i < $read_ctr + 2; $i++)
{
$item_name = 'item'."$i";
$amount_name = 'amount'."$i";
print '<tr>';
print "<td><input type=text name=$item_name value=''></td>\n";
print "<td><input type=text name=$amount_name value=''></td>\n";
print '</tr>';
}
print "</table>";
print "<br>Total Bills: $total_amt";
}
?>
<br><input type=submit value=Submit>
<br<br>
<!-- Hidden Action Field -->
<input type=hidden name=action value=update>
</form>
To answer the question posted, your problem appears to be that the username and password being are checked again when your user submits the form. Because the fields don't exist, the query finds zero rows, triggering your error message.
There are a number of ways of fixing your problem, one way would be to use a Session to remember that a user is logged in. This could be implemented by altering your password check as follows:
session_start();
if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in'])
{
$password = $_POST['password']; //retrieve variables for password and userId
$userid = $_POST['userid'];
$query = "SELECT * FROM valid_logon WHERE userid = '".mysql_real_escape_string($userid)."' AND
password='".mysql_real_escape_string($password)."'"; //get query from database
$result = mysql_query($query);
$numresults = mysql_num_rows($result); //get row number
$row = mysql_fetch_array($result); //get array into variable
$dbuserid = $row['userid'];
$dbpassword = $row['password'];
if ($numresults>0)
{
if ($userid == $dbuserid && $password == $dbpassword)
{
$_SESSION['logged_in'] = TRUE;
process();
}
}else{
err_msg();
}
}
I've kept the code as similar to the original as possible, but I will echo the comments above on the need to secure your SQL calls. Have a look at using PDO if possible, or at the very least start using mysql_real_escape_string as above.
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.
I am trying to check if the session username matches the record in my database and if it does, I want to include a file.
This is my code
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT * FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez)
{
include('check.php');
}
else
{
echo "error";
}
?>
The session username does not match the record in my database, yet the file is being included. Why?
OH, I FOUND THE ISSUE. IT IS CONSIDERING MY USERNAME TO BE ROOT...BUT WHEN I SAY ECHO $_SESSION['USERNAME'] IT IS CRAIG#CRAIG.COM..WHY SO>
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT sessionusername FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez["sessionusername"]==$username)
{
include('check.php');
}
else
{
echo "error";
}
?>
You are simply testing whether the array $geez is empty or not. If the array has anything in it, you if($geez) will return true. To stop this behaviour, please see ceteras' answer, particularly this part:
if($geez["sessionusername"]==$username)
{
include('check.php');
}
I believe that's the only part that has changed.
Thanks,
James