Using functions and PDO to check if account exists - php

I am having some trouble using functions to check if user account already exist in the backend. I created two functions: one to check if user account already exist and the other to create account.
Can someone enlighten me...? What is wrong with the code here?
<?php
try{
$username = 'web';
$password = '1234';
$username_signup = $_POST['username_signup'];
$password_signup = $_POST['password_signup'];
$hash = crypt($_POST['password'], '$3a$08$2'); // salt
$connection = new PDO ('mysql:host=localhost;dbname=tongue', $username, $password);
$connection -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection -> setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
function check(c){
$statement = $connection->prepare('
SELECT email FROM user
WHERE email=:username;
');
$statement -> bindParam(':username', c, PDO::PARAM_STR, 127);
$check = $statement -> execute();
return $check;
};
function create(a,b){
$statement = $connection->prepare('
INSERT INTO user (email, hash)
VALUES (:username, :hash);
');
$statement -> bindParam(':username', a, PDO::PARAM_STR, 127);
$statement -> bindParam(':hash', b, PDO::PARAM_STR);
$statement -> execute();
}
check($username_signup);
if ($check==0){
create($username_signup, $hash);
header("Location=index.php");
exit();
} else {
header("Location=sign_up.php?error=1");
exit();
}
$connection = null;
} // try{}
catch(PDOException $e) {
echo $e->getMessage();
}
?>

$connection is not global so it is not set inside the functions so you either need to make it global (don't) or pass it in as a argument
p.s. you should really work on your functions and variables names

Here's the final code:
<?php
try{
$username_signup = "Tst#gmail.com";
$password_signup = "est";
$hash = crypt($password_signup, '$3a$08$2'); // salt
$connection = new PDO ('mysql:host=localhost;dbname=tongue', 'web', '1234');
$connection -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection -> setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
function login ($query, $connect, $user) {
$statement = $connect->prepare($query);
$statement -> bindParam(':username', $user, PDO::PARAM_STR, 127);
$statement -> execute();
$data = $statement->fetch (PDO::FETCH_OBJ); // fetches the columns defined as $property
return $data;
}
function create ($query, $connect, $user, $pass) {
$statement = $connect->prepare($query);
$statement -> bindParam(':username', $user, PDO::PARAM_STR, 127);
$statement -> bindParam(':password', $pass, PDO::PARAM_STR, 127);
$statement -> execute();
}
$sql = 'SELECT email, hash FROM user WHERE email=:username'; // must be defined before calling
if ($row = login ($sql, $connection, $username_signup)) {
echo "Account already exists!";
}
else {
$sql = 'INSERT INTO user(email, hash) VALUES (:username, :password)';
create($sql, $connection, $username_signup, $password_signup);
echo "account created";
};
$connection = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>

Related

PDO Exception : Tried to bind parameter number 65536. SQL Server supports a maximum of 2100 parameters

I want to read user data. But the result showing like
Tried to bind parameter number 65536. SQL Server supports a maximum
of 2100 parameters.
and here is my code of login.php (test with hard code first)
<?php
header("Content-type: application/json");
include_once 'Database.php';
include_once 'master.php';
//$username = $_GET['username'];
//$password = $_GET['password'];
$username = "angela123";
$password = "admin123";
// get database connection
$database = new Database();
$db = $database->getConnection();
$login = new Master($db);
$stmt = $login->Login($username, $password);
?>
and here is function of Login with parameter username and password
public function Login($username,$password)
{
// select all query
try {
$sqlsrvquery = ("
EXEC [dbo].[GetAllAdmin2]
#username = ':username',
#password = ':password',
");
// prepare query statement
$stmt = $this->conn->prepare($sqlsrvquery);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$admin_arr = array(
"username" => $row['username'],
"password" => $row['password'],
);
}
if ($row = 0) {
$admin_arr = array(
"status" => false,
"message" => "Invalid Get Data Admin!",
);
}
} catch (Exception $e) {
print_r($e->getMessage());
}
print_r(json_encode($admin_arr));
}
What's going on in this code? actually the result is working properly on SQL Server with SP
Here is the Login SP
ALTER Procedure [dbo].[GetAllAdmin2]
(
#username varchar(55),
#password varchar(55)
)
as
begin
SELECT username, password
FROM Admin
WHERE username = #username and password = #password
and status = 'Active';
END
When execute the SP, the output should be showing username and password
username password
angela123 admin123
And here is database.php
<?php
class Database
{
// specify your own database credentials
private $host = "DESKTOP-N550JK\SQLEXPRESS";
private $user = "sa";
private $database = "Library";
private $password = "sqlserver123";
public $conn;
// get the database connection
public function getConnection(){
try {
$this->conn = new PDO("sqlsrv:Server=" .$this->host . ";database=" . $this->database, $this->user, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exception) {
echo "Connection error: " . $exception->getMessage();
die("Database Connection Error");
}
return $this->conn;
}
}
?>
any solution of this? thanks
You are using parameter binding in a wrong way and you need to remove the quotes around the placeholders (:username and :password). As is explained in the documetation, the statement template can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed.
<?php
...
// Statement
$sqlsrvquery = "
EXEC [dbo].[GetAllAdmin2]
#username = :username,
#password = :password
";
$stmt = $this->conn->prepare($sqlsrvquery);
// Parameter bindings
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Statement execution
$stmt->execute();
...
?>
An additional example, using the ? parameter marker:
<?php
...
// Statement
$sqlsrvquery = "
EXEC [dbo].[GetAllAdmin2]
#username = ?,
#password = ?
";
$stmt = $this->conn->prepare($sqlsrvquery);
// Parameter bindings
$stmt->bindParam(1, $username, PDO::PARAM_STR);
$stmt->bindParam(2, $password, PDO::PARAM_STR);
// Statement execution
$stmt->execute();
...
?>

Return from mysql using procedure and PDO

DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `verifLogin`(INOUT `email` VARCHAR(75), INOUT `password` VARCHAR(30))
READS SQL DATA
SELECT * FROM tblLogon WHERE emailLogon = email and passwordLogon = password$$
DELIMITER ;
try{
$email = $_POST['emailLog'];
$password = $_POST['passwordLog'];
$sql = "CALL verifLogin (?, ?)";
$stmt = $PDO -> prepare($sql);
$stmt -> bindParam(1, $email, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 75);
$stmt -> bindParam(2, $password, PDO::PARAM_STR, 30);
$stmt -> execute();
$row = (int) $stmt -> fetchAll(PDO::FETCH_ASSOC);
if($row > 0){
$res = array("erro" => "false", "message" => "Ok!");
}
else{
$res = array("erro" => "true", "message" => "Fail! ");
}
echo $res['message'];
} catch (Exception $exc) {
echo $exc -> getTraceAsString();
}
It's a login code, I am not getting a return from mysql, every time I try another way the error message is the same, the connection is ok, but I don't receive nothing from mysql

How to CRUD using PDO Connection?

I want to CRUD using PDO Connection
I know how to create insert update and delete using msql_query() but I have no idea how to do that with PDO Connection.
Below is the example of that
class connection{
public $cnn;
public function __construct(){
$host = 'localhost';
$db_name = "db_name";
$username = "db_username";
$password = "db_password";
try {
$this->cnn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function select($query){ //this function is created for get data
$result = $this->cnn->query($query);
return $result->fetchAll(PDO::FETCH_ASSOC);
}
public function insert($query){ //this function is created for insert data. it will be return last inserted id.
$this->cnn->exec($query);
return $this->cnn->lastInsertId();
}
public function update($query){ //this function is created for update data and it will be return effected rows (which are updated)
return $this->cnn->exec($query);
}
public function delete($query){ // this function is use to delete data.
return $this->cnn->exec($query);
}
}
$action = new connection;
$result = $action->select("select * from table_name");
print_r($result);
$result = $action->insert("insert into table_name set column_1 = 'first_value', column_2='second_value'");
$result = $action->update("update table_name set column_1 = 'first_value', column_2='second_value' where id=1");
$result = $action->delete("delete from table_name where id=1");
Maybe this is an easier way to do it. now the only thing you have to do is call the functions. Enjoy (:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "database";
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function updateuser($pdo, $username, $password, $id){
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password, $id]);
}
function deleteuser($pdo, $id){
$sql = 'DELETE FROM users WHERE id = ?';
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
}
function createuser($pdo, $username, $password){
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password]);
}
function readuser($pdo, $id){
$sql = "SELECT id, username FROM users WHERE id=?";
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}

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 script using PDO extension not working

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;
}
?>

Categories