Have a look through the code below. This is supposed to check whether or not a database contains a given user. If the it does, it just returns true. If it doesn't, then it returns false.
Anyway, regardless of the user and password existing in the database, for some reason it will not evaluate to true! ! !
function databaseContainsUser($email, $password)
{
include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
try
{
$sql = 'SELECT COUNT(*) FROM wl_user
WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute("USE $dbname");
}
catch (PDOException $e)
{
$error = 'Error searching for user. ' . $e->getMessage();
include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
exit();
}
$row = $s->fetch(PDO::FETCH_NUM);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
Any help would be appreciated
For some unknown reason you are passing "USE $dbname" string to execute.
remove that string.
Also, you are trying to catch an exception but apparently don't tell PDO to throw them.
And you are catching it only to echo a message, which is a big no-no.
I've explained the right way recently in this answer
If your problem is different, you have to ask (or better - google for this very problem).
Refer to PDO tag wiki for the proper connect options including database selection and error reporting.
Try this
try
{
$pdo = new PDO('mysql:host=localhost;dbname=yourDbName;', 'root', '',
array(PDO::ATTR_PERSISTENT => true));
$sql = 'SELECT count(*) FROM user WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute();
}
This is local server example, just change yourDbName to your db name. I just run this code on my local server and it is working.
Related
one specific php/mydql command is not working. the sql will not be executed, nor do I get an error message. The sql command executed by HEIDI SQL gives me no error. Query before this command are executed correct. Only this one specific isn't working. I wrote it done one by one as the others which worked perfect before. Heres the code:
$sql = "INSERT INTO users (username,password,email) VALUES(?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->execute(array($username, $hash, $email));
The connection.php file code:
global $conn;
$config = [
$dbname = "mysql:host=localhost; dbname=starwardb;",
$login = "root",
$password = ""
];
try {
$conn = new PDO(...$config);
} catch (Exception $ex) {
echo "ERROR: " . $ex;
}
Thank you for any advice!
The mistake was, that the hashing of the password extends the string. The Database length of the password was by 50. I have increased it to 64 and now it works fine.
From: https://stackoverflow.com/revisions/45147068/3
I have a variable called $message which outputs the message contents when an action is performed to give the user some feedback however I keep getting an undefined variable error from PHP.
It's really weird because sometimes it works fine and other times it just returns the error message. Can anyone tell me what I'm doing wrong.
Just to confirm, this is a variable which is purely for storing messages. This isn't something which is "POSTED' from a form. Its generated within the PHP file itself.
An example of its usage:
<?php
session_start();
include "../includes/db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_SESSION['username'];
$sql = $db_conx->prepare("SELECT username, user_record_id FROM login_details
WHERE username = :username");
$sql->bindParam(':username', $username, PDO::PARAM_STR);
$sql->execute();
$user_record_id = $sql->fetchColumn(1);
$proposal = $_POST['proposal_id'];
$insertRec = $db_conx->prepare("INSERT INTO student_saved (proposal_id, user_record_id) VALUES (:proposal, :user_record_id)");
$insertRec->bindParam(':user_record_id', $user_record_id, PDO::PARAM_STR);
$insertRec->bindParam(':proposal', $proposal, PDO::PARAM_STR);
$insertRec->execute();
$message = "<p class='text-success'> Proposal Added To Your Favourites <span class='glyphicon glyphicon-ok'/></p>";
}
catch(Exception $e)
{
if( $e->getCode() == 23000)
{
$message = 'This proposal has already been saved to your favourites';
}
else
{
$message = $e->getMessage();
}
}
die($message);
?>
Any help would be much appreciated!
Found lots of similar problems on this site, but the solutions for those issues don't seem to reply. The user in question has full access to the database, and from what I can tell I'm not missing any commas etc. A second set of eyes would be great.
Submitted signature is in an acceptable formatTrying to open a connectionError!: SQLSTATE[42000] [1044] Access denied for user 'emkinsti_user1'#'localhost' to database 'signatures'
<?php
// Tracks what fields have validation errors
$errors = array();
// Default to showing the form
$show_form = true;
// 1. Get the input from the form
// Using the PHP filters are the most secure way of doing it
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$output = filter_input(INPUT_POST, 'output', FILTER_UNSAFE_RAW);
// 2. Confirm the form was submitted before doing anything else
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 3. Validate that a name was typed in
if (empty($name)) {
$errors['name'] = true;
}
// 3. Validate that the submitted signature is in an acceptable format
if (!json_decode($output)) {
$errors['output'] = true;
}
}
// No validation errors exist, so we can start the database stuff
if (empty($errors)) {
echo "Submitted signature is in an acceptable format";"<br/>";
$dsn = 'mysql:host=localhost;dbname=signatures';
$user = 'emkinsti_user1';
$pass = '6nqq103t26';
}
// 4. Open a connection to the database using PDO
try {
echo "Trying to open a connection";
$db = new PDO($dsn, $user, $pass);
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// Make sure we are talking to the database in UTF-8
$db->exec('SET NAMES utf8');
// Create some other pieces of information about the user
// to confirm the legitimacy of their signature
$sig_hash = sha1($output);
$created = time();
$ip = $_SERVER['REMOTE_ADDR'];
// 5. Use PDO prepare to insert all the information into the database
$sql = $db->prepare('INSERT INTO signatures (signator, signature, sig_hash, ip, created)
VALUES (:signator, :signature, :sig_hash, :ip, :created)');
$sql->bindValue(':signator', $name, PDO::PARAM_STR);
$sql->bindValue(':signature', $output, PDO::PARAM_STR);
$sql->bindValue(':sig_hash', $sig_hash, PDO::PARAM_STR);
$sql->bindValue(':ip', $ip, PDO::PARAM_STR);
$sql->bindValue(':created', $created, PDO::PARAM_INT);
$sql->execute();
// 6. Trigger the display of the signature regeneration
$show_form = false;
// mysql_close($db);
$db = null;
?>
emkinsti_user1'#'localhost' to database 'signatures'
if you are using CPanel, CPanel uses prefixes also to the database name:
You used: emkinsti_user1 as users.
You should use: emkinsti_signatures as database name.
Log in into your CPanel and there you will find the database name with prefix
Try http://php.net/manual/en/pdo.getavailabledrivers.php to see if the database is supported by PDO.
<?php
print_r(PDO::getAvailableDrivers());
?>
Just an idea. I would expect another error message when it isn't. So, as far as I can tell, the user has no access when accessing the database from the local host.
Hey Everyone it has been awhile wince I've worked with try/catch blocks but I would like to start using them again just for purpose of error handling and proper practices. My code is below,
$email_code = $_REQUEST['code']; //retrive the code from the user clicked link in the email
//database information
$dsn = 'mysql:host=localhost;dbname=primarydb';
$username = 'root';
$password = '';
try {
//option for PDO allows for prepared SQL statements that will mazimize the prevention of sql injections and malicious attacks on the server and databases
$conn = new PDO($dsn, $username, $password); //establish the connection
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //disable the php parse from parsing the statements.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //allow error mode to be active in order to display any errors which may open up holes to attacks
//if the connection fails the try/catch block will pick it up
if (!$conn) {
throw new PDOException('Fatal error on connection');
} else {
//prepare and exexcute the query to match the codes up
$stmt = $conn->prepare("SELECT email_code, active from primarydb.user WHERE email_code = ?");
$stmt->bindParam(1, $email_code, PDO::PARAM_STR, 32);
//check to make sure that the statment executes properly
if (!$stmt->execute()){
throw new PDOException("PDO ERROR ON EXECUTION:\n" . $stmt->errorInfo());
} else { //statement has not failed
//get the row count
$count = $stmt->rowCount();
//traverse the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//there can only be one!
if ($count != 1 || $row['active'] != 0) {
//generate error message
throw new PDOException("Wrong Code");
} else {
echo "working";
//prepare the update statement
$stmt = $conn->prepare("UPDATE primarydb.user SET active = ? WHERE email_code = ?");
$stmt->brindParam(1, 1, PDO::PARAM_INT);
$stmt->bindParam(2, $email_code, PDO::PARAM_STR, 32);
if (!$stmt->execute()) {
throw new PDOException("We're sorry but we can not update your profile at this time, plesae try again later. If this problem persists please contact customer service.");
} else {
print "Your account has now been activated and it is ready to use!";
}
}
}
}
}
} catch(PDOException $e){
//display error message if the database has failed in some manner
echo $e->getMessage();
}
I would like to know why I am not getting any of the error messages, and then how do I fix this problem so that I can avoid making the same problems again in the future. If there is something that is missing or if more information is needed please let me know. Otherwise I think it is pretty straight forward.
ADDITIONAL INFO: I have putt a message that says working at each block of if/else and the one it finally stops showing up at is when I check if($count != 1 || $row['active'] != 0)
UPDATE
<?php
$email_code = $_REQUEST['code']; //retrive the code from the user clicked link in the email
//database information
$dsn = 'mysql:host=localhost;dbname=primarydb';
$username = 'root';
$password = '';
try{
//option for PDO allows for prepared SQL statements that will mazimize the prevention of sql injections and malicious attacks on the server and databases
$conn = new PDO($dsn, $username, $password); //establish the connection
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //disable the php parse from parsing the statements.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //allow error mode to be active in order to display any errors which may open up holes to attacks
//prepare the update statement
$stmt = $conn->prepare("UPDATE primarydb.user SET active = ? WHERE email_code = ?");
$stmt->bindParam('is', $a = 1, $email_code);
if($stmt->execute()){
print "Your account has now been activated and it is ready to use!";
}
} catch(PDOException $e){
//display error message if the database has failed in some manner
echo $e->getMessage();
}
?>
Generated new code, I don't want to get off topic, but I would like a complete solution to this problem. I am now getting the following error
Strict Standards: Only variables should be passed by reference in C:\inetpub\wwwroot\mjsite\login\complete_registration.php on line 14
SQLSTATE[HY000]: General error: 2031
Thoughts?
Please read this first line from the PDOException documentation:
Represents an error raised by PDO. You should not throw a PDOException
from your own code.
Just throw and catch regular old Exceptions. This would also catch a PDOException which inherits from it.
This also gives you a much better way to distinguish between actual exception thrown by PDO and your own exceptions. By the way, it would seem you have a number of cases where you are redundantly throwing exception when PDO would have encountered an error and thrown an exception anyway. Only the first exception will be caught, so in many of those cases, your throw would never be executed.
Also why bother with the SELECT before the update at all? YOu are basically just wasting a query because you aren't doing anything with the selected information. Perhaps just go straigth for update and handle cases where email_code doesn't exist.
Alright, so I'm building a new app, and have decided to use PDO for database access. (I'm completely new to PDO, but am under the impression that it is the best way to go about db access).
Right now, my login script is incredibly simple. It checks the database for a user with the given username (from the login form), attempts to match the given password with the stored one in plain text (no encrypting/decrypting yet), and redirect the user as necessary. Here is a simple sequence diagram:
Login Screen ---(user enters credentials)--->Login Handler---(gets user details and compares pw)-->if (pw == stored pw)--->dashboard / else --->login w/ error msg
Sorry if that's hard to read, I wasn't sure the best way to represent the flow...anyways...
Here's my issue: I input the correct username and password (case sensitive even!), and am always redirected back to the login screen with the error message. However, if I simply go to the dashboard via the url bar, I am not redirected back to the login screen (as I should be if no session is set), and my username is displayed in the navigation bar (as if I had logged in correctly).
Again, sorry if this is hard to follow. Its sort of difficult to simply explain. If this is an issue, I can perhaps do a screencast of sorts to explain better. Either way, here is my code:
loginHandler.php
if(!isset($_POST['username']) || !isset($_POST['password'])){
header('Location: login.php?error=pass');
}
$username = $_POST['username'];
$pass = $_POST['password'];
//TODO: crypt password
try{
$DB = new PDO("mysql:host=127.0.0.1;port=8889;dbname=cTix", 'root', 'root'); //TODO: change this when uploading to webserver
$STH = $DB->prepare("SELECT * FROM users WHERE username = $username LIMIT 0, 1");
$STH->setFetchMode(PDO::FETCH_OBJ);
$STH->execute();
$u = $STH->fetch();
if($pass == $u->password){
session_start();
$_SESSION['uid'] = $u->id; //TODO: securely store uid
header('Location: index.php');
} else {
//echo 'Your Password: ' . $pass . ' - Correct Password: ' . $u->password;
header('Location: login.php?error=pass');
}
} catch(PDOException $e){
//echo $e->getMessage();
header('Location: login.php?error=true');
exit;
}
here is code that is retrieving the username for dashboard.php:
function connection(){
$host = 'localhost';
$dbname = 'cTix';
$user = 'root';
$pass = 'root';
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
return $DBH;
} catch(PDOException $e){
echo $e->getMessage();
return null;
}
}
function getUserById($id){
$DB = connection();
$STH = $DB->query("SELECT * FROM users WHERE id = $id");
$STH->setFetchMode(PDO::FETCH_OBJ);
$u = $STH->fetch();
$DB = null;
return $u;
}
function getUserName(){
echo getUserById(getCurrentUserId())->name;
}
If there is any other information I can offer, or anything I can provide that would be more helpful, please let me know!
Unfortunately, without this stupid login issue figured out, I can't make any headway on this app, so any help would be greatly appreciated! Thanks SO!
Here's where your problem is:
$STH = $DB->prepare("SELECT * FROM users WHERE username = $username LIMIT 0, 1");
You're concatenating the username into your SQL string, but not quoting it out. I suspect that this will fix the problem:
$STH = $DB->prepare("SELECT * FROM users WHERE username = '$username' LIMIT 0, 1");
HOWEVER
You should look into how to use bound parameters. You're already using PDO, but you're still writing user-entered code in your SQL, and bound parameters avoid that - it would also have avoided this problem, too.
This ought to work, but I've not tested it:
$STH = $DB->prepare('SELECT * FROM users WHERE username = ? LIMIT 0, 1');
$STH->bindParam(1, $username);
$STH->setFetchMode(PDO::FETCH_OBJ);
$STH->execute();