Get variable from mySQLi to PHP - php

I'm pretty new to the whole PHP and mySQLi thing... But at the moment I am trying to make a simple project where I would like to read a specific value from a mySQL database, and then simply print (echo) it..
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password = $_POST['password'];
if($username == '' || $password == ''){
echo 'please fill all values';
}else{
require_once('dbConnect.php');
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo 'All values match!';
}else{
echo 'These values do not match!';
}
mysqli_close($con);
}
}else{
echo 'error';
}
?>
I don't know if it is that obvious... but this is actually code for an app. But I mainly want to know how to get a specific value from mySQL as a PHP variable?
I will be using the username to search for the correct variables
Let's say the table looks like this :
username password money
guy 123 10
then I want to use 'guy' to find the amount of money and print it to the screen.
Sorry if this is asked and/or explained badly...

change the code like this where you are making query
$result=mysqli_query($con,$sql);
while($row=mysqli_fetch_assoc($result)){
$money= $row['money'];
}
//So because your query will return only one user if the ///username is unique so //now you can print money anywhere.

Related

How do i convince the code that the data i am trying to pull out of a MySQL database actually exists?

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

Php log in allows entry with no user/pass

Hey guys ive put together a basic user log in for a secure admin area and it seems to work great, if you enter a correct user/pass you get access, if you enter the wrong user pass, you get no access. However if you enter nothing in both fields you get access.
This is how it works.
Creating a user, a basic form POSTS to this php file.
<?php
$con = mysqli_connect(credentials are all good) or die(mysqli_error($con)) ;
$escapedUser = mysqli_real_escape_string($con, $_POST['user']);
$escapedPass = mysqli_real_escape_string($con, $_POST['pass']);
$some_str = md5(uniqid(mt_rand(), true));
$base_64str = base64_encode($some_str);
$modified_base64 = str_replace('+', '.', $base_64str);
$gensalt = substr($modified_base64, 0, 22);
$format_str = "$2y$10$"; // 2y for Blowfish and 10 times.
$salt = $format_str . $gensalt . "$";
$hashed_pass = crypt($escapedPass, $salt);
$query = "INSERT INTO `userpass` (`username`, `password`, `salt`) VALUES ('$escapedUser', '$hashed_pass', '$salt'); ";
if(isset($escapedUser) && isset($hashed_pass))
{
mysqli_query($con, $query);
header("Location: ausers.php");
exit();
}
Echo "Something went wrong!";
?>
The database appears to be storing these fine
We then log in with this code
<?php
$con = mysqli_connect(again credentials are fine) or die(mysqli_error($con)) ;
$escapedUser = mysqli_real_escape_string($con, $_POST['user']);
$escapedPass = mysqli_real_escape_string($con, $_POST['pass']);
$saltQuery = "select salt from userpass where username = '$escapedUser';";
$result = mysqli_query($con, $saltQuery);
$row = mysqli_fetch_assoc($result);
$salt = $row['salt'];
$hashed_pass = crypt($escapedPass, $salt);
if(isset($escapedUser) && isset($hashed_pass))
{
$userQuery = "SELECT * FROM userpass WHERE username='$escapedUser' AND password='$hashed_pass'";
$userpass = mysqli_query($con, $userQuery);
$count = mysqli_num_rows($userpass);
if($count == 1)
{
$_SESSION['username'] = $escapedUser;
header("location: aindex.php");
exit();
}
header("Location: alogin.htm");
exit();
}
Echo "Something went wrong!";
?>
So as i said, this seems to work fine for when any user pass combination is given whether access granted or denied however using no user and pass and pressing log in allows entry. Any ideas? THeres no blank rows in the database table.
Side question, is this salt/hash method correct, its my first attempt.
For your login code, your condition relies on an isset() test. You perform this test on $escapedUser and $hashed_pass. Both of these variables were actually assigned values earlier in the code! Once you assign a value to the variable, it will pass the isset() test, even if the value is an empty string. You might want to use an empty() check, perhaps on the original $_POST variables.
Moving on to the inner condition, which tests if the mysql query returns exactly 1 row of results. If there were truly no rows with empty values, then this condition would never pass because the query would return 0 rows. But it is passing. Two things to consider:
Notice that your registering code uses the same isset() test. Therefore it is very possible that someone used your registration form, submitted empty fields, and successfully registered a row with empty user and password fields. Have you explicitly queried your database for empty fields and actually come up with 0 results?
Your query uses SELECT *. Perhaps this is causing the query to return some sort of aggregate value (like a COUNT() or something that always has a result no matter what). Perhaps try explicitly defining the columns to return?
I cannot comment on your salt/hash method as I have no experience in that part. Hope you find this helpful!
In my opinion you need more than one level of checks in any form, whether it be registration, comments, login, etc. The way I prefer to go about it is a tiered approach. It may work better for you, but it's just an example.
By doing it this way, you ensure that your input will never be empty. Another issue I see with your login script is that you never compare the input with the database so how can you know if they entered the correct information? The only thing allowing them to login is that the query returned a record. This is also why they can login with a blank form.
<?php
$con = mysqli_connect(again credentials are fine) or die(mysqli_error($con)) ;
/* Ensures that form was submitted before any processing is done */
if (isset($_POST)) {
$User = $_POST['user']);
$Pass = $_POST['pass']);
if (!empty($User)) {
if (!empty($Pass)) {
$escapedUser = mysqli_real_escape_string($con, $User);
$escapedPass = mysqli_real_escape_string($con, $Pass);
/* you need to verify the password here, before adding the salt */
$saltQuery = "select salt from userpass where username = '$escapedUser'";
$result = mysqli_query($con, $saltQuery);
$row = mysqli_fetch_assoc($result);
$salt = $row['salt'];
$hashed_pass = crypt($escapedPass, $salt);
$userQuery = "SELECT * FROM userpass WHERE username='$escapedUser' AND password='$hashed_pass'";
/* you need to verify the username somewhere here */
$userpass = mysqli_query($con, $userQuery);
$count = mysqli_num_rows($userpass);
if($count == 1)
{
$_SESSION['username'] = $escapedUser;
header("location: aindex.php");
exit();
} else {
header("Location: alogin.htm");
exit();
}
} else {
echo "Please enter a password.";
}
} else {
echo "Please enter a username.";
}
} else {
echo "You have not entered any information.";
}
?>

Error with MySql Query it shows part of the data and not the rest

In this index page of mine I have an error coming up with the code so I printed off the Query to see if the error is there and strangely enough I get the ID and Password of the query but not the username.
This is the print out:
SELECT * FROM admin WHERE id='3' AND username='' AND password='alan' LIMIT 1You data dont exist in the database
where username field is empty should be Alan
here is my PHP:
<?php
session_start();
if (!isset($_SESSION["manager"])){
header("location: admin_login.php");
exit();
}
$managerID = preg_replace('#[^0-9]#i','',$_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);
include"db_connection.php";
$q = "SELECT * FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1";
$sql = mysql_query($q);
echo $q;
$existCount=mysql_num_rows($sql);
if ($existCount ==0){
//header ("location: index.php");
echo "You data dont exist in the database";
exit();
}
?>
Using the following, I was able to successfully echo all three session variables.
Therefore, I am under the impression that either the username session variable is not set (from a previous form/HTML), and/or the form input element is not named or contains a typo.
Since you did not provide additional information in your (original) question in regards to how you are using it (from a form, or other) am submitting the following as a successful test.
I left out the first conditional statement from your code and filled in my own session variables.
<?php
session_start();
$_SESSION["id"] = "3";
$_SESSION["username"] = "FRED";
$_SESSION["password"] = "12345";
$managerID = preg_replace('#[^0-9]#i','',$_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);
echo $_SESSION["id"];
echo "<br>";
echo $_SESSION["username"];
echo "<br>";
echo $_SESSION["password"];
Which echo'ed:
3
FRED
12345
I am questioning this line though, since there is no other reference to it:
if (!isset($_SESSION["manager"]))
since it seems to be related to the word "manager"
$managerID = preg_replace('#[^0-9]#i','',$_SESSION["id"]);
where you might have meant to use:
if (!isset($_SESSION["id"]))
or:
$managerID = preg_replace('#[^0-9]#i','',$_SESSION["manager"]);

I don't know what's wrong with this code SQL

I'm new to PHP and Mysql, for some reason it only checks for statement if($email == $result2 ) wether the input is username or email. I don't know why? can someone explain it logically, i'm stuck for hours figuring it out. :( Thanks Please be kind.
<?php
session_start();
include_once("connect.php");
$email = $_POST['email'];
$username = $_POST['username'];
//echo $_POST['email'];
if(isset($_POST['email']) )
{
$extract= mysql_query("SELECT username, email FROM users");
$resultq = mysql_num_rows($extract);
while($row= mysql_fetch_array($extract))
{
$result = $row['username'];
$result2 = $row['email'];
//$pass = $_POST['pass'];
if($email == $result2 )
{ //check if there is already an entry for that username
echo "Email Address is already used!";
exit(); //break;
}
if ($username == $result )
{
echo " Username is already Taken!";
//mysql_query("INSERT INTO users (Username, Password) VALUES ('$user', '$pass')");
//header("location:index.php");
exit(); //break;
}
else
{
}
}
}
It's behaving as written. If either if() test succeeds, you tell the script to exit().
Remove the exit() calls...
You also really REALLY need to learn about WHERE clauses in queries. You are sucking across your entire user table and comparing the records one at a time. This is the equivalent of driving to the grocery store, buying up the ENTIRE store's inventory, driving it home... then throwing it all in the garbage because all you really wanted was one candy bar.
I think you better use unique in your email and username column, then you don't need to check it anymore, mysql will do that for you!
Does it go into the second if statement ( if ($username == $result ) ) after you comment out the first one ( if ($username == $result )) ?
If so, then it keeps hitting that exit() function.
Guys i kinda guessed the answer from combining some of your comments. for some reason i need to include isset($_POST['username']) along with isset($_POST['email']) in order for my if Statements to be all executed... perhaps it was the isset checking if there is a value for username.
try this
if($email == $result2 )
{ //check if there is already an entry for that username
echo "Email Address is already used!";
//---------removed that line
}
else if ($username == $result ) //add else if instead of if
{
echo " Username is already Taken!";
//mysql_query("INSERT INTO users (Username, Password) VALUES ('$user', '$pass')");
//header("location:index.php");
//----------removed that line
}
else
{
}
EDIT:
change this
if(isset($_POST['email']) )
to
if(isset($_POST['email']) or isset($_POST['username']))
this to check them both. you are checking just email thats why you dont get the second if.
change this line the following line:
$extract= mysql_query("SELECT username, email FROM users");
Then use where clause as follows:
$extract= mysql_query("SELECT username, email FROM users where username='$username' and email='$email'");

Unable to check for password and username at login

I have tried to create a PHP log in form. My code is as follows. The if-else statement is not functioning well. Please solve this.
$connect = mysql_connect("localhost", "root", ""); //connect
mysql_select_db("elective_mgmt", $connect);
$username = $_GET["name"];
$password = $_GET["password"];
$query = "SELECT * from verify_student where
username='$username' && password='$password'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if (name == $username && password == $password)
echo "you are logged in";
else
echo "please recheck your password and username";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "you are logged in";
}
else
echo "please recheck your password and username";
You can also do this by counting the number of rows. In your code $row is an array so whenver you need to acces the array elements do this $row['name']
You have a problem here.
if(name==$username && password==$password)
It should be
if($row['name']==$username && $row['password']==$password)
OR
if(mysql_num_rows($result) == 1)
You should look at - Why shouldn't I use mysql_* functions in PHP?
You could remove your if/else statement since you check the inputs already with your mysql query (name && password) and replace it with a mysql_num_rows == 1 (as the others have already mentioned before).
It seems that you are new to php and creating log in forms, so let me give you a good advice:
input values for a log in form shouldn't be passed via URL, use method post instead
never save passwords unencrypted (use sha512 since md5 is considered unsafe)
never use single information to store the log in status in the session

Categories