PHP login script always returns "login failed" - php

I have to give users the ability to log in for an assignment. At first, it seemed to me this script was simple enough to work, but everytime I try to log in with an existing account it gives me the "login failed" message. I don't know where my mistake lies. It's a PostgreSQL database, I'll enclose an image of it below.
<?php
require 'databaseaccess.php';
try {
$conn = new PDO('pgsql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME,DB_PASSWORD);
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "\n";
phpinfo();
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$tablename = "users";
// sql-injection counter
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$qry = $conn->prepare("SELECT * FROM $tablename WHERE userid = :username and userpass = :password");
$qry->bindParam(':username', $username, PDO::PARAM_STR, 16);
$qry->bindParam(':password', $password, PDO::PARAM_STR, 16);
$qry->execute();
$result = pg_query($qry);
$count = pg_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count == 1) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
header("location:logingelukt.php");
} elseif ($count = -1) {
echo "there has been an error";
} else{
print $count;
echo "login failed";
}
?>
I have no problems connecting to the database, so that's not an issue, it's just that it always sees $count as something else than zero. Another oddity is that the print $count command doesn't output anything.I use the account I made with postgresql outside of the page, which is just admin:admin. Also, I'm sure the right variables are getting passed from the form.
EDIT: After using var_dump($result), as advised by kingalligator, it seems that $result is indeed NULL, thus empty. I'm gonna try using fetch() instead of pg_query().

I think the issue is that you're mixing PDO and pg_ functions.
Replace:
$result = pg_query($qry);
$count = pg_num_rows($result);
With:
$result = $qry->fetchAll();
$count = count($result);
PDO Function reference can be found here: http://www.php.net/manual/en/class.pdostatement.php

Have you confirmed that you're actually getting data returned from your query? Try this:
var_dump($result);
To ensure that data is being returned from your query. You can still have a successful connection to a database, yet have a query that returns nothing.

You probably should check your column userid at WHERE clause. I don't know the table columns, but is strange that 'userid' has the name of the user in:
"SELECT * FROM $tablename WHERE userid = :username and userpass = :password"
Maybe it is causing the problem.

Related

SQL insert to MySQL doesn't work

I'm currently trying to insert username, pw to a DB, and check if the username already exists.
The problem is that the SQL (select) syntax doesn't work, nor does the (insert). I've checked around for a couple of hours in forums and Stackoverflow, and my current code is the following.
What might be the problem?
Thanks, Jimmie.
<?php
$servername = "localhost";
$username = "name";
$password = "pw";
$dbname = "dbaname";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ((isset ($_POST["identity"])) && (isset ($_POST["pin"])) && (isset ($_POST["token"])))
{
$identity = htmlspecialchars($_POST['identity'], ENT_QUOTES, "ISO-8859-1");
$pin = htmlspecialchars($_POST['pin'], ENT_QUOTES, "ISO-8859-1");
$token = htmlspecialchars($_POST['token'], ENT_QUOTES, "ISO-8859-1");
echo "$identity";
if($token == "xyz13D;A##:!#")
{
$result = $mysqli->query("SELECT `identity` FROM Users WHERE `identity` = '" . $identity . "'");
if($result->num_rows == 0)
{
echo "successCreat";
// Perform queries
mysqli_query($mysqli,"SELECT * FROM Users");
mysqli_query($mysqli,"INSERT INTO Users (identity,pin,userActivity, identityCreated) VALUES ('$identity', '$pin',1,now())");
}
else
{
echo "failureCreate";
}
}
else
{
echo"Wrong Key";
}
}
$mysqli->close();
?>
Assuming that identity is a primary key, then you can check the error flags after executing an INSERT query to see if an error occurred.
mysqli_query( $mysqli, "INSERT INTO ... " ); //< ... Represents query
if (mysqli_error( $mysqli )) {
echo "Failure";
}
else {
echo "Success";
}
Also, you should properly escape input as stated in the comments. In addition, you should check whether or not the connection attempt was successful using mysqli_connect_error.
Finally, there might be an issue in your SQL suntax which mysqli_error will also catch. A last possibility is that the POST data isn't being set properly and the code is being ignored completely.

PDO Insert not working with bindParam

I am currently using PDO to connect to my database and it works, but when a user logs in, I want it to check if the user's id is already in a row, I have already done this in the code below:
<?php
require 'steamauth/steamauth.php';
if(!isset($_SESSION['steamid'])) {
$username = "Unknown";
$avatar = "defaultUser";
$accid = "Unknown";
$credits = "Not Applicable";
$avatarSmall = "smallUser"; //For Dashboard
} else {
include ('steamauth/userInfo.php');
$username = &$steamprofile['personaname'];
$avatar = &$steamprofile['avatarmedium'];
$accid = &$steamprofile['steamid'];
$avatarSmall = &$steamprofile['avatar']; //For Dashboard
$db_user = "USERNAME";
$db_pass = "PASSWORD";
$db_host = "HOST";
$db_name = "DATABASE NAME";
$db = new PDO("mysql:host=".$db_host.";db_name=".db_name, $db_user, $db_pass);
try{
$check = $db->prepare("SELECT userID from userData WHERE userID = :accountID");
$check->bindParam(':accountID', $accid, PDO::PARAM_INT);
$check->execute();
if(!$check){
die("Server Error: 404Check, Please Contact A Member Of Staff If This Error Continues.");
}else{
if($check->rowCount() > 0) {
$creditsQuery = $db->prepare("SELECT userCredits FROM userData WHERE userID = :accountID3");
$creditsQuery->bindParam(":accountID3", $accid, PDO::PARAM_INT);
$creditsQuery->execute();
//Set Credits To Variable From Database Column
$credits = $creditsQuery->fetch(PDO::FETCH_ASSOC);
}else{
$sql = $db->prepare("INSERT INTO userData (userID, userCredits) VALUES (:accountID2, '0')");
$sql->bindParam(':accountID2', $accid, PDO::PARAM_INT);
$sql->execute();
if(!$sql){
die('Server Error: 404Insert, Please Contact A Member Of Staff If This Error Continues.');
}
}
}
}catch(PDOException $e){
die ("Server Error: 404Connection, Please Contact A Member Of Staff If This Error Continues.");
}
}
?>
Although, when I login, it doesn't seem to store the user's id or credits as 0, and the table (userData) is empty.
Thanks,
Matt
This is wrong:
$check->execute();
if(!$check){
^^^^^^^
$check doesn't magically change into a boolean true/false if the execute fails. It will ALWAYS be a prepared statement object, and therefore always evaluate to true.
You didn't enable exceptions in PDO, therefore it runs in the default "return false on failure" mode, which means your code should be:
$res = $check->execute();
if(!$res) {
die(...);
}
And this holds true for your other prepare/execute blocks as well - Your script is killing itself before it ever gets to the insert query, because your test for database failure is wrong.

PHP registered user check

I have PHP + AS3 user login&register modul.I want to check registered user by username.But can't do it because I'm new at PHP.If you can help it will helpfull thx.(result_message part is my AS3 info text box.)
<?php
include_once("connect.php");
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES ('$username', '$password', '$userbio')";
mysql_query($sql) or exit("result_message=Error");
exit("result_message=success.");
?>
Use MySQLi as your PHP function. Start there, it's safer.
Connect your DB -
$host = "////";
$user = "////";
$pass = "////";
$dbName = "////";
$db = new mysqli($host, $user, $pass, $dbName);
if($db->connect_errno){
echo "Failed to connect to MySQL: " .
$db->connect_errno . "<br>";
}
If you are getting the information from the form -
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
you can query the DB and check the username and password -
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $db->query($query);
If you get something back -
if($result) {
//CHECK PASSWORD TO VERIFY
} else {
echo "No user found.";
}
then verify the password. You could also attempt to verify the username and password at the same time in your MySQL query like so -
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password';
#Brad is right, though. You should take a little more precaution when writing this as it is easily susceptible to hacks. This is a pretty good starter guide - http://codular.com/php-mysqli
Using PDO is a good start, your connect.php should include something like the following:
try {
$db = new PDO('mysql:host=host','dbname=name','mysql_username','mysql_password');
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Your insert would go something like:
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES (?, ?, ?)";
$std = $db->prepare($sql);
$std = execute(array($username, $password, $userbio));
To find a user you could query similarly setting your $username manually of from $_POST:
$query = "SELECT * FROM users WHERE username = ?";
$std = $db->prepare($query)
$std = execute($username);
$result = $std->fetchAll();
if($result) {
foreach ($result as $user) { print_r($user); }
} else { echo "No Users found."; }
It is important to bind your values, yet another guide for reference, since I do not have enough rep yet to link for each PDO command directly from the manual, this guide and website has helped me out a lot with PHP and PDO.

fetching user id from login SQL table

I have recently switched my code from mysql to mysqli OOP for better practice. I am trying to fetch the user_id from my mysql table and save it in $_SESSION['user_id']. I have tried many different iterations of my code and worked on it for hours but no luck. As of now $_SESSION['user_id'] returns nothing. It works with my old mysql code so I know its not an issue with my table. I am still new at mysqli and I would greatly appreciate any help in this matter.
Here is the PHP:
<?php
session_start();
$con = new mysqli("localhost","root","pw","db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST['submit'])){
$query = "SELECT * FROM tapp_login WHERE username = ? AND password = ? LIMIT 1";
$username = $_POST['user_name'];
$password = $_POST['pwd'];
$stmt = $con->prepare($query);
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1){ //To check if the row exists
while($row = $stmt->fetch()){ //fetching the contents of the row
$_SESSION['user_id'] = $row[1];
$_SESSION['LOGIN_STATUS']=true;
$_SESSION['user_name'] = $username;
echo 'true';
}
}
else {
echo 'false';
}
$stmt->free_result();
$stmt->close();
}
else{
}
$con->close();
?>
The validation works and the user name is successfully stored in the session. I think the error is in the $row = $stmt->fetch() but I cannot figure it out. Thanks in advance!
I think the issue is this line:
$_SESSION['user_id'] = $row[1];
I believe it should either be $row[0] or $row['user_id'].
(note: I used 'user_id', but it would be the name of the column that holds the IDs)

Selecting certain row in mysql

I am completely new to MYSQL and PHP, so i just need to do something very basic.
I need to select a password from accounts where username = $_POST['username']... i couldn't figure this one out, i keep getting resource id(2) instead of the desired password for the entered account. I need to pass that mysql through a mysql query function and save the returned value in the variable $realpassword. Thanks!
EDIT:
this code returned Resource id (2) instead of the real password
CODE:
<?php
$con = mysql_connect('server', 'user', 'pass');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
echo '<br/> ';
// Create table
mysql_select_db("dbname", $con);
//Variables
//save the entered values
$enteredusername = $_POST['username'];
$hashedpassword = sha1($_POST['password']);
$sql = "SELECT password from accounts where username = '$enteredusername'";
$new = mysql_query($sql,$con);
echo "$new";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
It will be a lot better if you use PDO together with prepared statements.
This is how you connect to a MySQL server:
$db = new PDO('mysql:host=example.com;port=3306;dbname=your_database', $mysql_user, $mysql_pass);
And this is how you select rows properly (using bindParam):
$stmt = $db->prepare('SELECT password FROM accounts WHERE username = ?;');
$stmt->bindParam(1, $enteredusername);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$password = $result['password'];
Also, binding parameters, instead of putting them immediately into query string, protects you from SQL injection (which in your case would be very likely as you do not filter input in any way).
I think your code looks something like this
$realpassword = mysql_query("SELECT password
from accounts where username = '$_POST[username]'");
echo $realpassword;
This will return a Resource which is used to point to the records in the database. What you then need to do is fetch the row where the resource is pointing. So, you do this (Note that I am going to use structural MySQLi instead of MySQL, because MySQL is deprecated now.)
$connection = mysqli_connect("localhost", "your_mysql_username",
"your_mysql_password", "your_mysql_database")
or die("There was an error");
foreach($_POST as $key=>$val) //this code will sanitize your inputs.
$_POST[$key] = mysqli_real_escape_string($connection, $val);
$result = mysqli_query($connection, "what_ever_my_query_is")
or die("There was an error");
//since you should only get one row here, I'm not going to loop over the result.
//However, if you are getting more than one rows, you might have to loop.
$dataRow = mysqli_fetch_array($result);
$realpassword = $dataRow['password'];
echo $realpassword;
So, this will take care of retrieving the password. But then you have more inherent problems. You are not sanitizing your inputs, and probably not even storing the hashed password in the database. If you are starting out in PHP and MySQL, you should really look into these things.
Edit : If you are only looking to create a login system, then you don't need to retrieve the password from the database. The query is pretty simple in that case.
$pass = sha1($_POST['Password']);
$selQ = "select * from accounts
where username = '$_POST[Username]'
and password = '$pass'";
$result = mysqli_query($connection, $selQ);
if(mysqli_num_rows($result) == 1) {
//log the user in
}
else {
//authentication failed
}
Logically speaking, the only way the user can log in is if the username and password both match. So, there will only be exactly 1 row for the username and password. That's exactly what we are checking here.
By seeing this question we can understand you are very very new to programming.So i requesting you to go thru this link http://php.net/manual/en/function.mysql-fetch-assoc.php
I am adding comment to each line below
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1"; // This is query
$result = mysql_query($sql); // This is how to execute query
if (!$result) { //if the query is not successfully executed
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) { // if the query is successfully executed, check how many rows it returned
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) { //fetch the data from table as rows
echo $row["userid"]; //echoing each column
echo $row["fullname"];
echo $row["userstatus"];
}
hope it helps
try this
<?php
$con = mysql_connect('server', 'user', 'pass');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
echo '<br/> ';
// Create table
mysql_select_db("dbname", $con);
//Variables
//save the entered values
$enteredusername = mysql_real_escape_string($_POST['username']);
$hashedpassword = sha1($_POST['password']);
$sql = "SELECT password from accounts where username = '$enteredusername'";
$new = mysql_query($sql,$con);
$row = mysql_fetch_array($new) ;
echo $row['password'];
if (!$new)
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
<?php
$query = "SELECT password_field_name FROM UsersTableName WHERE username_field_name =".$_POST['username'];
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row['password_field_name'];
?>
$username = $_POST['username'];
$login_query = "SELECT password FROM users_info WHERE users_info.username ='$username'";
$password = mysql_result($result,0,'password');

Categories