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!
Related
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.
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.
I am trying to pass a variable from one page to another using $_GET, and I can't seem to get it to work. I would appreciate any help.
First I create a link based on the results from the database here.
clients.php
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host={$config->dbhost};dbname={$config->dbname}", $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$uid = $auth->SessionUID($_COOKIE['authID']);
$query = $dbh->prepare("SELECT fname, lname, id FROM client WHERE uid=? ORDER by id");
$query->execute(array($uid));
$rslt = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($rslt as $row ){
echo "<a href=../pages/status.php?id=$row[id]>$row[fname]<br></a>";
}
The result from the link are listed on this page
status.php
$cid = $_GET['id'];
$query = $dbh->prepare("SELECT function FROM funcbathing WHERE cid=?");
$query->execute(array($cid));
$rslt = $query->fetch(PDO::FETCH_ASSOC);
if (empty($rslt)){
header('Location: ../views/careplan.php');
echo $cid
}
else{
header('Location: ../views/home.php');
}
I would like to pass the $cid to this page in a text box, but I can't seem to get it work. Here's the page that the id should get passed to.
careplan.php this is a bigger form but I removed the irrelevant information for simplicity.
<input type="text" name="clientid" value="<?php if(isset($_GET['cid'])) { echo $_GET['cid']; } ?>" />
header('Location: ../views/careplan.php?cid='.$cid);
EDIT:
You should learn to print the strings in a valid manor, check error_reporting(E_ALL); and display_errors=on with your string.
then try this:
echo ''.$row["fname"].'<br>';
or:
echo sprintf('%s<br>', $row['id'], $row['fname']);
or even:
echo "{$row["fname"]}<br>";
or any of the other hundreds way to write a valid string
I have a simple account creation script that is not working. I know that there are no connection errors because the login works fine. Also, I turned on error-reporting (made it -1) but it shows no errors
This is my code in snippets, thanks
HTML
<form method="post">
<input type="text" name="newUsername" placeholder="Username"/>
<input type="password" name="newPassword" placeholder="Password"/>
<input type="submit" name="signUp" value="Sign Up!"/>
</form>
Then PHP:
if($_POST['signUp']) {
$username = $_POST['newUsername'];
$pass = $_POST['newPassword'];
$signedUp = SignUp($Username,$pass);
echo $signUpCode[$signedUp]; // See the SignUp function in prefunc.php
} elseif($_POST['LogIn']) {
$username = $_POST['Username'];
$password = $_POST['Password'];
$loggedIn = LogIn($username,$password);
echo $logInCode[$loggedIn];
}
$signUpCode = Array(
"-3"=>"Logged in already - can't sign up!",
"-2"=>"Username already exists!",
"-1"=>"Failed to sign up - please try again!",
"1"=>"Signed up, and logged in successfully!"
);
function SignUp($Username,$Password) {
$Username = preg_replace("/[^a-zA-Z0-9]/","",$Username);
$u = mysql_query("SELECT * FROM Users WHERE LOWER(Username)=LOWER('$Username')");
if(getCurrentId()){
return -3;
}
if(!mysql_num_rows($u)) {
mysql_query("INSERT INTO Users SET Username='$Username',Password=''$Password") or die(mysql_error());
$u = mysql_query("SELECT * FROM Users WHERE LOWER(Username)=LOWER('$Username')");
if(mysql_num_rows($u)) {
LogIn($Username,$Password);
return 1;
} else {
return -1;
}
}
return -2;
}
Are you sure you re executing the insert query?
also the query sintax is wrong, try this: insert into user ( username,password) values ('admin','1234').
finally you must fix security issue, your code is affected by sql injection
I'm trying to write a code where all SQL statements are stored inside a separate PHP file so I can call them later as functions.
I've tried different things but I can't seem to make it work properly.
Here is my code (I'm trying to make a login page here)
login.php
<?php
include('sql.php');
$sql = new sql();
?>
<form class = "form-inline" method = "post" style="color: #FFF; position: absolute; margin-top:100px; margin-left:500px;">
<table width="100%" border="0">
<tr>
<td>Username</td>
<td><input type="text" id = "username" name = "username" class="large" placeholder=""></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id = "password" name = "password" class="large" placeholder=""></td>
</tr>
</table>
<br />
<center><button type="submit" id = "submit" name = "submit" class="btn btn-primary">Log in</button></center>
</form>
<?php
//echo $sql->admin();
?>
<?php
if(isset($_POST['submit'])) {
// username and password sent from form
$username=$_POST['username'];
$password=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
//THIS IS THE PART WHERE I CALL THE SQL STATEMENT FROM A SEPARATE PHP FILE
echo $sql->admin($username,$password);
// Mysql_num_row is counting table row
$count=mysql_num_rows($sql);
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
//unset($_SESSION);
$row = mysql_fetch_assoc($sql);
$_SESSION[logged] = $row[logged];
// Register $username, $password and redirect to file "index.php"
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['submitted'] = $row[submitted];
$_SESSION['date_submitted'] = $row[date_submitted];
session_register($_SESSION['username']);
session_register($_SESSION['password']);
?>
<script>window.location="index.php";</script>
<?php
}
else
{ ?>
<center><span style="color:white;">Wrong Username or Password</span></center>
<?php
}
}
?>
sql.php
<?php
include('connect.php');
class sql{
function sql()
{
}
function admin($username,$password)
{
echo $sql=mysql_query("SELECT * FROM admin WHERE admin_username= '$username' and admin_password= '$password' ");
}
}
?>
The error that appears with this code is
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in login.php on line 40
my line 40 is
$count=mysql_num_rows($sql);
I've finally got it. As you said, I've added a line in my sql.php which is
return $result;
another reason why my code didn't work was because I didn't place my
$sql->admin($username,$password);
inside a variable. Now it looks like this
$a = $result->admin($username,$password);
and it's working now.
Like GBD told, you have to return the result set from the mysql query. Furthermore, you have to use the result in your script to handle the submission from the login page.
$result = admin($username,$password)
// Mysql_num_row is counting table row
$count = mysql_num_rows($result)
You should return result set in your function
function admin($username,$password)
{
$result=mysql_query("SELECT * FROM admin WHERE admin_username= '$username' and admin_password= '$password' ");
return $result; // return result set back
}
Your admin function should return a resultset of data:
function admin($username,$password)
{
$result = mysql_query("SELECT * FROM admin WHERE admin_username= '$username' and admin_password= '$password' ");
return $result;
}
By calling it like so:
$resultset = admin($username, $password);
You can then pass this resultset (not the sql) to mysql_num_rows:
$count = mysql_num_rows($resultset);
In login.php you used
//THIS IS THE PART WHERE I CALL THE SQL STATEMENT FROM A SEPARATE PHP FILE
echo $sql->admin($username,$password);
The parameters are send correctly, but the result of SQL should be returned from the function.
You used echo in sql.php as well as in login.php
Add return statement
function admin($username,$password)
{
$sql=mysql_query("SELECT * FROM admin WHERE admin_username= '$username' and admin_password= '$password' ");
return $sql;
}
in sql.php
$result=$sql->admin($username,$password);
and then use the variable $result as $sql is already used for CLASS
This should work.
As my predecessors said, you need to return the value from the admin function.
Besides, why do you call DB table 'admin' ? Do you plan on having multiple admins ? You shouldn't create separate tables for different types of users. You may create one table 'users' with column 'type' where you specify if he is an admin or regular user, and set his privileges based on this value.