I am still in the process of learning PHP so forgive me for the poor code.
I am attempting to get the users first name to output once they have logged in, however nothing is returning, please may I have some help.
<?php
session_start();
$DATABASE_HOST="localhost";
$DATABASE_USER="root";
$DATABASE_PWORD="";
$DATABASE_NAME="registration";
$connection=mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PWORD, $DATABASE_NAME);
if (mysqli_connect_errno()){
//if there is an issue with connecting to the database, ends code and displays the error
die("failed to connect to server: " .mysqli_connect_error()); //kills program
}
if (!isset($_POST['email'], $_POST['pswd'])){ //checking if both fields were inputted into on the form, isset()checks if data exists
//unable to get data
die("please fill in both email and password"); //kills program
}
$email = mysqli_real_escape_string($connection, $_POST['email']); //saves input as string, preventing misinterpretation
$password = mysqli_real_escape_string($connection, $_POST['pswd']);//saves input as string, preventing misinterpretation
$SQLstatement = "SELECT * FROM users WHERE email='$email' and password='$password'"; //querys the database for match
$Queryresult = mysqli_query($connection, $SQLstatement) or die(mysqli_error($connection)); //runs the query
$rowsQueryResult = mysqli_num_rows($Queryresult);//number of 'emails' in database where the emails match
$dbFirstName=$rowsQueryResult ['firstName'];
if ($rowsQueryResult==1){//if the number of emails where a match is made, is 1
echo "Welcome $dbFirstName <br/> ";
echo "successful login. <a href='accountPage.php'>Click</a> here to access the accounts page"; //successful login, links to accounts page
$_SESSION['firstName']=$dbFirstName;
}else{ //if matches are 0 or >=2
die ('unsuccessful login'); //kills program
}
?>
Thank you for your time and help
This problem can be solved by using the mysqli_fetch_assoc() function in place of mysqli_num_rows(). However, I would recommend you to use PDO since it's easier to implement and more readable.
The mysqli_num_rows() function returns the number of rows in a result set.
$rowsQueryResult = mysqli_num_rows($Queryresult);`
will give number of 'emails' in database where the emails match.
You need to use mysqli_fetch_assoc() as
$row = mysqli_fetch_assoc($Queryresult);
$dbFirstName=$row['firstName'];
Related
I am testing a login code and i ran into a problem where the information collected from a MySQL database can not be found even though the information exists inside the table, the code below says that there is 0 rows with the information i am trying to pull out, therefore it fails to execute it's primary function and always ends up executing the else solution
I have been googling around and tried different combinations and ways the code can be written as it is '".$username."' instead of '$username' but nothing seems to be working except in case where equal it to zero but that way it looses it's purpose and executes the primary function no matter what
<?php
$mysqli = new mysqli('localhost','root','password','accounts');
if (isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = '$username' AND pass = '$password' ";
$result = mysqli_query($mysqli,$sql);
if (mysqli_num_rows($result)>0){
echo "Login Success!";
exit();
}
else{
echo "Login Failed";
exit();
}
}
?>
I expected to solve this problem on my own but i got totally confused and don't even know what i have tried so far and what else is there to be tried
Note: My password is md5 protected
I'm trying to build a relatively simple PHP login script to connect to MySQL database running on my home server. I know the connection works as I've gotten some data returned as I would expect. However, I am having trouble getting the full script to work.
Essentially, I'm taking in a username/password from the user, and I first do a lookup to get the user_id from the users table. I then want to use that user_id value to do a comparison from user_pswd table (i'm storing usernames and passwords in separate database tables). At one point, I was able to echo the correct user_id based on the username input. But I haven't been able to get all the issues worked out, as I'm pretty new to PHP and don't really know where to see errors since I load this onto my server from a remote desktop. Can anyone offer some advice/corrections to my code?
The end result is I want to send the user to another page, but the echo "test" is just to see if I can get this much working. Thanks so much for the help!
<?php
ob_start();
$con = new mysqli("localhost","username","password","database");
// check connection
if (mysqli_connect_errno()) {
trigger_error('Database connection failed: ' . $con->connect_error, E_USER_ERROR);
}
$users_name = $_POST['user'];
$users_pass = $_POST['pass'];
$user_esc = $con->real_escape_string($users_name);
$pass_esc = $con->real_escape_string($users_pass);
$query1 = "SELECT user_id FROM users WHERE username = ?;";
if ($result1 = $con->prepare($query1)) {
$result1->bind_param("s",$user_esc);
$result1->execute();
$result1->bind_result($userid);
$result1->fetch();
$query2 = "SELECT user_pswd_id FROM user_pswd WHERE active = 1 AND user_id = ? AND user_pswd = ?;";
if ($result2 = $con->prepare($query2)) {
$result2->bind_param("is",$userid,$pass_esc);
$result2->execute();
$result2->bind_result($userpswd);
$result2->fetch();
echo "test", $userpswd;
$result2->free_result();
$result2->close();
} else {
echo "failed password";
}
$result1->free_result();
$result1->close();
}
$con->close();
ob_end_clean();
?>
I am a beginning php-programmer and have tried to create a registration/login system with a database. The system works at home on the latest version of phpmyadmin but my school hasn't updated it to the latest version yet (don't worry, this isn't homework). The problem I have is that at school mysql_num_rows returns 0 when I try to login but returns 1 when I try to login at home. My teacher said the version of phpmyadmin might be causing this problem. Version at school is: 4.5.2.
Here's my login.php file:
<?php
include('connect.php');
session_start();
$error = "";
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
if(empty($emailaddress) || empty($password)){
$error = "Email or password is invalid!";
echo $error;
}
else{
$queryforlogin = mysql_query("SELECT * FROM users WHERE emailaddress='$emailaddress' AND password='$password'");
$rows = mysql_num_rows($queryforlogin);
if($rows==1){
$_SESSION['login_user'] = mysql_query("SELECT firstname FROM users WHERE emailaddress='$emailaddress'");
$username = mysql_fetch_array($_SESSION['login_user']);
echo "Welcome, " . $username['firstname'] . "!";
}
else{
$error = "Email or password not found!";
echo $error;
}
mysql_close($connect);
}
?>
If I click the login button on the webpage, it gives me the error: Email or password not found! (the last else-statement). It executes the code in the file but does not execute the code under if($rows==1).
Is there anything I can do to still get this code to work?
Again, this code does work at home but not at school on an older version. I asked my teacher if he could update phpmyadmin but other classes are working with phpmyadmin right now so that cannot be done.
I hope you understand my question.
Sorry for my english, it's not my native language.
You just try once like this by passing mysql_connect connection variable in mysql_query so you can get the rows
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>
Lets get something right of the bat, PHPmyadmin has nothing to do with mysql_num_rows returning whatever it returns, PHPmyadmin is merely a tool to manage the database to which the server is linked to, everything happens on your server side.
I think you don't have the same username and password in your table at your school's database and hence the mysql_num_rows() returns 0, which is what it is supposed to do when the query does not yield any results,
OR it could be that your query returns more than 1 result, in that case the condition would fail again($rows==1).
Hello I facing a strange problem; I am using this code to check the login data with my db
include("includes/config.php");
include("includes/database.php");
$name = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM info_user WHERE user_name = '$name' AND password = '$pass'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['user_name']. " - ". $row['password'];
if (mysql_num_rows($sql)) {
echo "success";
}
else
{
echo "failed";
}
here, when i succeed it shows success but any blank input or wrong input is not showing the failed message why? and how can I solve it? is there any better way to check the login? please help
Thanks in advance
First off:
$row = mysql_fetch_array($result) or die(mysql_error());
If you pass along a wrong username or password, mysql_fetch_array() will return FALSE, because there is no rows to take from. This results in your or die(mysql_error()) part being executed, which means your script dies and outputs nothing since mysql didn't fail - which again means that mysql_error() has nothing to return to you.
Secondly, you are using mysql_num_rows() on the $sql string, not on the $result variable which actually contains a mysql resource that you should be using.
You should also check the mysql_num_rows() before using mysql_fetch_array() so that you don't try to pull out some data you don't have available.
Lastly, your solution is full of security flaws. You are passing along raw post data to your mysql database which makes you vulnerable to sql injection and you are storing your passwords as plain text values in your database (not plain text files, just plain text values).
You should google sql injection and password hashing to improve your security.
Try this:
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
echo "success";
} else {
echo "failed";
}
I am validating a form (checking if field are empty etc and at the end I am using my last validation rule:
//Database Information
//Connect to database
mysql_connect($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname)or die(mysql_error());
$email = mysql_real_escape_string($_POST['email']);
$cust_code = mysql_real_escape_string($_POST['cust_code']);
//validation e.g.
if (empty($email) + empty($cust_code) > 1){
....
//if everything is ok
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
$data = mysql_num_rows($result);
//get all fields from db and do something
}else{
//My error that is showing up
echo "<span class=\"difftext\">The customer code you have entered is not valid!
<br />
Please enter a valid Customer Code to procceed!
</span>";
Is anything wrong with that because even if I enter the correct cust_code I am getting my error msg instead of my data...
Thank you
EDIT...(I removed, as it is wrong) AND YOU DID WELL... I JUST REALISE WHAT I DID... SORRY...
I have corrected it above.
Thank you
HOW TO DEBUG
Do not put the query string immediately into the mysql method, echo it first
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
echo $sql;
$res=mysql_query($sql);
Are you even connected to the DB?
Error messages are written in English (if it is not MS error messages). Why would you ignore them? Put the error message, read it, try to understand what it says.
An advice, if you will write code that way, it is ok for very small application, for big ones, you need to take a different approach completely to code organization. Which is one of the problems/main problem frameworks are trying to solve for you.
Actually, you are wrong, your error is here, in this two lines:
$sql = mysql_query("SELECT * FROM clients WHERE ID='$cust_code'");
$result = mysql_query($sql);
You are running the query twice.
After the first time $sql holds the resource, then you refer to the resource as if it was a query string. To fix it, change it to:
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
You might have more underlying errors, but fix this one first.