Login script using PDO extension not working - php

I am unsure if I am doing it properly but I just started working with PDO and I am not able to get my code to work. I continue to get the error "sorry could not connect" and I am unable to figure out what is wrong.
Included below is the code that I am using:
function doRun( $data )
{
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare(' SELECT
username, pass
FROM
testTable
WHERE
username = :name
AND
pass = :pass
');
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$stmt->execute();
//$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $stmt->fetchColumn();
if($result == false)
{
echo 'sorry could not connect';
}
else
{
$_SESSION['username'] = $user;
echo 'logged in as' . $user;
}
}
catch (PDOException $e)
{
echo "throw";
}
$db = NULL;
}

This would give you 0 rows as it seems that $username and $pass are not defined:
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
^^^^^^^^^
You probably want some elements from $data variable you are feeding to the function as a username and password.
Later on you are using a variable $user that is undefined as well.
What does $data contain?

The reason that you are "unable to connect", even though you are connecting but you're not finding a match, is because your user variables are not defined.
Try the following solution:
<?php
function doRun( $data )
{
$msg = '';
$username = isset($_POST['name']);
$pass = isset($_POST['pass']);
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('
select
username
,pass
from
testTable
where
username = :name
and pass = :pass
');
$stmt->execute(array(':name' => $username, ':pass' => $pass);
$result = $stmt->fetchAll();
if(!empty($result)){
$_SESSION['username'] = $user;
$msg = "logged in as $user";
}else{
$msg = "Unable to connect";
}
} catch (PDOException $e) {
echo "Error: $e";
}
echo $msg
$db = NULL;
}
?>

Related

Can't figure out this bindParam issue

I'm trying to fetch some data from a MySql db using PDO but no matter what I do, I can't get anything when using a prepared statement... please tell me what I'm doing wrong.
The following code runs but returns nothing.
try {
$dbh = new PDO('mysql:host=localhost;dbname=banim', 'root', '');
$uName = "banim"; //$_POST['uName'];
$email = "Rabak#gmail.com"; //$_POST['email'];
$query = $dbh->prepare("SELECT * from users WHERE email = :email OR WHERE uName = :name");
$query->setFetchMode(PDO::FETCH_ASSOC);
$query->bindParam(":name", $uName);
$query->bindParam(":email", $email);
$query->execute();
foreach ($query as $row) {
print_r($query);
}
} catch (PDOException $e) {
echo "PDOException: " . $e->getMssage() . PHP_EOL;
}
What Alive To Die wrote was correct, and there was also an extra WHERE in the SQL string which also messed up the answer, this is the final code:
try {
$dbh = new PDO('mysql:host=localhost;dbname=banim', 'root', '');
$uName = "banim"; //$_POST['uName'];
$email = "Rabak#gmail.com"; //$_POST['email'];
$query = $dbh->prepare("SELECT * from users WHERE email = :email OR uName = :name");
$query->setFetchMode(PDO::FETCH_ASSOC);
$query->bindParam(":name", $uName);
$query->bindParam(":email", $email);
$query->execute();
while($row = $query->fetch()){
print_r($row);
}
} catch (PDOException $e) {
echo "PDOException: " . $e->getMssage() . PHP_EOL;
}

What is wrong in these mysqli prepared statements?

I'm trying to make a registration script using PHP with Mysql database. The insertion cannot be done. If I register with an email-id which is already in the database, it is working fine. But, the script fails to insert new entries. It is returning 'bool(false)'.
I've tried the to do the same using PDO. The insertion can't be done. So, I tried mysqli prepared statements instead and even this yields the same result. Here is the code.
<?php
$dbh = new mysqli('localhost', 'user', 'pass', 'db');
if(isset($_POST['register'])){
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$passw = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt( $passw );
$stmt = $dbh->prepare("SELECT mail FROM userrecs WHERE mail=?");
$stmt->bind_param('s',$mail);
if($stmt->execute())
{
$stmt->store_result();
$rows = $stmt->num_rows;
if($rows == 1)
{
session_start();
$_SESSION['notification_one'] = 'bla';
header('location:/someplace');
}
else {
$statement = $db->prepare("INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (?,?,?,?,?,?,?)");
$statement->bind_param('ssssiss',$ip,$name,$mail,$encrypted_pass,$codeone,$descs,$newstrings);
try {
if($statement->execute())
{
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
}
else
{
var_dump($statement->execute());
$statement->errorInfo();
}
}
catch(PDOException $pe) {
echo "S";
echo('Connection error, because: ' .$pe->getMessage());
}
}
}
}
else{
header('location:/someplace');
}
?>
EDIT:
This is the PDO-only code. I was mixing PDO and mysqli in the previous code.
<?php
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = 'user';
$password = 'pass';
$dbh = new PDO($dsn, $user, $password);
if(isset($_POST['regsubmit'])){
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$pass = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt( $passw );
$sql = "SELECT mail FROM userrecs WHERE mail=:mail";
$statement = $dbh->prepare($sql);
$statement->bindValue(':mail',$mail,PDO::PARAM_STR);
if($statement->execute())
{
if($statement->rowCount() == 1)
{
session_start();
$_SESSION['noti_one'] = 'bla';
header('location:/someplace');
}
else {
$sql2 = "INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (:ip,:name,:mail,:encrypted_pass,:codeone,:descs,:newstrings)";
$stmt = $dbh->prepare($sql2);
$stmt->bindParam(':ip',$ip,PDO::PARAM_STR);
$stmt->bindParam(':name',$name,PDO::PARAM_STR);
$stmt->bindValue(':mail',$mail,PDO::PARAM_STR);
$stmt->bindParam(':encrypted_pass',$encrypted_pass,PDO::PARAM_STR);
$stmt->bindParam(':codeone',$codeone,PDO::PARAM_STR);
$stmt->bindParam(':descs',$descs,PDO::PARAM_STR);
$stmt->bindParam(':newstrings',$temstr,PDO::PARAM_STR);
try {
if($stmt->execute())
{
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
}
else
{
var_dump($stmt->execute());
$stmt->errorInfo();
}
}
catch(PDOException $pe) {
echo "S";
echo('Connection error, because: ' .$pe->getMessage());
}
}
}
}
else{
header('location:/someplace');
}
?>
Please ignore variable or table names. I edited some of the names here.
You are mixing PDO and mysqli driver in the same script, this is not possible.
Please use either one but not both.
PDO is the prefferred extension.
EDIT:
In your query:
INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (...)
NAME is a mysql reserved keyword, you escape it by using backticks:
INSERT INTO userrecs (ip,`name`,mail,pass,codeone_one,desc_one,spcstrings) VALUES (...)
EDIT:
Change
var_dump($statement->execute());
$statement->errorInfo();
to
var_dump($statement->errorInfo());
EDIT:
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = 'user';
$password = 'pass';
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['regsubmit'])) {
try {
$sql = "SELECT mail FROM userrecs WHERE mail=:mail";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':mail', $_POST['mail'], PDO::PARAM_STR);
if ($stmt->execute() && $stmt->rowCount() == 1) {
session_start();
$_SESSION['noti_one'] = 'bla';
header('location:/someplace');
} else {
$sql = "INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (:ip,:name,:mail,:encrypted_pass,:codeone,:descs,:newstrings)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
$stmt->bindValue(':name', $_POST['$name'], PDO::PARAM_STR);
$stmt->bindValue(':mail', $_POST['mail'], PDO::PARAM_STR);
$stmt->bindValue(':encrypted_pass', crypt($_POST['passw']), PDO::PARAM_STR);
$stmt->bindValue(':codeone', $_POST['codeone'], PDO::PARAM_STR);
$stmt->bindValue(':descs', $_POST['desc'], PDO::PARAM_STR);
$stmt->bindValue(':newstrings', 'specialstring', PDO::PARAM_STR);
if ($stmt->execute()) {
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
} else {
var_dump($stmt->errorInfo());
}
}
} catch (PDOException $pe) {
echo "S";
echo('Connection error, because: ' . $pe->getMessage());
}
} else {
header('location:/someplace');
}
I believe you have an error in your logic.
Try this code and see what you get ...
<?php
$dbh = new mysqli('localhost', 'user', 'pass', 'db');
if(isset($_POST['register'])) {
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$passw = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt($passw);
$stmt = $dbh->prepare("SELECT mail FROM userrecs WHERE mail=?");
$stmt->bind_param('s', $mail);
$test = $stmt->execute();
if($test) {
$stmt->store_result();
$rows = $stmt->num_rows;
if($rows == 1) {
session_start();
$_SESSION['notification_one'] = 'bla';
header('location:/someplace');
} else {
$statement = $db->prepare("INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (?,?,?,?,?,?,?)");
$statement->bind_param('ssssiss', $ip, $name, $mail, $encrypted_pass, $codeone, $descs, $newstrings);
try {
if($statement->execute()) {
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
} else {
var_dump($statement->execute());
$statement->errorInfo();
}
} catch (PDOException $pe) {
echo "S";
echo('Connection error, because: ' . $pe->getMessage());
}
}
}else{
echo "test is not ok";
var_dump($test);
}
} else {
header('location:/someplace');
}

PHP PDO not deleting 2 fields from user table

I'm trying to delete a username and password from a table using PDO. Below is the code that I'm using. It inserts fine, does everything else perfect. It's a script I've got from the internet. The most decent one I could find. But I'm very new to PHP PDO and need some help deleting a username and password from a table.
<?php
function dbconnect()
{
global $pdo;
try {
$pdo = new PDO('mysql:host=localhost;dbname=redgrace_staxapp', 'root', '');
} catch (PDOException $e) {
die('MySQL connection fail! ' . $e->getMessage());
}
}
function insert_new_user($username, $password)
{
# checking username is already taken
if (username_exists($username))
return FALSE;
# insert new user info
global $pdo;
$stmt = $pdo->prepare('
INSERT INTO users
(username, password)
values (:username, :password)');
$stmt->execute( array(':username' => $username, ':password' => md5($password)) );
if ($pdo->lastInsertId())
return true;
else
return false;
}
function delete_user($username, $password)
{
if (username_exists($username))
return FALSE;
global $pdo;
$stmt = "DELETE FROM users WHERE username = :username and password = :password";
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
}
function username_exists($username)
{
global $pdo;
$stmt = $pdo->prepare('
SELECT id
FROM users
WHERE username = :username
LIMIT 1');
$stmt->execute( array('username' => $username) );
return $stmt->fetchColumn();
}
function attempt($username, $password)
{
global $pdo;
$stmt = $pdo->prepare('
SELECT id, username
FROM users
WHERE username = :username AND password = :password
LIMIT 1');
$stmt->execute(array(':username' => $username, 'password' => md5($password)));
if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
# set session
$_SESSION['username'] = $data->username;
return true;
} else {
return false;
}
}
function is_user()
{
if (isset($_SESSION['username']))
return true;
}
function redirect($url)
{
header('Location: ' .$url);
exit;
}
function valid_username($str){
return preg_match('/^[a-z0-9_-]{3,16}$/', $str);
}
function valid_password($str){
return preg_match('/^[a-z0-9_-]{6,18}$/', $str);
}
?>
Would be great if anyone can help me.
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
Do them one at a time (or use an array and execute)
http://us3.php.net/manual/en/pdostatement.bindparam.php
http://us3.php.net/manual/en/pdostatement.execute.php
$stmt->execute(['username'=>$username, 'password'=>$password]);
Try to find error if any like this (DETAILS: http://bd1.php.net/manual/en/pdo.errorinfo.php ):
global $pdo;
$sql = "DELETE FROM users WHERE username = :username and password = :password";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
if (!$stmt) {
print_r($pdo->errorInfo());
}
$stmt->execute();
Try to change:
$stmt->bindParam(':username', $username, ':password', $password);
to:
$sth->bindParam(':username', $username, PDO::PARAM_STR);
$sth->bindParam(':password', $password, PDO::PARAM_STR);
I have tried again to edit your code, you don't need to use global variable, because you instantiate the PDO class directly and use it on the fly.
try {
$pdo = new PDO('mysql:host=localhost;dbname=redgrace_staxapp', 'root', '');
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (PDOException $e) {
die('MySQL connection fail! ' . $e->getMessage());
}
function delete_user($username, $password)
{
if (username_exists($username))
return TRUE;
$query = "DELETE FROM users WHERE username = :username and password = :password";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
}

Login users/start session with PDO

Im trying to create a login section on my website using PDO.
So far I've the following...
config.php
// Connect to DB
$username = 'user#site.co.uk';
$password = 'pass';
try {
$conn = new PDO('mysql:host=localhost;dbname=db', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
header.php
// DB Config
include '/assets/config.php';
// User Session
$login = 'liam';
$pass = 'password';
$sth = $conn->prepare("SELECT * FROM access_users WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, $pass);
$sth->execute();
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
}
?>
My browser doesn't display the page however, and when I view my source theres no data contained within, can anybody see where im going wrong?
try this:
// User Session
$login = 'liam';
$pass = 'password';
$sth = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$sth->execute(array(":username" => $login,":password" => $pass));
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
echo $sth->rowCount();
}
make sure you have username "liam" and pass "password" in the database
You have set PDO::ERRMODE_EXCEPTION. This means, you should wrap your statements in a try/catch block and test execute()s return code:
try {
$sth = $conn->prepare("SELECT * FROM access_users WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, $pass);
if (!$sth->execute()) {
$info = $sth->errorInfo();
echo 'Error: ' . $sth->errorCode() . ' (' . $info[2] . ")\n";
} elseif ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
}
} catch (PDOException $e) {
echo 'Exception: ' . $e->getMessage() . "\n";
}
and put some trace statements in, of course.

php script echoing part of the php instead of what intended [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 2 years ago.
I'm having trouble with php script that I've created to insert instances into a database, however I'm getting a trivial output and i dont know how to fix it. the code is:
<?php
try{
$user = 'root';
$pass = null;
$pdo = new PDO('mysql:host=localhost; dbname=divebay', $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$password = sha1($_POST['password']);
$location = %_POST['location'];
$email = $_POST['email'];
$name = $_POST['fname'] . " " . $_POST['surname'];
$check = $pdo->prepare('SELECT * FROM user WHERE username=?');
$check->bindValue(1, $username);
$check->execute();
if($check->fetch(PDO::FETCH_OBJ)){
echo "Account name already exists";
}
else{
$stmt = $pdo->prepare('INSERT INTO user(username, password, location, email, name)
VALUES(:username, :password, :location, :email, :name)');
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':location', $location, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if($stmt->execute()){
echo "Account created";
}
else{
echo "Account could not be created";
}
}
$pdo = null;
}catch(PDOException $e){
echo $e->getMessage();
}
?>
i would expect the output to be something like "Account created". Instead the output I'm getting this error:
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $username =
$_POST['username']; $password = sha1($_POST['password']);
$location = %_POST['location']; $email = $_POST['email']; $name =
$_POST['fname'] . " " . $_POST['surname']; $check =
$pdo->prepare('SELECT * FROM user WHERE username=?');
$check->bindValue(1, $username); $check->execute();
if($check->fetch(PDO::FETCH_OBJ)){ echo "Account name already exists";
} else{ $stmt = $pdo->prepare('INSERT INTO user(username, password,
location, email, name) VALUES(:username, :password, :location, :email,
:name)'); $stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':location', $location, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if($stmt->execute()){ echo "Account created"; } else{ echo "Account
could not be created"; } } $pdo = null; }catch(PDOException $e){ echo
$e->getMessage(); } ?>
whats going wrong with this script to cause this?
The only way you'd get that output is if you had written:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
as:
$pdo?>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
by mistake.
YOU HAVE a % INSTEAD OF $ on %_POST['location']
RECOMMENDATION:
Also I HIGHLY recommend wrapping the PDO functions into a class. Here is what I use personally in every single project:
save this to it's own file (ex:sql.class.php)
<?php
class SqlIt{
public $Sql;
public $Response;
private $Host;
private $DBname;
private $User;
private $Pass;
public $NumResults;
public function __construct($Sql, $type, $vars){
if($vars == ""){
$vars = array();
}
try{
$DB = $this->db_connect();
$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DB->prepare($Sql);
$doit = $STH->execute($vars);
$this->Result = $doit;
}
catch(PDOException $e){
echo $e->getMessage();
}
//find function to run
switch($type){
case 'select':
$this->select($STH);
break;
}
}
public function select($query){
$rows = $query->rowCount();
$this->NumResults = $rows;
while($row = $query->fetchObject()){
$this->Response[] = $row;
}
}
//create a separate function for connecting to DB. Private to only this class.
private function db_connect(){
$this->User = 'root';
$this->Pass = '';
$DBH = new PDO("mysql:host=localhost;dbname=divebaby", $this->User, $this->Pass);
return $DBH;
}
}
?>
Then to actually run the statement you placed above you simply right the following code:
$username = $_POST['username'];
$password = sha1($_POST['password']);
$location = $_POST['location'];
$email = $_POST['email'];
$name = $_POST['fname'] . " " . $_POST['surname'];
$getUser = new SqlIt("SELECT * FROM user WHERE username=?","select",array($username));
if($getUser){
echo 'Account name already exists';
}else{
$insertUser = new SqlIt("INSERT INTO user (username,password,location,email,name) VALUES (?,?,?,?,?)","insert",array($username,$password,$location,$email,$name));
if($insertUser){
echo 'Account created!';
}else{
echo 'Account not created.';
}
Missing <?php at the beginning of one of your pages that contains that code with the first line of setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Categories