Having trouble retrieving values from MySQL database - php

I'm very new to using MySql and am having trouble retrieving values from my database. I was under the impression that i was going about it the correct way but my echo statements don't print anything.
I'd appreciate some help. My code is below. I know i'll have to add security later on like sanitizing user input.
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$hashedPass = sha1($password);
if ((!isset($email)) || (!isset($password))) {
//Visitor needs to enter a name and password
echo "Data not provided";
} else {
echo "Received details $email and $password <br/>";
// connect to mysql
$mysql = mysqli_connect("localhost", "root", "root");
if(!$mysql) {
echo "Cannot connect to PHPMyAdmin.";
exit;
} else {
echo "Connected to phpmyadmin <br/>";
}
}
// select the appropriate database
$selected = mysqli_select_db($mysql, "languageapp");
if(!$selected) {
echo "Cannot select database.";
exit;
} else {
echo "DB Selected";
}
// query the database to see if there is a record which matches
$query = "select count(*) from user where email = '".$email."' and password = '".$hashedPass."'";
$result = mysqli_query($mysql, $query);
if(!$result) {
echo "Cannot run query.";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
$userdata = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $userdata[3];
echo $userdata['firstName'];
if ($count > 0) {
echo "<h1>Login successful!</h1>";
echo "<p>Welcome.</p>";
echo "<p>This page is only visible when the correct details are provided.</p>";
} else {
// visitor's name and password combination are not correct
echo "<h1>Login unsuccessful!</h1>";
echo "<p>You are not authorized to access this system.</p>";
}
?>

I believe the problem is that you call twice the *fetch* family function which will cause the $userdata to be empty.
From the documentation mysql_fetch_row will fetch the next row and move the internal data pointer ahead. So when you call mysqli_fetch_array($result, MYSQLI_BOTH) and I suppose the user/password is unique there is nothing to retrieve. Also another mistake you did is that your SELECT doesn't retrieve the actual user data, but just the count number for the user/password combination. So your userdata will be always incorrect, even if you fetch the data right.
So change your query to something like that:
$query = "select * from user where email = '".$email."' and password = '".$hashedPass."' LIMIT 1";
Then use mysql_fetch_array to check if the entry exist and then retrieve the user data.

Related

MySQL select doesn't select

I have been through quite some different codes on this site. To find what wrong with my code. Basically I just want to search in a table and test the result. I wrote something like this:
<?php
ob_start();
session_start();
$conn = new mysqli('localhost','username','password','mytable');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$valuetotest = 'something';
$result = mysql_query("SELECT id FROM members WHERE UserName = $valuetotest");
if(mysql_num_rows($result) == 0)
{
echo "User not found";
}
$password = 'something2';
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
if($password != $userData['Password'])
{
echo "Password not found";
}else{ // Redirect to home page after successful login.
header('Location: welcome.php');
}
?>
And I get always the message :
"User not found." and "password not found."
when I know the username and password are in the table...
No I'm quite knew with PHP/MySQL so there might be something quite big right in front of my face and I can't see it!!!!
Can somebody help please. Thanx.
Takes less than a second to spot. (If you had error reporting on it would take even less than that)
1) Your connection is mysqli but your query call is mysql
$result = mysql_query("SELECT id FROM members WHERE UserName = $valuetotest");
2) Value of $valuetotest is a string value and needs to be within quotes in your query. Should be like
SELECT id FROM members WHERE UserName = 'hellohi'
And not like
SELECT id FROM members WHERE UserName = hellohi
And Oh, How can I prevent SQL injection in PHP?
<?php
$result = mysqli_query("SELECT `id`, `Password` FROM `members` WHERE `UserName` = '$valuetotest'");
if(mysqli_num_rows($result) == 0)
{
echo "User not found";
}
$password = 'something2';
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
if($password != $userData['Password'])
{
echo "Password not found";
}else{ // Redirect to home page after successful login.
header('Location: welcome.php');
}
?>
You are selecting a text so you should use ' ' Symbols in your Select statement.
Like this:
$valuetotest = 'something';
$result = mysql_query("SELECT id FROM members WHERE UserName = '$valuetotest'");
$result = mysql_query("SELECT id FROM members WHERE UserName = '".$valuetotest."'");

Cannot find mistake in PHP + MySQLi register page

I am trying to build a register page using PHP and MySQLi. However, it doesn't work, and I cannot understand the issue. It was previously with no MySQL improved syntax. There is just an empty page in browser.
<?php
include ("bd.php");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['login']))
{
$login = $_POST['login'];
if ($login == '')
{
unset($login);
}
}
if (isset($_POST['password']))
{
$password=$_POST['password'];
if ($password =='')
{
unset($password);
}
}
if (empty($login) or empty($password))
{
exit ("You have entered not all of the information, go back and fill in all the fields!");
}
$login = stripslashes($login);
$login = htmlspecialchars($login);
$password = stripslashes($password);
$password = htmlspecialchars($password);
$login = trim($login);
$password = trim($password);
$myrow = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
if (!empty($myrow['id']))
{
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2=mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2=='TRUE')
{
echo "You have successfully signed up!";
}
else
{
echo "Failed to sign up";
}
?>
bd.php:
<?php
$db = new mysqli ("localhost","root","root","kotik");
?>
<?php
include ("bd.php");
if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$login = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = htmlspecialchars($password);
if (empty($login) || empty($password)){exit ("You have entered not all of the information, go back and fill in all the fields!");}
$res = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
$myrow = mysqli_fetch_assoc($res);
if (!empty($myrow['id'])) {
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2 =mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2 == true)//use true not 'True' because 'True' is a string
{
echo "You have successfully signed up!";
}
else {
echo "Failed to sign up";
}
?>
EDIT: You should use mysqli_fetch_assoc to get an associative array which corresponds to the fetched row or NULL if there are no more rows.
You cannot use the variable $myrow like this:
$myrow['id']
You need to get the row then you can treat it like an array. It would look something like this:
$row = $myrow->fetch_row()
$row['id']
this gets the first row of the results of the query. If the query returns multiple results you can use something like this:
while($row = $myrow->fetch_row()) {
$rows[]=$row;
}
Then you use $rows as a normal array and get the individual rows 1 by 1 in a for loop, then you can use the same format:
$temp = $rows[0];
$temp['id']

mySQL statement not working inside of php

Im trying to do a login system for my website and I changed around how it is implemented and it broke, whenever I try to login with a correct login it fails to take me to the next page, here is my php:
<?php
//finds the correct database
$sql_link = mysqli_connect("localhost", "root" , "12buckle", "GameData");
if (mysqli_connect_errno())
{
echo "Failed to connect to databse: " . mysqli_connect_error();
}
if (isset($_POST['Username']))
{
$username = mysql_real_escape_string($_POST['Username']);
$password = mysql_real_escape_string($_POST['Password']);
//checking to see if password and username can be found in student database
//loading in correct data
$login = mysqli_query($sql_link,"SELECT * FROM tblStudents WHERE UserName='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['StudentFirstName'];
$_SESSION['ClassID'] = $login['ClassID'];
$_SESSION['ID'] = $login['StudentID'];
header ("Location: index.php");
}
else
{
$login = mysqli_query($sql_link,"SELECT * FROM tblTeacher WHERE Username='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['TeacherSurname'];
$_SESSION['title'] = $login['Title'];
$_SESSION['ID'] = $login['TeacherID'];
header ("Location: TeacherSide.php");
}
else
{
echo 'Login details incorrect';
}
}
}
Also if it helps when I ran it last night im sure it worked, but I was half awake so I may have been testing the old version
Your logic is faulty. mysql_query returns a result HANDLE. it does not return any actual data. You need to fetch a row first, before checking for actual data:
$result = mysqli_query($sql_link, "SELECT * FROM tblStduents ....");
if (mysqli_num_rows($result) > 0) {
... got a student record
$row = mysqli_fetch_assoc($result);
echo $row['StudentFirstName'];
} else {
... no student rows, repeat with teachers
}
I've had issues in the past where variables aren't read properly the way you have them in your SQL statements.
Try Username='" . $username . "' AND instead and see what happens.

why if condition doesn't handle username field in php-mysql?

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);

PHP/MySQL mysql_num_rows not returning values

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);

Categories