How can I provide conditions in SQL query? - php

I'm trying to update the database table. How can I prevent the password ("MemberPassword", $ pass) coming from the form from being updated with sql codes by providing a condition if it is empty? Is it possible?
//database connection
$SQL = "mysql:host=" . $this->MYSQL_HOST . ";dbname=" . $this->MYSQL_DB;
try {
$this->pdo = new \PDO($SQL, $this->MYSQL_USER, $this->MYSQL_PASS);
$this->pdo->exec("SET NAMES'" . $this->CHARSET . "'COLLATE'" . $this->COLLATION . "'");
$this->pdo->exec("SET CHARACTER SET'" . $this->CHARSET . "'");
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);
} catch (PDOException $e) {
die( $e->getMessage());
}
}
//Connect DB END
private function myQuery($query, $params = null)
{
if (is_null($params)) {
$this->stmt = $this->pdo->query($query);
} else {
$this->stmt = $this->pdo->prepare($query);
$this->stmt->execute($params);
}
return $this->stmt;
}
public function Update($query, $params = null)
{
try {
return $this->myQuery($query, $params)->rowCount();
} catch (PDOException $e) {
die($e->getMessage());
}
}
$update = $db->Update("UPDATE members SET
MemberUsername=?,
MemberPassword=?,
MemberEmail=?,
MemberName=?,
MemberLastName=?,
MemberBirthday=?,
MemberAge=?,
MemberGender=?,
CityID=?
WHERE MemberID=?
", array($username, $pass, $email, $name, $lastname, $birthday, $age, $gender, $city, $memberID));

You can easy use IFNULL(expr1,expr2) like:
IFNULL returns expr1 if they is not null else expr2
$update = $db->Update("UPDATE members SET
MemberUsername=?,
MemberPassword=IFNULL(?,MemberPassword),
MemberEmail=?,
MemberName=?,
MemberLastName=?,
MemberBirthday=?,
MemberAge=?,
MemberGender=?,
CityID=?
WHERE MemberID=?
", array($username, $pass, $email, $name, $lastname, $birthday, $age, $gender, $city, $memberID));

Use something like this in your php code:
$param = array($username, $email, $name, $lastname, $birthday, $age, $gender, $city);
$sqlUpdate = "UPDATE members SET
MemberUsername=?,
MemberEmail=?,
MemberName=?,
MemberLastName=?,
MemberBirthday=?,
MemberAge=?,
MemberGender=?,
CityID=?"
if(!is_null(pass)) {
$sqlUpdate = $sqlUpdate . ", MemberPassword = ?";
array_push($param , $pass);
}
$sqlUpdate = $sqlUpdate . " WHERE MemberID=?";
array_push($param , $memberID);
$update = $db->Update($sqlUpdate, $param);
You can use this pattern for all other fields.

I didn't understand what your question exactly is but I think this is what you want :
User submits a form and if Password that sent from this form was not empty then update everything including password, otherwise update everything except password!
For do this you can use if statement in your SQL Query
$update = $db->Update("UPDATE members SET
MemberUsername=?,
MemberPassword=IF(? IS NOT NULL AND LENGTH(?) > 0, ?, MembersPassword),
MemberEmail=?,
MemberName=?,
MemberLastName=?,
MemberBirthday=?,
MemberAge=?,
MemberGender=?,
CityID=?
WHERE MemberID=?
", array($username, $pass, $pass, $pass, $email, $name, $lastname, $birthday, $age, $gender, $city, $memberID));

Related

how to fix easily this error Fatal error: Call to a member function execute() on boolean in /Applications/XAMPP/xamppfiles/htdocs

I developed php simple page to register users and check if the user exists or not but it is not working and displays the fallowing error :
Fatal error: Call to a member function execute() on boolean in /Applications/XAMPP/xamppfiles/htdocs/one/include/DbOperation.php on line 31
and php code here please help us for this issue
<?php
class DbOperation
{
private $conn;
enter code here
//Constructor
function __construct()
{
require_once('Constants.php');
require_once('DbConnect.php');
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createUser($username, $pass, $email, $name, $phone)
{
if (!$this->isUserExist($username, $email, $phone)) {
$password = md5($pass);
$stmt = $this->conn->prepare("INSERT INTO users (username, password, email, name, phone) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $username, $password, $email, $name, $phone);
if ($stmt->execute()) {
return USER_CREATED;
} else {
return USER_NOT_CREATED;
}
} else {
return USER_ALREADY_EXIST;
}
}
private function isUserExist($username, $email, $phone)
{
$stmt = $this->conn->prepare("SELECT id FROM users WHERE username = ? OR email = ? OR phone = ?");
//if($query = $this->db->conn->prepare($sql)){
$stmt->bind_param(array("sss", $username, $email, $phone));
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $stmt->num_rows > 0;
}
}
?>
In your isUserExist() function it looks like your bind_param has an array which shouldn't be there:
$stmt->bind_param(array("sss", $username, $email, $phone));
should be:
$stmt->bind_param("sss", $username, $email, $phone);
This is most likely why mysqli->bind_param is returning FALSE
change your isUserExist as below:
private function isUserExist($username, $email, $phone)
{
$stmt = $this->conn->prepare("SELECT id FROM users WHERE username = ? OR email = ? OR phone = ?");
//if($query = $this->db->conn->prepare($sql)){
$stmt->bind_param("sss", $username, $email, $phone); // change here remove array
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
//$stmt->close(); // change this comment or remove this
return $stmt->num_rows > 0;
}
use this in isUserExist() function
$stmt->bind_param("sss", $username, $email, $phone);

PDO MYSQL Prepared Update Statement using PHP Not executing

I am trying to execute a prepared statement using a PDO via PHP on a MySQL database.
I have tried two versions of the code both have not worked. The function update will execute but nothing will get updated in the database. My view customerData functions using fetch() and fetchAll() both work as does my deleteData function.
My current database structure is:
customerID(int11)
firstName(varchar(50)
lastName(varchar(50)
address(varchar(50)
city(varchar(50)
state(varchar(50)
postalCode(varchar(20)
countryCode(char(2)
phone(varchar(20)
email(varchar(50)
password(varchar(20)
The current version of code I am using:
function update_customer($customerID, $firstName, $lastName, $address, $city, $state, $postalCode, $countryCode, $phone, $email, $password)
{
global $db;
$query = "UPDATE customers
SET
firstName = :first,
lastName = :last,
address = :add,
city = :c,
state = :s,
postalCode = :postal,
countryCode = :country,
phone = :p,
email = :e,
password = :password
WHERE customerID = :ID";
$statement = $db->prepare($query);
$statement->bindValue(':first',$firstName);
$statement->bindValue(':last', $lastName);
$statement->bindValue(':add', $address);
$statement->bindValue(':c' ,$city);
$statement->bindValue(':s',$state);
$statement->bindValue(':postal', $postalCode);
$statement->bindValue(':country',$countryCode);
$statement->bindValue(':p', $phone);
$statement->bindValue(':e', $email);
$statement->bindValue(':pass', $password);
$statement->bindValue(':ID', $customerID);
$statement->execute();
$statement->closeCursor();
}
The other version of code I have used
function update_customer($customerID, $firstName, $lastName, $address, $city, $state, $postalCode, $countryCode, $phone, $email, $password)
{
global $db;
$query = "UPDATE customers
SET
firstName = ?,
lastName = ?
address = ?,
city = ?,
state = ?,
postalCode = ?,
countryCode = ?,
phone = ?,
email = ?,
password = ?
WHERE customerID = ?";
$statement = $db->prepare($query);
$statement->bindParam('ssssssssssi', $firstName, $lastName, $address, $city, $state, $postalCode, $countryCode, $phone, $email, $password, $customerID);
$statement->execute();
$statement->closeCursor();
}
My other 3 prepared statements work perfectly, for example here is the prepared statement that populates the update customer form.
function view_customerData ($customerID) {
global $db;
$query = "SELECT * FROM customers
WHERE customerID = $customerID";
try {
$statement = $db->prepare($query);
$statement->execute();
$customerData = $statement->fetch();
return $customerData;
} catch (PDOException $e) {
$error_message = $e->getMessage();
echo "<p>Database error: $error_message </p>";
exit();
}
}
Try to put the whole update customer code on try block and put catch block if any error occurs. But first of all fix this line
$statement->bindValue(':pass', $password);
to
$statement->bindValue(':password', $password);
^^^^
try {
//.....put your update customer code here ...
} catch (PDOException $e) {
$error_message = $e->getMessage();
echo "<p>Database error: $error_message </p>";
exit();
}

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

PDO connection / prep and execute in there own functions best practice

Hi all i have been playing with PDO's and am slowly converting some old code over to this.
Getting a little stuck with a few thing and struggling to find what i need.
What i am getting stuck on is:
Having the $db in a function or the sorts so its only open when i
call it, i only want to manage one instance of this
checking if
execute was successful and if not return a value etc.
Also any advice on the below code would be great full as i have gathered this from sources around the web.
Current Code:
//Database Array
$config['db'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'root');
//New PDO
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
//Check connection is ok
try {
$db->exec("SET CHARACTER SET utf8");
}
catch (PDOException $ex) {
print "Error!: " . $ex->getMessage() . "<br/>";
die();
}
//Update users function
function update($db, $fn, $ln, $email, $offers, $vlue, $responce) {
$stmt = $db->prepare("insert into kkt (fName_765, lName_765, email_765, signup_765, stamp_765) values (:fname, :lname, :email, :signup, NOW())");
$stmt->bindParam(':fname', $fn, PDO::PARAM_STR);
$stmt->bindParam(':lname', $ln, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':signup', $offers, PDO::PARAM_STR);
$stmt->execute();
print $db->lastInsertId();
$stmt = null;
}
//Test Attributes
$fn = 'test';
$ln = 'test';
$email = 'tesst#test,com';
$offers = '1';
update($db, $fn, $ln, $email, $offers, $vlue, $responce);
thanks in advance for any help / tips
Edited Code:
//Database Array
$config['db'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'local');
//New PDO
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Check connection is ok
try {
$db->exec("SET CHARACTER SET utf8");
}
catch (PDOException $ex) {
print "Error!: " . $ex->getMessage() . "<br/>";
die();
}
//Update users function
function update($db, $fn, $ln, $email, $offers, $vlue, $responce)
{
$stmt = $db->prepare("insert into local (fName_765, lName_765, email_765, signup_765) values (:fname, :lname, :email, :signup, NOW())");
$stmt->bindParam(':fname', $fn, PDO::PARAM_STR);
$stmt->bindParam(':lname', $ln, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':signup', $offers, PDO::PARAM_STR);
try {
$stmt->execute();
print $db->lastInsertId(); //show ID
return true;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>"; // show error
return false;
}
}
//Test Attributes
$fn = 'test';
$ln = 'test';
$email = 'tesst#test,com';
$offers = '1';
if (!update($db, $fn, $ln, $email, $offers, $vlue, $responce)) {
echo "no update there is a slight problem";
} else {
echo "it seemed to work";
}
Seem to be getting there, the above works hows it looking
checking if execute was successful and if not return a value etc.
Personally I prefer Exceptions, and PDO can be configured to raise Exceptions on errors. Exceptions are nice because the code that comes after the failed statement is not executed. This comes handy if you've a parent row, and then write some child rows which depend on the inserted parent. You don't want to write the child rows when the parent could not be created.
One can turn this on by doing this:
<?php
$pdo = new PDO(/* DSN */);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ATTR_ERRMODE_EXCEPTION);
Then you would do:
<?php
try {
$stmt->execute();
return true;
} catch (\PDOException $e) {
return false;
}
You can find more about this here: http://www.php.net/manual/en/pdo.error-handling.php
Having the $db in a function or the sorts so its only open when i call it, i only want to manage one instance of this
I'm usually managing a database connection by using a service container. The simplest existing option is Pimple. You then pass this service container around, and the service container is responsible for only creating one database connection.
<?php
$config = new \Pimple;
$config['db.options'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'root');
# Calling the "share" method makes sure that the function is only called when
# 'db' is retrieved the first time.
$config['db'] = $config->share(function() use ($config) {
return new PDO('mysql:host=' . $config['db.options']['host'] . ';dbname=' . $config['db.options'']['dbname'], $config['db.options'']['username'], $config['db.options'']['password']);
});
function update() {
global $config;
# Connection is only made the first time the 'db' key is accessed.
$db = $config['db'];
/* Do queries */
}
Having the $db in a function or the sorts so its only open when i call
it, i only want to manage one instance of this.
Open it at the start of your script and then pass it into the functions that need it. Opening a new database connection inside a function can lead to problems further down the line. For example, what if your function is used multiple times throughout the same script? You don't really want to open a new database connection every time that same function gets called.
checking if execute was successful and if not return a value etc.
As for checking if PDOStatement::execute was successful:
$result = $stmt->execute();
If you look at the manual, the return types are listed as:
Returns TRUE on success or FALSE on failure.
$result = $stmt->execute();
return $result;
or
return $stmt->execute();
Personally, I'd go with:
function update($db, $fn, $ln, $email, $offers, $vlue, $responce) {
$stmt = $db->prepare("insert into kkt (fName_765, lName_765, email_765, signup_765, stamp_765) values (:fname, :lname, :email, :signup, NOW())");
$stmt->bindParam(':fname', $fn, PDO::PARAM_STR);
$stmt->bindParam(':lname', $ln, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':signup', $offers, PDO::PARAM_STR);
return $stmt->execute();
}
By the way, when you pass an object into a function, it is automatically passed by reference, which means that you can do something like:
$result = update($db, $fn, $ln, $email, $offers, $vlue, $responce);
if($result){
echo $db->lastInsertId();
}

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