PHP Retrieiving Column Data from database - php

I have an earlier post here
But NONE of those answers worked. So here's my entire class code:
<?php
session_start();
class Mysql {
private $conn;
function __construct() {
$this->conn = new PDO('mysql:host=***;dbname=***;charset=UTF-8','***','***') or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT Username
FROM Conference
WHERE Username = :un AND Password = :pwd";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':un', $un);
$stmt->bindParam(':pwd', $pwd);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// User exist
$stmt->bindColumn('First Name', $firstName);
$_SESSION["FirstName"] = $firstName;
die($_SESSION["FirstName"]);
return true;
$stmt->close();
}
else {
// User doesn't exist
//die("failure");
return false;
$stmt->close();
}
}
}
?>
I've tried fetch, i've tried bind_result, etc and none of them print the correct value on the die statement. Now this worked when i stored username in session and tried to print that. What is wrong with the code?

You aren't calling the code in the snippet. What's the call procedure?
You aren't retrieving Conference.First Name only Conference.Username so you should be getting a warning unless you're not displaying errors. You probably want
"SELECT * FROM Conference...."
or
"SELECT FirstName From Conference WHERE Username = :un AND Password = :pwd";
It's possibly Conference.FirstName.
die(); is not very useful for debugging. Try var_dump($_SESSION["FirstName"]); die();

I have looked at your code, and made a working version on my own server. If you have any questions, feel free to ask.
class Mysql
{
private $conn;
public $error;
public $username;
function __construct()
{
try {
$this->conn = new PDO( 'mysql:host=localhost;dbname=****', 'root', '****' );
$this->conn->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
}
catch ( Exception $e ) {
$this->error = $e->getMessage();
}
}
function verify_Username_and_Pass( $un, $pwd )
{
$query = "SELECT Username
FROM Conference
WHERE Username = :un AND Password = :pwd";
$stmt = $this->conn->prepare( $query );
if( !$stmt ) {
$this->error = $this->conn->errorInfo();
return false;
}
$stmt->bindParam( ':un', $un );
$stmt->bindParam( ':pwd', $pwd );
$stmt->execute();
if ( $stmt->rowCount() > 0 ) {
// User exist
$this->username = $stmt->fetchColumn();
return true;
}
else {
// User doesn't exist
return false;
}
}
}
session_start();
$db = new Mysql();
if( !$db->error ) {
if( $db->verify_Username_and_Pass ( 'user', 'test' )) {
$_SESSION["FirstName"] = $db->username;
}
else
echo 'Unknown user';
}
var_dump( $db );
The script will output this:
Unknown user
object(Mysql)#1 (3) {
["conn":"Mysql":private]=> object(PDO)#2 (0) { }
["error"]=> array(3)
{ [0]=> string(5) "42S02"
[1]=> int(1146)
[2]=> string(39) "Table 'xxxx.Conference' doesn't exist" }
["username"]=> NULL }

Related

bcrypt algorithm failed to login

I use
password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
for my signup form. It's okay in database save perfectly, but can't login.
This is my login function
public function Login($user, $password)
{
try {
$db = DB();
$query = $db->prepare("SELECT id FROM members WHERE user=:user AND password=:password");
$query->bindParam("user", $user, PDO::PARAM_STR);
$data = $this->query->single();
$getpass = $data['password'];
$passv = password_verify($password, $getpass);
$query->bindParam("password", $passv, PDO::PARAM_STR);
$query->execute();
if ($query->rowCount() > 0) {
$result = $query->fetch(PDO::FETCH_OBJ);
return $result->id;
} else {
return false;
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
EDIT:
login.php
<?php
// Start Session
session_start();
// Database connection
require __DIR__ . '/database.php';
$db = DB();
// Application library
require __DIR__ . 'inc/functions.php';
$app = new DemoLib();
// check Login request
if (!empty($_POST['login'])) {
$user = trim($_POST['user']);
$password = trim($_POST['password']);
if ($user == "") {
echo 'Please enter username.';
} else if ($password == "") {
echo 'Please enter password.';
} else {
$id = $app->Login($user, $password); // check user login
if($id > 0)
{
$_SESSION['id'] = $id; // Set Session
}
else
{
echo 'Wrong data.';
}
}
}
?>
You don't want to try to match the password during the query as matching the hash would not work. In order to verify the password you will want to do something like this:
public function Login($user, $password)
{
try {
$db = DB();
$query = $db->prepare("SELECT * FROM members WHERE user=:user"); // get everything for the user
$query->bindParam("user", $user, PDO::PARAM_STR);
//$data = $this->query->single();
$data = $query->execute();
$getpass = $data['password'];
$passv = password_verify($password, $getpass);
if ($passv) { // if the password is good
return $data['id'];
} else {
return false;
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}

How can I fix this MySQL Code

How can I fix the following code?
function userExists($pdow, $login)
{
$userQuery = "SELECT * FROM login u WHERE login=:user;";
$stmt = $pdow->prepare($userQuery);
$stmt->execute(array(':user' => $login));
return !!$stmt->fetch(PDO::FETCH_ASSOC);
}
$login = 'user';
$exists = userExists($pdow, $login);
if('$login')
$user= var_dump((bool) 'Exists');
{
echo "Login exsists!";
}
I have two problems with my code.
First error:
Error with echoing 'login exsists!'. I see this echo all the time in browser.
Second error:
When I get echo 'login exsists!' my code still inserts data to database.
Simply:
$servername = '';
$dbname = '';
$username = '';
$password = '';
$dbh = new PDO("mysql:host={$servername};dbname={$dbname}", $username, $password);
function user_exists($dbh, $Login) {
$Q = $dbh->prepare("SELECT * FROM login WHERE login = :Login");
$Q->bindParam(':Login', $Login);
$Q->execute();
return $Q->fetch(PDO::FETCH_ASSOC);
}
//Lets try:
$user = user_exists($dbh, 'email#example.com');
if ($user) {
echo 'User: ' . $user['login'] . ' was found in the database.';
} else {
echo 'The user was NOT found.';
}
if($login)
// this line doesnt make any sense!
// $user= var_dump((bool) 'Exists');
// so this is not a valid if clause
{
echo "Login exsists!";
}`
try {
$pdow = new PDO('mysql:host=localhost;dbname=log_cdr', 'root', 'slawek132');
$pdow -> query ('SET NAMES utf8');
$pdow -> query ('SET CHARACTER_SET utf8_unicode_ci');
$pdow->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlw = "INSERT INTO login (login, pass, pass_v, email, email_v)
VALUES ('".$_POST["login"]."','".$_POST["pass"]."','".$_POST["pass_v"]."','".$_POST["email"]."','".$_POST["email_v"]."')";
function user_exists($login) {
$Q = pdow()->prepare("SELECT * FROM login WHERE login = :Login");
$Q->bindParam(':login', $Login);
$Q->execute();
if ($Q->rowCount() != 0) {
//User exist:
return $Q->fetch(PDO::FETCH_ASSOC);
} else {
//User doesn't exist.
return false;
}
}

PHP get the email of a user currently logged in

I have a problem. I want to get the email of a user, the email is a special column in a table called users in my database. I created a login-system that is working well, but I still want to get the e-mail of the user who is currently logged in.
I am really new to php and mysql. :(
This is my code in login.php:
<?php
require 'Mysql.php';
class Membership {
//Check if input is correct
function validate_user($un, $pwd) {
$mysql = New Mysql();
$ensure_credentials = $mysql->verify_Username_and_Pass($un, $pwd);
//input correct
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION["username"] = $un;
$_SESSION["email"] = $ensure_credentials['email'];
header("location: ?status=authorized");
}
function log_User_Out() {
if(isset($_SESSION['status'])) {
unset($_SESSION['status']);
if(isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time() - 10000);
session_destroy();
}
if(isset($_SESSION["username"])) {
unset($_SESSION["username"]);
}
if(isset($_SESSION["email"])) {
unset($_SESSION["email"]);
}
}
}
and here from Mysql.php:
<?php
require "/data/logindata/constants.php";
class Mysql {
private $conn;
function __construct() {
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT *
FROM users
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
$stmt->bind_result($username, $email); // the columns fetched with SELECT *
if (!$stmt->fetch()) {
return false;
}
return array(
'username' => $username,
'email' => $email
);
}
return false;
}
}
Instead of returning a boolean, you may return some user data with verify_Username_and_Pass function. There you can include authenticated user's email:
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT username, password
FROM users
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
$stmt->bind_result($username, $email); // the columns fetched with SELECT *
if (!$stmt->fetch()) {
return false;
}
return array(
'username' => $username,
'email' => $email
);
}
return false;
}
....
$ensure_credentials = $mysql->verify_Username_and_Pass($un, $pwd);
//input correct
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION["username"] = $un;
$_SESSION["email"] = $ensure_credentials['email'];
header("location: ?status=authorized");
}
First of all be sure to sanitize every variable inserted by final users.
It's very important to sanitize your variable to avoid SQL injection.
Then on the Session variable user I'm gonna save the user Id and to get his/her email I'm gonna make a function that should receive the session id to return an email.
Now I'm gonna write a couple of functions that could be useful:
function logged() {
return (isset($_SESSION['id_user'])) ? true : false;
}
function getEmail($userId) {
$userId = sanitize(userId);
$query = "SELECT userEmail FROM users WHERE id_user =" . $userId;
$name = mysql_result(mysql_query($query), 0);
return $name;
}
function sanitize($data) {
return mysql_real_escape_string($data);
}

INSERT INTO called from a php script fails

I am having an ios app and I am calling a script from my online server, in order to insert a value into a table.
In this code:
//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//success
login($user, $pass);
} else {
//error
errorJson($result['error']);
}
I always get into the else clause and it is printed Database error.
Note: errorJson is a function that makes a json output from a string in order to send it back to the iphone app.
A normal select from where plays normally, so there is no chance that I am not connected to the DB.
The whole code is here:
function register($user, $pass) {
//check if username exists
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
errorJson('Username already exists');
}
//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (! $result['error']) {
//success
login($user, $pass);
} else {
//error
errorJson($result['error']);
}
}
If the username exists the NSLog above is printed normally, so I guess I can connect to the DB.
and this is my query function:
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysql_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysql_query($link, $sql);
if (mysql_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysql_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
Your syntax is wrong, should be:
mysql_query($sql, $link):
Right syntax: mysql_query ( string $query [, resource $link_identifier = NULL ] )

MySQLi Num Rows Doesnt Work

i have a simple login system and i get nothing when trying to fetch the number of rows, the same method used to work all the time, i dont know what is going on today.
Code:
<?php
class LoginClass {
public $User;
public $Pass;
public $Query;
function Init() {
$User = $this->User;
$Pass = $this->Pass;
if($User != '')
{
if($Pass != '')
{
$this->HashPass();
}
else
{
echo 'Please Enter A Password.';
}
}
else
{
echo 'Please Enter A Username or E-Mail.';
}
}
function HashPass() {
$Pass = $this->Pass;
$this->Pass = hash('sha256', $Pass);
$this->CheckUser();
}
function CheckUser() {
$User = $this->User;
if(!filter_var($User, FILTER_VALIDATE_EMAIL))
{
$this->Query = 'SELECT * FROM Users WHERE User = "'.$User.'" AND Pass = "'.$this->Pass.'"';
}
else
{
$this->Query = 'SELECT * FROM Users WHERE EMail = "'.$User.'" AND Pass = "'.$this->Pass.'"';
}
$this->CheckDB();
}
function CheckDB() {
$Query = $this->Query;
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Stmt = $Connect->prepare($Query)
$Stmt->execute();
$Stmt->store_result();
echo $Stmt->num_rows;
$Stmt->close();
$Connect->close();
}
function SetupSession() {
echo 'Test';
}
}
the Check DB is the problem here and im able to echo out the query variable in that function everything is fine, here is exactly what i get
SELECT * FROM Users WHERE User = "Test" AND Pass = "532eaabd9574880dbf76b9b8cc00832c20a6ec113d682299550d7a6e0f345e25"
I also checked my DB and all my tables are setup correctly and there is no password.
OK, need more space than the comments area, the issue is clearly in this block:
function CheckDB() {
$Query = $this->Query;
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Stmt = $Connect->prepare($Query)
$Stmt->execute();
$Stmt->store_result();
echo $Stmt->num_rows;
$Stmt->close();
$Connect->close();
}
I think it's because you aren't binding parameters to the prepared statement, you've already included them inline in your earlier statement. Therefore, you probably want to:
Switch to non-prepared statement
The easy option here will be to switch to a non-prepared statement. Replace your block with:
function CheckDB() {
$Query = $this->Query;
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Stmt = $Connect->query($Query)
echo $Stmt->num_rows;
$Stmt->close();
$Connect->close();
}
A word of caution with this approach: you need to sanitize your user input in the block which defines $User, otherwise you're leaving yourself open to mysql injection. In that block, change this line:
$User = $this->User;
To the following:
$User = mysql_real_escape_string($this->User);

Categories