Do not update with empty vars on UPDATE statement - php

I am trying to run an sql update but i dont want to update when the post vars that are empty.
Code that i run is :
require '../includes/db.php';
$settings_owner = ( isset($_POST[wb_owner_field]) ? $_POST[wb_owner_field] : false );
$settings_title = ( isset($_POST[wb_title_field]) ? $_POST[wb_title_field] : false );
$settings_description = ( isset($_POST[wb_descr_field]) ? $_POST[wb_descr_field] : false );
$settings_keywords = ( isset($_POST[wb_keywd_field]) ? $_POST[wb_keywd_field] : false );
$settings_id = ( isset($_POST[wb_id]) ? $_POST[wb_id] : false );
try {
$sql = "UPDATE Website SET website_owner = '$settings_owner', website_title = '$settings_title', website_description = '$settings_description', website_keywords = '$settings_keywords' WHERE _ID = '$settings_id' ";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;

One way is to test the value in the UPDATE statement:
$sql = "UPDATE Website
SET website_owner = IF('$settings_owner' = '', website_owner, '$settings_owner'),
website_title = IF('$settings_title' = '', website_title, '$settings_title'),
website_description = IF('$settings_description' = '', website_description, '$settings_description'),
website_keywords = IF('$settings_keywords' = '', website_keywords, '$settings_keywords')
WHERE _ID = '$settings_id' ";
Another way is to build the UPDATE statement dynamically.
$sets = array();
if ($settings_owner != '') {
$sets[] = "website_owner = '$settings_owner'";
}
if ($settings_title != '') {
$sets[] = "website_title = '$settings_title'";
}
...
if (!empty($sets)) {
$sql = "UPDATE Website SET " . implode(', ', $sets) . " WHERE _ID = '$settings_id'";
$stmt = $conn->prepare($sql);
$stmt->execute();
}

I don't do much web programming, and haven't touched php in 10 years, but I work with MySQL daily and would imagine something like this would work:
UPDATE Website
SET website_owner = IF('$settings_owner'='', website_owner, '$settings_owner')
, website_title = IF('$settings_title'='',website_title, '$settings_title')
, website_description = IF('$settings_description'='',website_description, '$settings_description')
, website_keywords = IF('$settings_keywords'='',website_keywords, '$settings_keywords')
WHERE _ID = '$settings_id'
;

Related

Overwritte data in postgresql table php

The data present in the postgresql table isn't update any more. I want to overwrite the data. When I just use insert into, new data is added but the old data remains. I tried to use update but then I get errors. I would like to update all records. I think it's probably something with the syntax. But I can't find the problem.
Code
$dbname = "dbtest";
$host = "localhost";
$username = "postgres";
$password = "pasword";
$dbh = new PDO("pgsql:dbname=$dbname; host=$host", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$c = array("Human","Mouse","Rat","Hamster","SV40");
$b = array("Human HBO gene", "Mouse BB gene", "Human CCB gene", "SV40 TP gene", "Hamster TP53 gene");
$count=0;
foreach($c as $key => $d){
$e =$b[$key];
$name = $count++;
if (strpos($e, $d) !== FALSE) {
$match = $d;
$specie = $d;
$specie = str_replace("Human","Homo Sapiens",$specie);
$specie = str_replace("Mouse","Mus Musculus",$specie);
$specie = str_replace("Rat","Rattus norvegicus",$specie);
$Specie = str_replace("Hamster", "Mesocricetus Auratus",$specie);
$specie = str_replace("SV40","Simian virus 40",$specie);
}else{
$match = "0";
$specie = "0";
}
echo $match. " ". $specie. " ";
$var_id = $name;
$var_match = $match;
$var_full_name = $specie;
#$sql = "INSERT INTO species (id,match,full_name) VALUES ('".$var_id."','".$var_match ."','".$var_full_name."')";
$sql = "UPDATE species SET id = '".$var_id."', match = '".$var_match ."', full_name='".$var_full_name."'";
if ($dbh->query($sql)) {
echo "New Record Inserted Successfully!<br \>\n";
}else{
echo "Data not successfully Inserted.<br \>\n";
}
}
The error I get:
Fatal error: Uncaught PDOException: SQLSTATE[42601]: Syntax error: 7 ERROR: > syntax error at or near "Sapiens" LINE 1: ...species SET id = '0', match = Human, full_name=Homo Sapiens' ^ in /var/www/html/test/Insert.php:59 Stack trace: #0 /var/www/html/test/Insert.php(59): PDO->query('UPDATE species ...') #1 {main} thrown in /var/www/html/test/Insert.php on line 59
You should use a select query to determine if the value is new or old. If old update data, else insert data.
FUNCTION
function execute_query($query,$dbh){
if ($dbh->query($query)) {
return "New Record Inserted Successfully!<br \>\n";
}else{
return "Data not successfully Inserted.<br \>\n";
}
}
SELECT
$query = 'SELECT * FROM tbl '. 'WHERE "test1" = '.
"'".$var_test."'" . 'AND "test2" = '.
"'".$var_test2."'";
$stmt = $dbh->prepare($query);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$outcome = $stmt->fetch();
UPDATE
if ($outcome !== false){
$sql = "UPDATE tbl SET test1 = '".$var_test1."', test2 = '".$var_test2."',
test3 = '".$var_test3."'
"WHERE id = '".$var_id."' ";
execute_query($sql,$dbh);
INSERT
}else{
$sql = "INSERT INTO genes
(id,test1,test2,test3)
VALUES ('".$var_id."','".$var_test1 ."','".$var_test2."','".$var_test3."')";
execute_query($sql,$dbh);
}
When I use the following syntax, the error is gone. This query needs to be used to update.
$sql = "UPDATE species SET match ='".$var_match ."', full_name='".$var_full_name."' WHERE id = '".$var_id."' ";

prepare($sql)->execute() works, but $statement->execute() not

If I use the following statement, my code is working well:
$statement = $this->pdo->prepare($sql)->execute();
But if I use the following statements, my code doesn't work:
$statement = $this->pdo->prepare($sql);
$statement->execute();
Does anyone have an idea, what I'm doing wrong or why this is so?
Here my complete code:
public function deleteUser($pid_user){
/* DESCRIPTION
* delete an user an all his data
*
* PARAMETERS
*
* EXAMPLE
* deleteUser();
*/
try {
//begin transaction
$this->pdo->beginTransaction();
//define all tables to delete all entries from the overgiven user id
//name = name of the table
//column = column to identify the users entries
$tables = array();
$tables[0]["name"] = "snsho_bittrex_apikey";
$tables[0]["column"] = "fk_user";
$tables[1]["name"] = "snsho_bittrex_balances";
$tables[1]["column"] = "fk_user";
$tables[2]["name"] = "snsho_bittrex_deposit_history";
$tables[2]["column"] = "fk_user";
$tables[3]["name"] = "snsho_bittrex_order_history";
$tables[3]["column"] = "fk_user";
$tables[4]["name"] = "snsho_bittrex_withdrawal_history";
$tables[4]["column"] = "fk_user";
$tables[5]["name"] = "snsho_user_settings";
$tables[5]["column"] = "fk_user";
$tables[6]["name"] = "snsho_user";
$tables[6]["column"] = "pid_user";
//do the queries
$sql = '';
foreach($tables as $key => $table){
$sql .= 'DELETE FROM ' . $table["name"] . ' WHERE ' . $table["column"] . ' = ' . $pid_user . ';';
}
//$statement = $this->pdo->prepare($sql)->execute();
$statement = $this->pdo->prepare($sql);
$statement->execute();
if($this->pdo->commit()){
echo "commited";
}else{
echo "commit failed";
}
return TRUE;
} catch (Exception $e) {
$this->adminMessages->setSingleError("Failed: " . $e->getMessage());
$this->pdo->rollBack();
return FALSE;
}
}
Try the execute without the assignment.
$this->pdo->prepare($sql)->execute();
This only returns a true or false.

Update query from PHP does not work

I run this update query from PHP code:
$update_begin_insurance = "UPDATE `vehicles`
SET `begin_insurance_date` = '$begin_insurance'
WHERE `plate` = '$plate'";
$conn->query($update_begin_insurance);
$conn is a PDO object.
The problem is that any exception is thrown by $conn, but the vehicles table in my database is not updated. So, I've tried to run this query directly through phpmyadmin, and it works correctly, so I think it's a PHP problem, but I can't figure out where the problem is.
My begin_insurance_date column is of type DATE, and $begin_insurance is a string in the correct format (YYYY-MM-DD, I've tried this code with 2017-06-10).
I'm using MySQL DBMS
This is the echo of $update_begin_insurance:
UPDATE `vehicles`
SET `begin_insurance_date` = '2017-06-10'
WHERE `plate` = 'ccccc'
UPDATE
This is the full PHP code of my page:
<?php
require_once "connect_db.php";
$plate = $_POST["plate"];
$begin_insurance = $_POST["begin_insurance"];
$end_insurance = $_POST["end_insurance"];
$fuel_economy = $_POST["fuel_economy"];
$fuel_type = $_POST["fuel_type"];
$response = array();
try
{
$conn->beginTransaction();
if ($begin_insurance != "")
{
$update_begin_insurance = "UPDATE `vehicles`
SET `begin_insurance_date` = '$begin_insurance'
WHERE `plate` = '$plate'";
$conn->query($update_begin_insurance);
}
if ($end_insurance != "")
{
$update_end_insurance = "UPDATE `vehicles`
SET `end_insurance_date` = '$end_insurance'
WHERE `plate` = '$plate'";
$conn->query($update_end_insurance);
}
if ($fuel_economy != "")
{
$update_fuel_economy = "UPDATE `vehicles`
SET `fuel_economy` = $fuel_economy
WHERE `plate` = '$plate'";
$conn->query($update_fuel_economy);
}
if ($fuel_type != "")
{
$update_fuel_type = "UPDATE `vehicles`
SET `id_fuel` = $fuel_type
WHERE `plate` = '$plate'";
$conn->query($update_fuel_type);
}
$response["post"] = $_POST;
$response["error_code"] = "0";
$response["error_message"] = "none";
$response["driver_error_code"] = "0";
}
catch (PDOException $e)
{
if ($conn->inTransaction())
{
$conn->rollBack();
}
$response["post"] = $_POST;
$response["error_code"] = $e->getCode();
$response["error_message"] = $e->getMessage();
$response["driver_error_code"] = $e->errorInfo[1];
}
echo json_encode($response);
?>
As I said before, I don't get any exception (as you can see, I also print the $_POST array to check if the params are received correctly, and yes, they are).
This is what echo json_encode($response) prints:
{
"post":
{
"plate":"ccccc",
"begin_insurance":"2017-06-10"
},
"error_code":"0",
"error_message":"none",
"driver_error_code":"0"
}
I'm sure the connection works correctly because I've got others PHP files which execute some INSERT queries, and they works correctly.
I've solved the problem, I was missing the $conn->commit().

PHP MySql PDO Multiple insert doesn't work

I have this code for a multiple insert query (I have to transfer data from db to another and makes some update, so I wanna use a code that could do all this automatically)
$query = "select * from pubblicate order by idPubblicate asc";
$dbh = newPdo2();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query);
$sth->execute();
$count = 0;
$query2 = "insert into published_offer
(codice_onshop,nome,inbreve,anteprima,
galleria1,galleria2,galleria3,galleria4,prezzo,
tp_prezzo,bonus_usabile,proposta,condizioni,
prenotare,categoria,description,keywords,
valido_da,valido_a) ";
while($offerta = $sth->fetch(PDO::FETCH_ASSOC)) {
$array[$count]['id'] = $offerta['idPubblicate'];
$array[$count]['co'] = $offerta['codiceOfferta'];
$array[$count]['no'] = $offerta['nomeOfferta'];
$array[$count]['ib'] = $offerta['inBreve'];
$array[$count]['ke'] = $offerta['keywords'];
$array[$count]['de'] = $offerta['description'];
$array[$count]['pr'] = $pfferta['prezzo'];
$array[$count]['pe'] = $offerta['persona'];
$array[$count]['da'] = $offerta['daTimer'];
$array[$count]['a'] = $offerta['aTimer'];
$array[$count]['an'] = $offerta['anteprima'];
$array[$count]['g1'] = $offerta['galleria1'];
$array[$count]['g2'] = $offerta['galleria2'];
$array[$count]['g3'] = $offerta['galleria3'];
$array[$count]['g4'] = $offerta['galleria4'];
$array[$count]['pro'] = $offerta['proposta'];
$array[$count]['con'] = $offerta['condizioni'];
$array[$count]['pre'] = $offerta['prenotare'];
$array[$count]['bo'] = 999;
if($offerta['italia']=="Sì") $array[$count]['ca'] = "ita";
else if($offerta['europa']=="Sì") $array[$count]['ca'] = "eur";
else if($offerta['mondo']=="Sì") $array[$count]['ca'] = "mon";
$count++;
}
$query2 .= "values (:co,:no,:ib,:an,:g1,:g2,
:g3,:g4,:pr,:pe,:bo,:pro,:con,
:pre,:ca,:de,:ke,:da,:a)";
$dbh = newPdo();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query2);
$i=0;
echo $array[0]['no'] . " " . count($array) . " " . $array[125]['no'] . "<br>" . $query2 . "<br>";
while($i<count($array)) {
$sth->bindParam(":co", $array[$i]['co']);
$sth->bindParam(":no", $array[$i]['no']);
$sth->bindParam(":ib", $array[$i]['ib']);
$sth->bindParam(":an", $array[$i]['an']);
$sth->bindParam(":g1", $array[$i]['g1']);
$sth->bindParam(":g2", $array[$i]['g2']);
$sth->bindParam(":g3", $array[$i]['g3']);
$sth->bindParam(":g4", $array[$i]['g4']);
$sth->bindParam(":pr", $array[$i]['pr']);
$sth->bindParam(":pe", $array[$i]['pe']);
$sth->bindParam(":bo", $array[$i]['bo']);
$sth->bindParam(":pro",$array[$i]['pro']);
$sth->bindParam(":con",$array[$i]['con']);
$sth->bindParam(":pre",$array[$i]['pre']);
$sth->bindParam(":ca", $array[$i]['ca']);
$sth->bindParam(":de", $array[$i]['de']);
$sth->bindParam(":ke", $array[$i]['ke']);
$sth->bindParam(":da", $array[$i]['da']);
$sth->bindParam(":a", $array[$i]['a'] );
$sth->execute();
$i++;
}
But this code doesn't work. I've also tried to use try-catch(PDOException) for $sth->execute() but it doesn't show me anything.
Why?
Who says "this question is a duplicated" doesn't read really the question. Infact the error was a wrong character: $array[$count]['pr'] = $pfferta['prezzo'] would be been $array[$count]['pr'] = $offerta['prezzo']so I couldn't find an answer in another question.
Try adding some simple checks that things actually worked like this
$res = $sth->execute();
if ( ! $res ) {
echo sprintf('ERROR: %d - %s', $sth->errorCode(), $sth->errorInfo() );
}

Dynamically create a SQL statment from passed values in PHP

I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.

Categories