PDO Insert not working with bindParam - php

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.

Related

PDO Username validation if already exists

I have a problem with register form.My form works properly but whenever i try to insert username that already exists it doesn't shows any error.
here is my php register file:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=dblogin", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
else{
$insert = $conn->prepare("INSERT INTO users (user_name,user_email,user_pass) values(:user_name,:user_email,:user_pass)");
$insert->bindparam(':user_name',$user_name);
$insert->bindparam(':user_email',$user_email);
$insert->bindparam(':user_pass',$hash);
$insert->execute();
}
}
catch(PDOException $e)
{
echo "connection failed";
}
?>
Thanks for your support
You are not executing the select statement. You need to bind params and execute the select statement, try this after the select statemnt.
$stmt->bindparam(':user_name',$user_name);
$stmt->execute();
public function usernameCheck($username)
{
$sql = "SELECT * FROM $this->table where username = :username";
$query = $this->pdo->prepare($sql);
$query->bindValue(':username', $username);
$query->execute();
if ($query->rowCount() > 0) {
return true;
} else {
return false;
}
}
use this one in your project hope it will work... :)
missing } in if statement
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
}else{
}
I notice 4 things (2 of which have been mentioned by others):
First and smallest is you have a spelling error ($con instead of $conn) - don't worry it happens to the best of us - in you first $stmt query which means your select-results becomes NULL instead of 0 - so you rowCount find that it is not over 0 and moves on without your error message
Second you forgot to bind and execute the parameters in your first $stmt query which gives the same result for your rowCount results
Third always clean your variables even when using prepared statements - at a bare minimum use
$conn->mysql_real_escape_string($variable);
and you can with advantage use
htmlspecialchars($variable);
And fourth since you are not doing anything with the database (other than looking) you could simplify your code by simply writing:
$stmt = $conn->query("SELECT user_name FROM users WHERE user_name = '$user_name' LIMIT 1")->fetch();
as I said - no need to bind or execute in the first query
and as a general rule - don't use rowCount - ever - if you have to know the number of results (and in 99% of cases you don't) use count(); but if you as here just want to know if anything at all was found instead use:
if ( $stmt ) {
echo "exists!";
} else {
// insert new user as you did
}
Edit:
Also - as a side note - there are a few things you should consider when you initially create your connection...
Ex:
// Set variables
$servername = "localhost";
$username = "***";
$password = "***";
$database = "***";
$charset = 'utf8'; // It is always a good idea to also set the character-set
// Always create the connection before you create the new PDO
$dsn = "mysql:host=$servername;dbname=$database;charset=$charset";
// Set default handlings as you create the new PDO instead of after
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // And add default fetch_mode
PDO::ATTR_EMULATE_PREPARES => false, // And ALWAYS set emulate_prepares to false
];
// And now you are ready to create your new PDO
$conn = new PDO($dsn, $username, $password, $opt);
Just a suggestion... happy trails

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

Switch from mysql_connect to PDO: mysql_num_rows() expects parameter 1 to be resource

I had code that used mysql_connect which I understand is now deprecated to I switched to the following code (I'm working locally):
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$DBusername = 'admin';
/*** mysql password ***/
$DBpassword = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
But this now means that a function of mine breaks:
$result = mysql_num_rows($query);
Because, following the script back, the connection is not working. There is something up with my PDO connection script but I do not understand what I have done wrong. The details are correct for logging into phpMyAdmin on localhost.
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
PDO is entirely independent from the mysql extension, you will have to update your function calls as well. mysql_query for example should be a combination of prepare and execute.
As a note: Please please use Prepared Statements, your example query is completely insecure.
As an example was requested:
// initialize PDO
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
// Prepare a query
$sql = "SELECT COUNT(*) AS count
FROM users
WHERE username = ?
LIMIT 1";
$statement = $dbh->prepare($sql);
// execute the query
$statement->execute(array($username));
// retrieve the first row
$row = $statement->fetch();
if ($row['count']) echo 'The user exists';
else echo 'The user does not exist';

PHP login script always returns "login failed"

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.

PHP mysql_real_escape_string(); whats the correct method using mysqli?

its a little difficult to explain. I've build the mysql function which works fine and with the depreciation of mysql I will need to change this function to use mysqli rather than the mysql method.
I current have:
$con = mysql_connect("host", "username", "pass");
mysql_select_db("db", $con);
$Username = mysql_real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$Query = mysql_query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'") or die(mysql_error());
$Query_Res = mysql_fetch_array($Query, MYSQL_NUM);
if($Query_Res[0] === '1')
{
//add session
header('Location: newpage.php');
}
else {
echo 'failed login';
}
Now I've applied mysqli to this and it's not returning any data or errors but the function still complies.
$log = new mysqli("host", "user", "pass");
$log->select_db("db");
$Username = $log->real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$qu = $log->query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'");
$res = $qu->fetch_array();
if($res[0] === '1'){
//add session
header('Location: newpage.php');
}
else {
$Error = 'Failed login';
sleep(0.5);
}
echo $res['username'].' hello';
}
But I'm unsure on why this is wrong. I know it's probably a simply answer
Just to have it as an answer:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.prepare.php
e.g.
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
You may check if the connection is establishing before using real_escape_string()
if ($log->connect_errno) {
echo "Failed to connect to MySQL: (".$log->connect_errno.")".$log->connect_error;
}
afaik, there's no problem with $log->real_escape_string($_POST['user']);

Categories