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();
}
Related
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));
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);
Using PDO with MariaDB server. I am having trouble understanding why this code does not work. Whenever I have :value for the values it gives me an error " Invalid parameter number: parameter was not defined"
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':domain', $domain);
$stmt->bindValue(':flag', $flag);
$stmt->execute();
But then the code below does work.
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (?,?,?)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(1, $username);
$stmt->bindValue(2, $domain);
$stmt->bindValue(3, $flag);
$stmt->execute();
Below is the rest of the section for this code.
if(isset($_POST['addEditor'])){
$username = $_POST['formUsername'];
$domain = $_POST['formDomain'];
$flag = $_POST['formflg'];
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':domain', $domain);
$stmt->bindValue(':flag', $flag);
$stmt->execute();
try{
$stmt->execute();
}
catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
That code worked for me have read something about PDO here
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$username='a';
$domain ='b';
$flag ='c';
$sql = "INSERT INTO `table` (`USER`, `DOMAIN`, `FLG`) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->execute(
array(':username'=> $username,
':domain'=> $domain,
':flag'=> $flag)
);
I am having trouble understanding why this code does not work.
No wonder, as you're using wrong way to understand.
Get rid of all try and catch operators in your code, run it again and then read the full error message, that will make you understand which code does not work.
if($_POST)
{
$role ="student";
try{
$stmt = $db_con->prepare("INSERT INTO userinfo (role)
VALUES(:qrole)");
$stmt->bindParam(":qrole", $role);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
try this , if some errors occurred it will post it using catch
Hi I am getting error during the execution of PDO prepare statement. My local development works fine but when I try to insert to cleardb in cloud this error occur:
SQLSTATE[42000]: Syntax error or access violation: 1142 INSERT command denied to user 'b2218f51d4a66e'#'191.235.136.58' for table 'user'' in /var/www/php1/CRUD.php:52
function create_User($firstname, $lastname, $username, $password, $address, $city, $zip, $country, $email) {
global $dbh;
$this->password = $password;
$token = md5($this->salt1 . $this->password . $this->salt2);
$this->sth = $dbh->prepare('INSERT INTO `Php_Project`.`User`
(
userName,
passWord,
create_DateStamp,
e_mail)
VALUES
(
:username,
:token,
NOW(),
:email
);
');
$this->sth->bindParam(':username', $username, PDO::PARAM_STR);
$this->sth->bindParam(':token', $token, PDO::PARAM_STR);
$this->sth->bindParam(':email', $email, PDO::PARAM_STR);
if ($this->sth->execute()) {
$this->message = "true";
} else {
$this->message = "false";
}
if ($this->message == "true") {
$userId = $dbh->lastInsertId();
$this->sth = $dbh->prepare('INSERT INTO `Php_Project`.`user_Detail`
(
firstName,
lastname,
adress,
zip,
city,
country,
userId)
VALUES
(
:firstname,
:lastname,
:address,
:zip,
:city,
:country,
:userId
);');
$this->sth->bindParam(':firstname', $firstname, PDO::PARAM_STR);
$this->sth->bindParam(':lastname', $lastname, PDO::PARAM_STR);
$this->sth->bindParam(':address', $address, PDO::PARAM_STR);
$this->sth->bindParam(':zip', $zip, PDO::PARAM_INT);
$this->sth->bindParam(':city', $city, PDO::PARAM_STR);
$this->sth->bindParam(':country', $country, PDO::PARAM_STR);
$this->sth->bindParam(':userId', $userId, PDO::PARAM_STR);
if ($this->sth->execute()) {
$this->message = true;
} else {
$this->message = false;
}
}
}
This is a permissions problem. Your database user has the INSERT permission for the table on your development server but not on your production server, so you'll need to change the user permissions using GRANT on your production server.
$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!";
}