PHP PDO not deleting 2 fields from user table - php

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();
}

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();
...
?>

php PDO prepare(" INSERT ..(variables ) VALUES(?,?,) produces an error need assistance

$query = $this->link->prepare("INSERT INTO surveys (`username`,`inspected`,
`comments`,`ip_address`,`date`,`time`)
VALUES '(?,?,?,?,?,?)';);
$values = array ($username,$inspected,$comments,$ip_address,$date,$time);
var_dump($query);$rowCount = $query->rowCount();
$return $rowCount;
You can base yourself on the following which I've prepared for you.
Sidenote: I'm not entirely sure as to why you want to use rowCount() for, so I left it out for now.
If you're looking to check if a record exists using rowCount(), let me know.
The following method works to insert data into a database, which is based on a method I use.
<?php
$dbname = 'xxx';
$username = 'xxx';
$password = 'xxx';
try {
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
$sql = "INSERT INTO surveys (
username,
inspected,
comments,
ip_address,
date,
time
) VALUES (
:username,
:inspected,
:comments,
:ip_address,
:date,
:time)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':inspected', $_POST['inspected'], PDO::PARAM_STR);
$stmt->bindParam(':comments', $_POST['comments'], PDO::PARAM_STR);
$stmt->bindParam(':ip_address', $_POST['ip_address'], PDO::PARAM_STR);
$stmt->bindParam(':date', $_POST['date'], PDO::PARAM_STR);
$stmt->bindParam(':time', $_POST['time'], PDO::PARAM_STR);
// $stmt->execute();
$stmt->execute(array(':username' => $_POST['username'],':inspected' => $_POST['inspected'],':comments' => $_POST['comments'],
':ip_address' => $_POST['ip_address'],':date' => $_POST['date'],':time' => $_POST['time']));
if($stmt != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}

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);

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

Using functions and PDO to check if account exists

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

Categories