MySQL to PDO

Hey guys, I am pretty new to PHP and i am following a tutorial to make a chatbox with login system, but it is using MySQL and i would like to use PDO.

Could someone help me convert line 2 & 3? in the code?

[code]$result = “SELECT * FROM users WHERE username=’$username’ AND password=’$password’”;
if(mysql_num_rows($result)){
$res = mysql_fetch_array($result);

	$_SESSION['username'] = $res['username'];
	echo "Success"

}
[/code]
Thanks.

Kenny

This is a good way to start:

[PHP]

<?php //The safest way is to verify the password before pulling any other data $statement = $dbconn->prepare(" SELECT password FROM users WHERE username = :username "); $statement->execute([ ":username" => $_POST['username'] ]); $result = $statement->fetchAll(PDO::FETCH_ASSOC); if (!$result){ //There is no user //I add my errors to a function with an id e.g. 1 = error, 2 = warning, 3 = success myError(2, "There is no such user"); }else { //Validate the password using password_verify -- requires the password to already be hashed using password_hash if (password_verify($_POST['password'], $result->password)) { //The password was correct you can now safely pull the users data using a new query $statement = $dbconn->prepare(" SELECT id, username, fname, email FROM users WHERE id = :id "); $statement->execute([ ":id" => $result->id ]); $result = $statement->fetchAll(PDO::FETCH_ASSOC); foreach ($result AS $row){ //Output your user details or create a session //These are the usual things I use in a session $_SESSION['SESS_USERID'] = $row['id']; $_SESSION['SESS_FNAME'] = $row['fname']; $_SESSION['SESS_EMAIL'] = $row['email']; //User is now authenticated and session is created header("Location:/My_Account/"); } }else { //The users password was incorrect myError(1, "Your password was incorrect"); } } ?>

[/PHP]

I’m sure someone already has a tutorial on here for a PDO register/login…

I first want to make this statement that the following script is NOT TESTED meaning that it probably won’t work as is. Secondly, this is just to give you a general idea on how to go about converting to PDO.

Here’s the connection part of the script (I thought this might be handy?):
[php]// Create the database connection as a PDO object:
try {

$db_options = array(
	   PDO::ATTR_EMULATE_PREPARES => false                     // important! use actual prepared statements (default: emulate prepared statements)
	   , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION           // throw exceptions on errors (default: stay silent)
	   , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC      // fetch associative arrays (default: mixed arrays)
	   ); 		 

$pdo = new PDO('mysql:host=localhost;dbname=your_database_name;charset=utf8', 'your_username', 'your_password', $db_options);	

} catch (PDOException $e) { // Report the Error!

$errMsg = "<p>Something is not right, check your php.ini settings or code</p>";

} [/php]

The login in portion of the script:
[php]if (isset($_POST[‘username’])) {

$username = $_POST['username']; // I'm assuming you pull this in from a form?

    /* Note whatever table fields that might be need you might want to add to SELECT */
$query = 'SELECT username, password FROM users WHERE username = :username';

/* The parameter values */
$query_params = array(':username' => $username);		

try
{
	// Execute the query against the database
	$stmt = $pdo->prepare($query);
	$stmt->execute($query_params);
}
catch(PDOException $ex)
{
	// Note: On a production website, you should not output $ex->getMessage().
	// It may provide an attacker with helpful information about your code. 
	die("Failed to run query: " . $ex->getMessage());
}

// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;		

// Retrieve the user data from the database.  If $row is false, then the username
// they entered is not registered.
$row = $stmt->fetch();

if($row)
{

	/* A nice password hashing library for PHP 5 (If not using PHP 5.5)
	   Find it here: https://github.com/ircmaxell/password_compat/blob/master/lib/password.php
	   Read the Documentation for further help: */

	// Verify Stored Hashed Password:
	$result = password_verify($_POST['password'], $row['password']);
	
	if ($result) {
		$login_ok = true;	
	} else {
		$errMsg = 'Invalid Credientials!';
	}
	
}

// If login is OK:
if ($login_ok) {
	
	// Unset password *Probably not needed, but I get a little paranoid at times...LOL */
	unset($row['password']);	

        // This stores the user's data into the session at the index 'user'.
	// We will check this index on the private members-only page to determine whether
	// or not the user is logged in.  We can also use it to retrieve
	// the user's details.
	$_SESSION['username'] = $row['username'];
	
            // Now redirect or display a message saying the person is now logged in
}	

}[/php]

A few other comments, the password should be encrypted by some kind of password hashing library (Don’t use your own!). Since you don’t show much code I’m just guessing and probably 99.9 percent wrong in the guess. Just change the password library hash script to an if statement and check against the password that was inputted (Very insecure by the way). Like I said I just threw it together, but if you want show more code and I’m sure someone else will gladly help you out.

Hello,
Here’s my full code (and indeed, it’s not with encryption yet… But i can do that later. Its just for learning some php).

[php]<?php
session_start();
$username = $_POST[‘username’];
$password = $_POST[‘password’];

$con = new PDO(“mysql:host=localhost;dbname=chat”, “root”, “lol”);

$sql = “SELECT * FROM users WHERE username=’$username’ AND password=’$password’”;
*** if(mysql_num_rows($result)){
*** $res = mysql_fetch_array($result);

$_SESSION['username'] = $res['username'];
echo "<center>";
echo "Je bent nu ingelogd. Klik <a href='index.php'>hier</a> om verder te gaan.";

echo “”;
}
else {
echo “”;
echo “Geen gebruiker gevonden. Probeer opnieuw.”;
echo"Je kan een nieuw account aanmaken door hierte klikken";
echo “”;
}

?>[/php] *** = to modify

Check out the link of my signature for my PDO pump start data base. It will get you on a good start with PDO.

Sponsor our Newsletter | Privacy Policy | Terms of Service