This question already has an answer here:
Get results from from MySQL using PDO
(1 answer)
Closed 7 years ago.
I'm totally new to PDO so I apologize if I made a simple mistake here. Also if this has been answered before. I searched but couldn't find. My problem is that when I print the sessions it prints out 'Array ( [user_id] => 1 )' but the username and password I entered is for user_id 2. I have tried this with a differant username and password and it still gives an id value of 1. So I echoed out $user_id before the session is created and it is 1. But I can't figure out where it is getting this 1 from? Because there is no id of 1 in the database. Can anyone shed some light on this?
Here is the code from my login file:
<?php
require 'core.inc.php';
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
$stmt = $db->prepare("SELECT password FROM users WHERE username = ?");
$stmt->bindParam(1, $username);
$hash = $stmt->execute();
$password_verified = password_verify($password, $hash);
if ($password_verified = true) {
$stmt_id = $db->prepare("SELECT id FROM users WHERE username = ?");
$stmt_id->bindParam(1, $username);
$user_id = $stmt_id->execute();
echo $user_id;
$id_num_rows = $stmt_id->rowCount();
if ($id_num_rows == 0) {
echo 'You have entered a wrong password';
}else if($id_num_rows == 1){
$_SESSION['user_id'] = $user_id;
print_r($_SESSION);
}
} else {
echo("Please enter a username and password.");
}
}
}
?>
<!DOCTYPE html>
<header>
</header>
<body>
<form action ="<?php echo $current_file;?>" method="post">
<div class='field'>
<label for="username">Username: </label><input type='text'
name='username'/><br>
</div>
<div class='field'>
<label for ="password">Password: </label><input type='password'
name='password'/>
</div>
<div class='field'>
<label for='remember'>
<input type='checkbox' name="remember" id="remember"/> Remember me
</label>
</div>
<input type='submit' value='Log in'/>
</form>
</body>
</html>
<And here is the code from core.inc.php
<?php
session_start();
require 'connect.inc.php';
ob_start();
$current_file = $_SERVER['SCRIPT_NAME'];
#$http_referer = $_SERVER['HTTP_REFERER'];
function loggedin(){
if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
return true;
}else{
return false;
}
}
?>
<Core.inc.php uses connect.inc.php which is added below:
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=goal;charset=utf8','root','');
var_dump($db);
echo 'connected';
}
catch(Exception $e){
echo 'Error 1 has occured';
}
?>
$stmt_id->execute();
Returns true on succes, or false on failure, you need to use the result of the query (and not the status of the execution):
$stmt_id->fetchAll()
Also you have an error here, you need to use comparison and not assignment:
if ($password_verified = true)
The line
if ($password_verified = true) {
is very incorrect because you're basically just assigning true to $password_verified. You should just be doing a if($password_verified) though, I am not sure if it will solve your problem.
You are also not parsing the results as you should be using fetchAll() and then going through the results to see if the user exists.
$stmt_id->execute() will return bool, in your case it's true and later converted to int.
See http://php.net/manual/en/pdostatement.execute.php
You need to fetch the data in order to retrieve the user_id.
Related
the registration form is connected to the database via db.php but I am having trouble in submitting the login details.
<html>
<head>
<?php
include('db.php');
$username = #$_POST['username'];
$password = #$_POST['password'];
$submit = #$_POST['submit'];
the main problem is after the submit button is clicked by an existing user it should give the message but there's problem in the if statement, because on the wamp server its showing only the else message i.e. Error.
if ($submit)
{
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
if (mysql_num_rows($result)) {
$check_rows = mysql_fetch_array($result);
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
echo "<center>";
echo "You are now Logged In. ";
echo "</center>";
}
else {
echo "<center>";
echo "No User found. ";
echo "</center>";
}
}
else echo "Error";
?>
</head>
<body>
<form method="post">
Username : <input name="username" placeholder="Enter Username" type="text"><br></br>
Password : <input name="password" placeholder="Enter Password" type="password"><br>
<input type="submit" value="Submit">
</body>
</html>
You want get $_POST with name submit, but do not send it to the form
Try change
<input type="submit" value="Submit">
to
<input type="submit" name="submit" value="Submit">
Firstly this is old style of php/mysql. So look at PDO on php.net seeing as you are setting out on new project it really wont be hard to make the change now rather than later.
Now onto your issue. if you intend on carrying on with your old method try this.
$sql = "SELECT * FROM user WHERE username=' . $username . ' AND password=' . $password . '";
// check the query with the die & mysql_error functions
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_num_rows($query);
// checking here equal to 1 In a live case, for testing you could use >= but not much point.
if ($result == 1) {
// Checking needs to be Assoc Now you can use the field names,
// otherwise $check_rows[0], $check_rows[1] etc etc
$check_rows = mysql_fetch_assoc($query); // oops we all make mistakes, query not result, sorry.
// This is bad but for example il let this by,
// please dont access user supplied data without
// validating/sanitising it.
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
} else {
// do not logged in here
}
The same in PDO
$sql=" Your query here ";
$pdo->query($sql);
$pdo->execute();
$result = $pdo->fetch();
if ($result = 1) {
// do login stuff
} else {
// no login
}
Remember though that you need to set up PDO and it may not be available on your server by default (older php/mysql versions) but your host should be happy enough to set them up.
Coding, as I've been learning, is about little details, and I'm missing something because I have the following code:
public function login() {
if ($_POST) {
$logdb = new PDO('mysql:host=localhost;dbname=kiko', 'kiko', 'pass');
$logdb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $logdb->prepare("SELECT * FROM usreg WHERE email=:email AND password=:pass");
$stmt->bindParam(":email", $_POST['email']);
$stmt->bindParam(":pass", $_POST['password']);
$stmt->execute();
$loged = $stmt->fetch();
$atributes = $stmt->fetch(PDO::FETCH_ASSOC);
if ($loged) {
session_start();
$_SESSION["loggedIn"] = true;
$_SESSION["id"] = $atributes->id;
$_SESSION["email"] = $_POST['email'];
$_SESSION["group"] = $atributes->group;
$_SESSION["firstname"] = $atributes->firstname;
$_SESSION["lastname"] = $atributes->lastname;
$_SESSION["phone"] = $atributes->phone;
$_SESSION["mobile"] = $atributes->mobile;
$_SESSION["adress"] = $atributes->adress;
$_SESSION["city"] = $atributes->city;
$_SESSION["country"] = $atributes->country;
} else {
echo 'wrong login try again';
}
} else {
echo '<form name="login" action="" method="POST">
Email: <br />
<input type="text" name="email"/><br />
Password: <br />
<input type="password" name="password"/><br />
<button type="submit">Login</button>
Register</form>';
}
}
and everything works well except the part where I'm registering globals. What I'm trying to do is set the global session the details from the fetch array atributes, I tried with:
$atributes = $stmt->fetch(PDO::FETCH_OBJ);
but the result is the same, and I changed the email from array to POST and it works because when I do:
echo $_SESSION['email'];
It works, but the fetch is not passing the details to the other session globals. What should I put in there to sucess what I'm trying to do can you guys help me? Do I need another kind of prepared statement? Is it missing results because I'm making the WHERE clause?
Why are you fetching twice? Once for $loged and another for $atributes
I assume the username/password combination will be unique, so you'll only get one result from your SQL query. That means when you call fetch again, you'll get nothing.
Perhaps you want:
//$loged = $stmt->fetch();
$atributes = $stmt->fetch(PDO::FETCH_OBJ);
if ($atributes) {
session_start();
$_SESSION["loggedIn"] = true;
$_SESSION["id"] = $atributes->id;
Also, make sure you use password_verify when dealing with passwords!
I'm trying to sign users in. I've already made the sign up form, And the database is properly connected.
It keeps on skipping over the first IF statements and going to straight to the "something went wrong error".
Does anybody know why it's not working?
<?php
$pageTitle = "Sign In";
$pageCategory = "Sign In";
$pageCategoryurl = "/signin.php";
//signup.php
include($_SERVER["DOCUMENT_ROOT"] . "/inc/header.php");
include($_SERVER["DOCUMENT_ROOT"] . "/inc/search.php");
?>
<div class="content">
<div id="signinheader"><h2>Sign in</h2></div><div style="clear:both"></div>
<?php
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can sign out if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form method="post" action="">
<table>
<tr>
<th><label for="username" class="signinlabel">Username:</label></th>
<td><input type="text" name="username" class="signininput"></td>
</tr>
<tr>
<th><label for="userpass" class="signinlabel">Password:</label></th>
<td><input type="password" name="userpass" class="signininput"></td>
</tr>
</table>
<input type="submit" value="Sign In" class="signinbutton">
</form>';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Save the data
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['username']) OR empty($_POST['username']))
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['userpass']) OR empty($_POST['userpass']))
{
$errors[] = 'The password field must not be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo '<div id="signinerror"><h3>Uh-oh.. a couple of fields are not filled in correctly..</h3>';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li class="signinerrorli">' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul></div><div style="clear:both"></div>';
}
else
{
//the form has been posted without, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$username = $_POST['username'];
$userpass = sha1($_POST['userpass']);
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass");
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysqli_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysqli_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['useremail'] = $row['useremail'];
}
echo 'Welcome, ' . $_SESSION['username'] . '. Proceed to the homepage.';
}
}
}
}
}
?>
</div>
<?php
include($_SERVER["DOCUMENT_ROOT"] . "/inc/footer.php");
?>
Your error is on your query:
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass");
You miss a quote at the end.
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass' ");
^here
Your query to the database is resulting in some sort of database failure, as !$result, as you have it, will only resolve to true when $result is false. In your case, $result would only be false if something went wrong with the query.
The answer? You have a syntax error:
You have this:
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass");
Where it should be this
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass'");
Do you see it? You were missing that last ' :)
I like to call these "missing semicolon" errors, because they're impossible to find, drive you crazy, and are so simple to fix that it makes you feel dumb.
I'm making a login page for the admins to make some changes to a website easily. However, the login page isn't working correctly. It won't go to the error page InvalidLogin.html and it won't go to the next page of the admin website AdminChanges.php.
Instead, I'm getting the following message:
Not Found
The requested URL /website/method="post" was not found on this server.
<?php
if ($_POST['submit'] == "submit")
{
$userName = $_POST['username'];
$passWord = $_POST['password'];
$db= mysql_connect("localhost", "root", "root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("onlineform", $db);
$checkUserNameQuery = "SELECT username FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWordQuery = "SELECT password FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkPassWord = mysql_query($checkPassWordQuery);
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
$AdminChanges = "AdminChanges.php";
}
else
{
$AdminChanges = "InvalidLogin.html";
}
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<form action = <?php PrepSQL($AdminChanges); ?> method="post">
username: <input type="text" name="username" />
password: <input type="text" name="password" /> <br/>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
Two problems are joining forces to cause this error. First, your PrepSQL function does not echo the response, and neither does the code that calls it. You need to echo or print the response so that it appears in your generated HTML.
<?php echo PrepSQL($AdminChanges); ?>
Second, you need to encapsulate that value of the action attribute in double-quotes, like this:
<form action = "<?php echo PrepSQL($AdminChanges); ?>" method="post">
Also note that your code assumes that your mysql_query() statements were successful. For troubleshooting purposes, you should at least add an or die(mysql_error()) statement to the end of the mysql_query() lines. This will allow your code to provide some feedback when the query fails.
Additionally, please note that your query-handling method will never result in a valid login response.
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWord = mysql_query($checkPassWordQuery);
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
mysql_query() returns a MySQL resource, not a single field from the database. Your code attempts to compare that resource to the supplied username and password, and the comparison will always fail. For details about handling the results of mysql_query() see the documentation.
Replace:
PrepSQL($AdminChanges);
with:
print PrepSQL($AdminChanges);
Try this:
<form action = "<?php echo PrepSQL($AdminChanges); ?>" method="post">
You need to echo the value.
There are 2 errors I noticed:
Your $_POST['submit'] if statement doesn't let $AdminChanges be set for the form unless it has already been submitted.
To fix this you could change your if submit statement to just redirect to your invalid login page like so:
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
//Correct info do what you need to here
}
else
{
header("Location: InvalidLogin.html");
exit();
}
And also:
You need to change the action to go post to this page.
<form action="<? $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
there is a problem with the following code that I can't seem to figure out. Perhaps there are more that I haven't yet seen. For some reason, when I hit submit with valid credentials, the verification doesn't work properly. I've tried the resulting sql code directly in mysql and it works, but $result always returns false. Also, the remember me checkbox always checks on between submissions. Any suggestions people have would be really appreciated.
Thanks,
Jason
<?php
$username = (isset($_POST["username"]) ? $_POST["username"] : (isset($_COOKIE["username"]) ? $_COOKIE["username"] : ""));
$password = (isset($_POST["password"]) ? md5($_POST["password"]) : (isset($_COOKIE["password"]) ? $_COOKIE["password"] : ""));
$pwlength = (isset($_POST["pwlength"]) ? strlen($_POST["pwlength"]) : (isset($_COOKIE["password"]) ? $_COOKIE["password"] : 0));
$remember = (isset($_POST["remember"]) ? 1 : (isset($_COOKIE["remember"]) ? $_COOKIE["remember"] : 0));
if (isset($username) && isset($password)) {
//$result = mysql_query("select companyID from Users where username='$username' && password='$password'");
$result = 0;
if (!$result) {
$message = "Attempt to retrieve user credentials from database failed. Please contact the administrator.";
}
else {
$field = mysql_fetch_assoc($result);
if (!isset($field['companyID'])) {
$message = "Please enter a valid username and password combination.";
}
else {
$_SESSION['companyID'] = $field['companyID'];
if ($remember == '1') {
setcookie("username", $username);
setcookie("password", $password, time()+(7*24*60*60));
setcookie("pwlength", $pwlength, time()+(7*24*60*60));
setcookie("remember", $remember, time()+(7*24*60*60));
}
else {
setcookie("username",'', time()-(60*60));
setcookie("password",'', time()-(60*60));
setcookie("pwlength",'', time()-(60*60));
setcookie("remember",'', time()-(60*60));
}
}
}
}
?>
<html><head><title>Login to CAPA</title>
<?php
//include 'includes/global.php';
session_unset();
//mysql_login();
if (isset($_SESSION['companyID'])) { die("<meta http-equiv='refresh' content='0; url=company.php' /></head></html>"); }
?>
</head>
<body onLoad="document.forms.form.username.focus()">
<?php echo "select companyID from Users where username='$username' && password='$password'"; ?>
<center>
<h1>Login to CAPA</h1>
<?php if (isset($message)) { echo "<p>$message</p>"; } ?>
<form name='form' method="post" action="login.php">
<table border=0>
<tr><td colspan=2>Username:</td><td><input type=text name='username' value='<?php echo $username; ?>'/></td></tr>
<tr><td colspan=2>Password:</td><td><input type=password name='password'<?php echo " value='".str_repeat(" ", $pwlength)."'"; ?> /></td></tr>
<tr><td><input type=checkbox name=remember value=1<?php if (isset($remember)) { echo " checked"; } ?> /> Remember me</td><td colspan=2 align=right><input type=submit value="Submit" /></td></tr>
<tr></tr>
</table>
</form>
</body>
</html>
Php reads 0 == false
So your code:
$result = 0;
if (!$result) {
$message = "Attempt to retrieve user credentials from database failed. Please contact the administrator.";
}
Will always be true. It's like saying:
if(!0){
echo 'true';
}
One great way to troubleshoot and debug your code is to use echo mysql_error(); to see any MySQL error messages returned from your last query. Since the output was not provided in your original post, I think your problem is that the following lines are in the incorrect place in your code:
include 'includes/global.php';
mysql_login();
They should instead be at the top of your page's code before you can attempt to use mysql_query(...);. This is assuming include/global.php includes the mysql_login() function, and the mysql_login() function correctly establishes a connection your MySQL database and selects the proper database.
In PHP, things are run line by line. So where you might think adding the include... or mysql_login() at the beginning of the "page" will work, you actually need to add them at the beginning of the "code".
You should replace your code with this:
<?php
include 'includes/global.php';
$username = (isset($_POST["username"]) ? $_POST["username"] : (isset($_COOKIE["username"]) ? $_COOKIE["username"] : ""));
$password = (isset($_POST["password"]) ? md5($_POST["password"]) : isset($_COOKIE["password"]) ? $_COOKIE["password"] : ""));
$pwlength = (isset($_POST["pwlength"]) ? strlen($_POST["pwlength"]) : (isset($_COOKIE["password"]) ? $_COOKIE["password"] : 0));
$remember = (isset($_POST["remember"]) ? 1 : (isset($_COOKIE["remember"]) ? $_COOKIE["remember"] : 0));
if (isset($username) && isset($password)) {
mysql_login();
$result = mysql_query("select companyID from Users where username='$username' && password='$password'");
if (!$result) {
...
Note: as #serialworm has pointed out setting $result = 0 will ensure your code always enters the if statement and never the else. The above is the correct way to do what you're trying to accomplish.
If the statement is valid i.e. as mentioned with &&. The only possibility is that either your table Users does not exist or you are working on a not initialized database connection. You need to have a valid mysql connection.
See mysql_connect
A few questions:
Are you connected to the DB? as I see, the commented include 'includes/global.php'; is after the mysql_query()
Is your table called Users or users? case sensitivity is important in some cases