MySQL update, skip blank fields with PDO - php

I would like to update a MySQL row via the form below. The form works great as is but, if I leave a field blank, it changes the field in MySQL to blank as well. I would like to update the sql but skip over any fields that are blank.
I have read a few ways of doing this but they didn't seem logical. I.e. using if statements in the sql string itself. (Having MySQL do the work that should be done in PHP).
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
echo '<form method="post" action="">
ID: <input type="text" name="a" /><br>
Program: <input type="text" name="b" /><br>
Description: <textarea row="6" cols="50" name="c"></textarea><br>
Cost: <input type="text" name="d"><br>
<input type="submit" value="Add Link" />
</form>';
}
try {
$dbh = new PDO($dsn, $user, $pass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $dbh->prepare('UPDATE links SET Program = :program , Descr = :descr, Cost = :cost WHERE Id= :id');
$stmt->bindParam(":id", $_POST["a"]);
$stmt->bindParam(":program", $_POST["b"]);
$stmt->bindParam(":descr", $_POST["c"]);
$stmt->bindParam(":cost", $_POST["d"]);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());}
$dbh = null;
}
}catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}

Something like this should work
.
.
.
$q = array();
if(trim($_POST["b"]) !== ""){
$q[] = "Program = :program";
}
if(trim($_POST["c"]) !== ""){
$q[] = "Descr = :descr";
}
if(trim($_POST["d"]) !== ""){
$q[] = "Cost = :cost";
}
if(sizeof($q) > 0){//check if we have any updates otherwise don't execute
$query = "UPDATE links SET " . implode(", ", $q) . " WHERE Id= :id";
$stmt = $dbh->prepare($query);
$stmt->bindParam(":id", $_POST["a"]);
if(trim($_POST["b"]) !== ""){
$stmt->bindParam(":program", $_POST["b"]);
}
if(trim($_POST["c"]) !== ""){
$stmt->bindParam(":descr", $_POST["c"]);
}
if(trim($_POST["d"]) !== ""){
$stmt->bindParam(":cost", $_POST["d"]);
}
$stmt->execute();
}
.
.
.

Change the statement:
$stmt = $dbh->prepare('UPDATE links SET Program = :program , Descr = :descr, Cost = :cost WHERE Id= :id');
As follows:
$stmt = $dbh->prepare('UPDATE links SET Program = IF(trim(:program)="", Program, :program) , Descr = IF(trim(:descr)="", Descr, :descr), Cost = IF(trim(:cost)="", Cost, :cost) WHERE Id= :id');

Check post field for empty :
It will skip update query if any field data is empty.
If( $_POST["a"] && $_POST["b"] && $_POST["c"] && $_POST["d"]){
try {
$dbh = new PDO($dsn, $user, $pass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $dbh->prepare('UPDATE links SET Program = :program , Descr = :descr, Cost = :cost WHERE Id= :id');
$stmt->bindParam(":id", $_POST["a"]);
$stmt->bindParam(":program", $_POST["b"]);
$stmt->bindParam(":descr", $_POST["c"]);
$stmt->bindParam(":cost", $_POST["d"]);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());}
$dbh = null;
}
}catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
Option2 Update all fields except empty:
try {
$sql ="UPDATE links SET ";
if($_POST["a"])
$sql .=" Program = :program ,";
if($_POST["b"])
$sql .=" Descr = :descr ,";
if($_POST["c"])
$sql .=" Cost = :cost ,";
$sql = rtrim($sql,',');
$dbh = new PDO($dsn, $user, $pass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $dbh->prepare($sql);
if($_POST["a"])
$stmt->bindParam(":id", $_POST["a"]);
if($_POST["b"])
$stmt->bindParam(":program", $_POST["b"]);
if($_POST["c"])
$stmt->bindParam(":descr", $_POST["c"]);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());}
$dbh = null;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}

It is easier to use unnamed parameters for dynamic queries in PDO and passing them as an array in execute(). The statement will not be executed unless at least 1 parameter is passed along with the id. I have left in the echo of the derived statement and the dump of the array.
Example statement
UPDATE `links` SET `Program` = ? , `Cost` = ? WHERE `Id` = ?
Example array
Array ( [0] => 2 [1] => 3 [2] => 2 )
if(isset($_GET['a'])){
$id = $_GET['a'];
$program = isset($_GET['b']) ? $_GET['b'] : NULL;
$descr = isset($_GET['c']) ? $_GET['c'] : NULL;
$cost= isset($_GET['d']) ? $_GET['d'] : NULL;
$params =array();
$sql = "UPDATE `links` SET "; //SQL Stub
if (isset($program)) {
$sql .= " `Program` = ? ,";
array_push($params,$program);
}
if (isset($descr)) {
$sql .= " `Descr` = ? ,";
array_push($params,$descr);
}
if (isset($cost)) {
$sql .= " `Cost` = ? ,";
array_push($params,$cost);
}
$sql = substr($sql, 0, -1);//Remove trailing comma
if(count($params)> 0){//Only execute if 1 or more parameters passed.
$sql .= " WHERE `Id` = ? ";
array_push($params,$id);
echo $sql;//Test
print_r($params);//Test
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
}
}

Related

I want to write code for check if data already exits then insert in different table

I already write the code to check if table call hm2_history type = commission if yes then insert data into table call hm2_deposit, when I test echo was correct and show the result is :
Connected successfully
354
368
But won't insert into hm2_deposit , I don't know how to adjust it i have a little bit knowledge about php
This is my code
<?php
$servername = "localhost";
$username = "tinybaht_findroom";
$password = "212224";
function setChecked($conn,$params){
$s = $conn->prepare("UPDATE `hm2_history`
SET history_ref_id=-1
WHERE id=:id
");
$s->execute($params);
}
try {
$conn = new PDO("mysql:host=$servername;dbname=tinybaht_findroom", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$stmt = $conn->prepare("SELECT * FROM hm2_history");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$a = $stmt->fetchAll();
$plans = array();
foreach($a as $i){
$plans[$i['type']] = 'commissions';
}
$stmt = $conn->prepare("SELECT * FROM hm2_history WHERE id NOT IN(SELECT ref_id FROM hm2_deposits WHERE ref_id > 0) AND type='commissions'");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = $stmt->fetchAll();
foreach($rows as $k=>$v) {
$plan_type = isset($plans)?:'';
$m = $v['type'];
if (!empty($plan_type)){
echo '<br>'.$v['id'];
if ($m = "commissions" ){
setChecked($conn,array('id'=>$v['id']));
continue;
}
}else{
setChecked($conn,array('id'=>$v['id']));
continue;
}
//deposits
$s = $conn->prepare("INSERT INTO `hm2_deposits`
SET `user_id`=:user_id,
`type_id`=:type_id,
`deposit_date`=:deposit_date,
`last_pay_date`=:last_pay_date,
`status`=:status,
`q_pays`=:q_pays,
`amount`=:amount,
`actual_amount`=:actual_amount,
`ec`=:ec,
`compound`=:compound,
`dde`=:dde,
`unit_amount`=:unit_amount,
`bonus_flag`=:bonus_flag,
`init_amount`=:init_amount,
`ref_id`=:ref_id
");
$v['ref_id'] = $v['id'];
$v['amount'] = $v['amount']*$rate;
$v['actual_amount'] = $v['actual_amount']*$rate;
$v['init_amount'] = $v['init_amount']*$rate;
$v['bonus_flag'] = 1;
$v['type_id']= 9;
unset($v['id']);
$s->execute($v);
$lastDepositId = $conn->lastInsertId();
$date = date('Y-m-d H:i:s');
}
?>
this is photo of my db table name is hm2_deposits hm2_deposits
this is photo of my db table name is hm2_history enter image description here
There is an error in your SQL:
$s = $conn->prepare("INSERT INTO hm2_deposits
SET user_id=:user_id,
type_id=:type_id,
deposit_date=:deposit_date,
last_pay_date=:last_pay_date,
status=:status,
q_pays=:q_pays,
amount=:amount,
actual_amount=:actual_amount,
ec=:ec,
compound=:compound,
dde=:dde,
unit_amount=:unit_amount,
bonus_flag=:bonus_flag,
init_amount=:init_amount,
ref_id=:ref_id
");
Read the proper way to do it at:
https://www.w3schools.com/sql/sql_insert.asp

Update record if parameter has a value - SQL, PHP

My current code updates all values, and if there is an empty parameter it updates the corresponding field on the table to null. I want to update only the fields that have a value.
This is my code:
$sql = "
UPDATE drinks SET
name = :name, // Mojito -> Update it
description = :description, // Lorem ipsum.. -> Update it
glass_id = :glass_id, // NULL -> do not update
video_url = :video_url // NULL -> do not update
WHERE id = '$drinkId'
";
try {
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $drinkName);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':glass_id', $glassId);
$stmt->bindParam(':video_url', $videoUrl);
$stmt->execute();
// Close databse
$db = null;
} catch(PDOException $e) {
echo $e;
}
you don't want to update those 2 fields when they are empty.
this code check if a field is null and only when it is not null it will add the field to the query, also the same for binding the value.
$sql = 'UPDATE drinks SET';
$sql = sql . 'name = :name,';
$sql = sql . 'description = :description';
if (!is_null($glassId))
$sql = sql . ',glass_id = :glass_id';
if (!is_null($videoUrl))
$sql = sql . ',video_url = :video_url';
$sql = sql . ' WHERE id = :drinkId';
try {
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $drinkName);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':drinkId', $drinkId);
if (!is_null($glassId))
$stmt->bindParam(':glass_id', $glassId);
if (!is_null($videoUrl))
$stmt->bindParam(':video_url', $videoUrl);
$stmt->execute();
// Close databse
$db = null;
} catch(PDOException $e) {
echo $e;
}

php/pdo insert into database mssql with arrays

I need some help
Is there a way to make this in PDO? https://stackoverflow.com/a/1899508/6208408
Yes I know I could change to mysql but I use a mssql server and can't use mysql. I tried some things but I'm not as good with PDO as mysql... It's hard to find some good examples of inserting array's into database with PDO. So quickly said I have a PDO based code connected to a mssql webserver.
best regards joep
I tried this before:
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$data = array_merge($mon_barcode, $mon_merk, $mon_type, $mon_inch, $mon_a_date, $mon_a_prijs);
try{
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
$insertData = array();
foreach($_POST['mon_barcode'] as $i => $barcode)
{
$insertData[] = $barcode;
}
if (!empty($insertData))
{
implode(', ', $insertData);
$stmt = $conn->prepare($sql);
$stmt->execute($insertData);
}
}catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
The code below should fix your problems.
$db_username='';
$db_password='';
$conn = new \PDO("sqlsrv:Server=localhost,1521;Database=testdb", $db_username, $db_password,[]);
//above added per #YourCommonSense's request to provide a complete example to a code fragment
if (isset($_POST['com_id'])) { //was com_id posted?
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
try {
$stmt = $conn->prepare($sql);
foreach ($mon_barcode as $i => $barcode) {
$stmt->execute([$com_id, $barcode, $mon_merk[$i], $mon_type[$i], $mon_inch[$i], $mon_a_date[$i], $mon_a_prijs[$i]]);
}
} catch (\PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
$conn = null;

Conditional PDO bindParam Update

So I'm trying to do a conditional update but I seem to be having problems with binding the data with the statement.
function:
function updateEditor($email, $first, $last, $id){
global $DBH;
$response = false;
$upemail = "";
$upfirst = "";
$uplast = "";
$stmt = "SELECT memEmail, memFirst, memLast FROM MEMBER WHERE memID = :id";
try{
$STH = $DBH->prepare($stmt);
$STH->bindParam(':id', $id);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
$row = $STH->fetch();
if($row['memEmail'] != $email){ $upemail = $email;}
if($row['memFirst'] != $first){ $upfirst = $first;}
if($row['memLast'] != $last){ $uplast = $last;}
}catch(PDOException $e) {
echo $e->getMessage() . "first";
}
$stmt .= "UPDATE MEMBER SET ";
if(!empty($upemail)){
$stmt .= "memEmail = :memEmail";
if(!empty($upfirst) || !empty($uplast)){
$stmt .= ", ";
}
}
if(!empty($upfirst)){
$stmt .= "memFirst = :memFirst";
if(!empty($uplast)){
$stmt .= ", ";
}
}
if(!empty($uplast)){
$stmt .= "memLast = :memLast";
}
if(empty($upemail) && empty($upfirst) && empty($uplast)){
return false;
}else{
$stmt .= " WHERE memID = :id";
}
try{
$STH = $DBH->prepare($stmt);
if(!empty($upemail)){$STH->bindParam(':memEmail', $upemail);}else{$STH->bindParam(':memEmail', $row['memEmail']);}
if(!empty($upfirst)){$STH->bindParam(':memFirst', $upfirst);}else{$STH->bindParam(':memFirst', $row['memFirst']);}
if(!empty($uplast)){$STH->bindParam(':memLast', $uplast);}else{$STH->bindParam(':memLast', $row['memLast']);}
$STH->bindParam(':id', $id);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
$response = true;
}catch(PDOException $e) {
echo $e->getMessage() . "second";
$response = $e->getMessage() . "second";
}
return $response;
}
I have tried putting the variables into the statement, using ?, and the code above so far. The error I keep getting is:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Here:
$stmt .= "UPDATE MEMBER SET ";
you append the UPDATE to the previous $stmt string. You'll end up with:
$stmt = "SELECT memEmail, memFirst, memLast FROM MEMBER WHERE memID = :idUPDATE MEMBER SET "; // and the rest
reulting in one identifier more (:idUPDATE).
Remove the . to start a new query in this string.
$stmt = "UPDATE MEMBER SET ";
Note:
You are making this way too complicated. Skip the checks for empty values, just update all columns when you update a dataset, you don't gain anything by checking what has changed and what hasn't first.
Besides #Gerald Schneider answer, you are setting the param in both cases (if/else)
if(!empty($upemail)){$STH->bindParam(':memEmail', $upemail);}else{$STH->bindParam(':memEmail', $row['memEmail']);}
But are defining the parameters only in one case
if(!empty($upemail)){
$stmt .= "memEmail = :memEmail";
if(!empty($upfirst) || !empty($uplast)){
$stmt .= ", ";
}
}
if(!empty($upfirst)){
$stmt .= "memFirst = :memFirst";
if(!empty($uplast)){
$stmt .= ", ";
}
}
if(!empty($uplast)){
$stmt .= "memLast = :memLast";
}
There's no else condition

Query doesn't insert value into DB

In my query the update statement doesn't work, the error given is:
Number of parameter doesn't match with prepared statement
this is my code:
public function update_resource($resource)
{
$mysqli = new MySQLi(HOST, USERNAME, PASSWORD, DATABASE);
$this->connection_state($mysqli);
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
AND sigla = '$sigla' AND colore = '$colore' AND planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param("ssssi", $descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}
The code go into the Added condition but the query fail, what's the problem?
public function update_resource($resource)
{
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
, sigla = '$sigla', colore = '$colore', planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param($descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}?
Your problem is that you don't have any placeholders in your query.
Refer to manual to see how placeholders should be set.
In general, placeholders are ? which later will be replaced with values, so your query should look like:
$query = "UPDATE risorse SET descrizione = ?
AND sigla = ? AND colore = ? AND planning = ?
WHERE id = ?";
please visit on http://php.net/manual/en/pdostatement.bindparam.php.you got your answer.see Example #1 Execute a prepared statement with named placeholders

Categories