Convertion from mysql to PDO - php

So i have decided that its time to modernize my code by updating some of my script from mysql to PDO. Ihave used the last days trying to get to know PDO better, but i cant relate the examples that i have found to my script.
Database Connection:
mysql_connect('localhost', 'root', '') or die ('The server is facing issues at the moment');
mysql_select_db('openchat') or die('Problem with connecting to the database');
Php function with db connection included:
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `user` WHERE `username` = '$username'"), 0) == 1) ? true : false;
}
The function checks if the user already exists, where $username is the posted username in a form, and the function checks if the username is taken or not.
I am just showing a small part of the code so i hope this is enough information to get the code :)
Update
I think i finnaly have made an updated version that works!
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=openchat', 'user', 'user123');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
die('The server is facing issues' . '</br>' . $e->getMessage());
}
function test() {
global $db;
$query = $db->query("SELECT COUNT(`user_id`) FROM `user` WHERE `username` = 'testbruker'");
$result = $query->fetchColumn();
return ($result == 1) ? true: false;
}

You can try something like that. But I recommand you to store your DB information in a safe place. But this should do the work.
try{
$db = new Database($host,$username,$password,$database);
$user = 'This user';
$sql = "SELECT COUNT (user_id) FROM users WHERE username = ?;";
$result = $db->prepare($sql);
$result ->execute(array($user));
if ($result ->rowCount() > 0) {
echo 'The user is present';
} else {
echo 'There is nothing';
}
}
catch (Exception $e){
die('Error : ' . utf8_encode($e->getMessage()));
}

Related

PDO Insert not working with bindParam

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.

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

PHP PDO:Login System

I am working on a PHP PDO Login system but i keep getting an error, perhaps some part of my code is incorrect.
//LOG IN VERIFICATION
if (isset($_POST['username'],$_POST['pass'])) {
try {
$con = new PDO("mysql:host=" . host . ";dbname=" . database, user, auth);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!empty($_POST['username'])&& !empty($_POST['pass'])) {
//username and password sent from Form
$usernames = trim($_POST['username']);
$password = $_POST['pass'];
$select= $con -> prepare("SELECT username,password FROM users WHERE username='$username' AND password='$password'");
$select ->execute();
$results = $select->fetch(PDO::FETCH_ASSOC);
if (count($results) > 0 && password_verify($password, $results['password'])) {
header('location:home.php');
} else{
header('location:login.php');
}
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
I suspect the error to be here
$select= $con -> prepare("SELECT username,password FROM users WHERE username='$username' AND password='$password'");
$select ->execute();
$results = $select->fetch(PDO::FETCH_ASSOC);
because i verified the connection to the database. Any help will be appreciated.
You're assigning to $usernames, not $username. However, the real problem is count($results) - you cannot count the rows this way. Which means, the count will be 0, hence the else branch is executed. See here: Row count with PDO.
Edit: In such cases, simply debug your code and var_dump(count($results)), for example. You have a simple if statement - if an unexpected branch is executed, something is wrong with the if condition.

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 form will not login a user with correct credentials [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a php form that when the user submits with incorrect credentials gets appropriate error messages but when using correct credentials does not get login success message just the same incorrect credentials message. I have tried with both hashing password and without no luck. Here is my login function code:
function login($username, $password) {
$host = 'localhost';
$user = 'jamaixan_bobsled';
$pass = 'v67fvg7gk_&g';
$db = 'db_for_site_67';
mysql_connect($host, $user, $pass);
mysql_select_db($db);
$connected = mysql_select_db($db);
$user_id = user_id_from_username ($username);
$password = md5($password);
return(mysql_result(mysql_query("SELECT COUNT(`id_user`) FROM `table_of_users` WHERE
`email_user` = `$username` AND `password_user` = `$password`") , 0) == 1) ? $user_id : `false`;
}
You shouldn't put username and password value in backticks, put them in quotes. You even placed false in backticks. Do like this :
$result = mysql_query("SELECT COUNT(`id_user`) FROM `table_of_users` WHERE
`email_user` = '$username' AND `password_user` = '$password'");
return (mysql_num_rows($result)>0) ? $user_id : false;
I recommend you to use PDOs, a more secure way to handle DB request. mysql_* functions are deprecated.
http://www.php.net/manual/en/book.pdo.php
Use mysqli_* or pdo... mysql is deprecated
function login($username, $password)
{
$cn = mysqli_connect('localhost', 'jamaixan_bobsled', 'v67fvg7gk_&g', 'db_for_site_67') or die('Connection error!');
$SQL = "SELECT COUNT(id_user) FROM table_of_users WHERE email_user = '%s' AND password_user = '%s'";
$Query = sprintf($SQL, mysqli_real_escape_string($username), md5($password));
$Result = mysqli_query($cn, $Query) or die( mysqli_error($cn) );
$Rows = mysqli_fetch_array($Result);
return ( isset($Rows[0]) && ($Rows[0] > 0) );
}
function connectdb()
{
$dbhost='localhost';
$dbname='db_for_site_67';
$dbuser="jamaixan_bobsled";
$pwd="v67fvg7gk_&g";
try
{
$db=mysql_connect($dbhost,$dbuser,$pwd);
if($db)
{
try
{
$dbselect=mysql_select_db($dbname,$db);
if(!$dbselect)
{
throw new Exception("Unable to select database: $dbname with error ". mysql_error());
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
else
{
throw new Exception("Unable to connect to database with error ". mysql_error());
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
return $db;
}
function login($username, $password) {
$user_id = user_id_from_username ($username);
$password = md5($password);
$conn1=connectdb();
$sql1="SELECT COUNT(`id_user`) FROM `table_of_users` WHERE `email_user` = $username AND `password_user` = $password";
$res1=mysql_query($sql1);
$res1=mysql_fetch_array($res1);
$res1=$res1['COUNT(`id_user`)'];
if($res1==1){
echo "login sucessful";
} else {
echo "login Failed";
}
}

Categories