I want to create a simple SQL UPDATE query which can check via an IF statement that the passed POST variable is empty or not. If empty then won't modify the original value, if not then update. I just can't figure out how I did it before.
It should be something like that, but not working:
$sql = "UPDATE Clients SET Name = IF(" . $_POST['edit_client_name'] .
" = '', Name, " .
mysqli_real_escape_string( $this -> link, $_POST['edit_client_name'] ) .
" WHERE Id=" . $_GET['selected_client'] . "";
You need to check this in application not query. Like
if(isset($_POST['edit_client_name'])){
$name = mysqli_real_escape_string( $this -> link, $_POST['edit_client_name'] );
$id = mysqli_real_escape_string( $this -> link, $_GET['selected_client'] );
mysqli_query("UPDATE Clients SET Name = '".$name."' WHERE Id=".$id."');
}
You can tweak through the SQL instead of doing checks in the DB.
I skipped the SQL Injection prevention part.
<?php
if(empty($_POST['edited_client_name'])){
$namequery = '';
}
else{
$namequery = "Name = '".$_POST['edited_client_name']."'";
}
$sql = "UPDATE Clients SET ".$namequery." WHERE ID = ".$_GET['selected_client'];
echo $sql;
?>
returns:
UPDATE Clients SET Name = 'foo' WHERE ID = 1
when edited_client_name is provided,
else returns:
UPDATE Clients SET WHERE ID = 1
Hope this will give you an idea what to do with your code.
Related
On a table that displays data from a database, I have a form that has a text area on which a user can type a receipt number and submit to save in a database for a specif row. The PHP code below is what updates the database after the form is submitted.
I want to pick the rest of the details for the specific row so I used the $_POST['id'] on which the receipt has been submitted. The id is the primary key. I'm however having a challenge since I can't fetch data from the database using $id = $_POST['id'];I created before outside the function The update statement works perfectly but the SELECT STATEMENTdoesn't . How do I go about it? Any one?
if(isset($_POST['submit'])) {
$rec = $_POST['receipt'];
$id = $_POST['id'];
//reate connection
$sql = "UPDATE customer SET `receipt` = '".$_POST['receipt']."', `date_entered` = NOW(), `receipt_lock` = 1 WHERE `id` = '".$_POST['tid']."' AND receipt_lock = 0";
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit();
$conn->close();
}
function wall(){
global $recp;
global $id;
// Create con
$sql = "SELECT * FROM customer WHERE id ='$id'";
$result1 = mysqli_query($conn, $sql);
$resultarr = mysqli_fetch_assoc($result1); // fetch data
$name = $resultarr['name'];
echo "$name"; //Does not display
$amount = $resultarr['amount'];
$transaction_id = $resultarr['trans_id'];
$date = $resultarr['time_paid'];
}
else {
echo "this is not right!;
}
wall();
Ignoring all the (valid) questions about SQL security and just addressing your problem - how about passing the $id variable as a parameter to your wall function.?
wall($id);
function wall($id){
$sql = "SELECT * FROM customer WHERE id ='$id'";
// ... use prepared statements for security...
...
}
Looks like you are using $_POST['tid'] instead of $_POST['id'] or $id in your SQL-query.
What you are doing there is a big nono, in terms of security. Make sure you escape your POST parameters before adding them inside your query.
$id = $_POST['id'];
$id = mysqli_real_escape_string($conn, $id);
http://php.net/manual/ro/mysqli.real-escape-string.php
Think about sending data as parameters of a function function wall($id) instead of a global parameter.
Require("dbconnect.php");//works is used on other another page
echo $Customer_id;//Displays correctly
Can anyone help?
First Check that use session variable is getting the data or not.
If the Customer id is of varchar then you are missing single inverted comma in where clause.
session_start();
$Customer_id = $_SESSION['id'];
Require("dbconnect.php");//works is used on other another page
$sql = "SELECT Job_id FROM Job";
$sql.= " WHERE Job_Customer_id = '$Customer_id'";
$stmt = $dbh->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$Job_id = $row['Job_id'];
echo $Customer_id;//Displays correctly
echo $Job_id;//Curently dose not display anything
Change the $sql.= line to this:
$sql.= " WHERE Job_Customer_id = '$Customer_id'"
with the ' around $Customer_id.
I have been trying to do this for hours now, and I can't quite get my head round it. I have a table called "requests" that has the columns "deletekey" and "deleted". "deletekey" is a random unique number (data-type text), and "deleted" is by default set to 0 (data-type boolean), and when the user inputs the deletekey, it changes "deleted" to 1.
But I can't get it to work.
Here is the code I have, and I have no idea what I'm doing wrong:
$key = $_GET["delkey"];
$link = mysqli_connect("localhost","username","password","dbname");
$query = 'UPDATE requests SET deleted = True WHERE deletekey = "$key"';
$result = $link->query($query);
This should help, and will also provide protection against SQL injection:
$link = mysqli_connect("localhost","username","password","dbname");
$key = $link->real_escape_string($_GET["delkey"]);
$query = sprintf("UPDATE requests SET deleted = 1 WHERE deletekey = '%s'", $key);
$result = $link->query($query);
Shouldn't it be WHERE deletekey = '$key', then? The deleted field could NEVER equal whatever's in $key, since deleted is a simple boolean, and $key is probably an int/char/varchar-type thing.
Note that you are vulnerable to SQL injection attacks. Stop working on this sort of code until you've learned about the problem and how to avoid it.
Its deletedkey = "$key" right ? and not deleted = "$key" :
$key = $_GET["delkey"];
$link = mysqli_connect("localhost","username","password","dbname");
$query = 'UPDATE requests SET deleted = true WHERE deletedkey = "$key"';
$result = $link->query($query);
Try this?
$link = mysqli_connect("localhost","username","password","dbname");
$key = $link->real_escape_string($_GET["delkey"]);
$query = "UPDATE `requests` SET `deleted` = true WHERE `deletedkey` = $key";
$result = $link->query($query);
$query = 'UPDATE requests SET deleted = 1 WHERE deletekey = "$key"';
the query is a string. And to add a variable to a string you need to type
$query = 'UPDATE requests SET deleted = True WHERE deleted = '".$key."';
the difference is how to make a variable put into the string. You have to do like this in php.
$query = "randomtext ". $randomvar ." ";
where the important point is to ". $var ." inside the string. This i similar to javas "+ var +"
I've got such query:
$sql = "UPDATE test_accs SET
acc_owner = '$owner_id',
acc_policy_version = '$version',
acc_policy_last_update = '$approved',
acc_policy_next_update = '$renewed'
WHERE acc_id = '1'";
Now, all of these values on the web folmular are optional, one can set one of these values, two, or so. Now, after I submit the form, it goes in the query like that:
UPDATE test_accs SET acc_owner = '2', acc_policy_version = '1.2', acc_policy_last_update = '2012-12-19', acc_policy_next_update = '2012-12-18' WHERE acc_id = '1'
It works only when I submit all values from the form. Can you please show me how could it work even if not all the values has been sent, just for example one of them?
When I set one value (f.ex. policy version), it looks like that:
UPDATE test_accs SET acc_owner = '', acc_policy_version = '1.2', acc_policy_last_update = '', acc_policy_next_update = '' WHERE acc_id = '1'
and it isn't working.
It might be possible cause of the acc_owner table values?
#1366 - Incorrect integer value: '' for column 'acc_owner' at row 1
Thanks in advice.
Form:
echo '<td>Change owner: <select name="owner_id" onchange="showUser(this.value)" style="font-size:9px"><option value="">Select a person:</option>';
while($owners = mysql_fetch_array($owners_query)) { echo '<option value="'.$owners['id'].'">'.$owners['surname'].' '.$owners['name'].'</option></h2>'; } echo '</select></td>';
echo "<td><input name='version' style='width:50px;text-align:center' placeholder='0.0' /></td>";
echo "<td><input name='approved' class='datepicker_all' readonly='readonly' style='text-align:center' placeholder='1999-01-01' /></td>";
echo "<td><input name='renewed' class='datepicker_all' readonly='readonly' style='text-align:center' placeholder='1999-01-01' /></td>";
One way to accomplish this is to use an expression in the SQL statement that tests whether the supplied value is an empty string. If the supplied value is an empty string, then use the current value of the column as the value to assign to the column. Otherwise, assign the supplied value to the column.
In the example below, the each of the supplied values have to be include TWICE in the statement: once in the conditional test, and then again, as a possible result of the conditional test.
This statement:
UPDATE test_accs
SET acc_owner = IF('2'='',acc_owner,'2')
, acc_policy_version = IF('1.2'='',acc_policy_version,'1.2')
, acc_policy_last_update = IF('2012-12-19'='',acc_policy_last_update,'2012-12-19')
, acc_policy_next_update = IF('2012-12-18'='',acc_policy_next_update,'2012-12-18')
WHERE acc_id = '1'
is equivalent to the first UPDATE statement in the question, in that it sets the value of all four columns to the new specified value.
This statement:
UPDATE test_accs
SET acc_owner = IF(''='',acc_owner,'')
, acc_policy_version = IF('1.2'='',acc_policy_version,'1.2')
, acc_policy_last_update = IF(''='',acc_policy_last_update,'')
, acc_policy_next_update = IF(''='',acc_policy_next_update,'')
WHERE acc_id = '1'
changes ONLY the value of the acc_policy_version column, the values of the other three columns will remain unchanged.
This is not necessarily the best approach, but it is workable for some scenarios.
It's also possible to create an expression that requires each supplied value be specified in the statement one time, although I think these expressions are a little less intuitive:
SET acc_owner = COALESCE(NULLIF( '' ,''),acc_owner )
, acc_policy_version = COALESCE(NULLIF( '1.2' ,''),acc_policy_version)
That's essentially doing the same thing as the examples above.
If the supplied value is equal to '' (like it is for acc_owner in the example above), then the NULLIF expression will return a NULL. The COALESCE function essentially causes that NULL value to be skipped, and the current value of the column will remain unchanged (the current value of the column is assigned to the column.)
If the supplied value is not equal to '' (like it is for acc_policy_version in the example above), then the NULLIF expression will return the supplied value. The COALESCE function will pick up that value, and assign it to the column.
Check if acc_owner is empty and set it to zero is one option, you can't insert empty space if column is supposed to hold integer - or just don't do update unless you have int value
1:
if(strlen($acc_owner)==0){
$acc_owner=0;
}
2:
if(is_int($acc_owner)){
//update it
}
Is the value for the Integer field required? If not, then check for the GET/POST value being set, and if its empty, don't include that in your update statement.
if(isset($_GET['acc_id'])) {
$acc_id = $_GET['acc_id'];
$sql = "UPDATE test_accs SET ";
if(isset($_GET['version'])) {
$version = $_GET['version'];
$sql = $sql . "acc_policy_version = " . $version . ",";
}
if(isset($_GET['owner_id'])) {
$owner_id = $_GET['owner_id'];
$sql = $sql . "acc_owner = " . $owner_id . ",";
}
$sql = $sql .
"acc_policy_last_update = '$approved',
acc_policy_next_update = '$renewed'
WHERE acc_id = " . $acc_id;
//Execute SQL
echo "successfully updated " . $acc_id;
} else {
echo "invalid acc_id";
}
1 - Convert your $owner_id to type int
$owner_id = (int)$owner_id;
2 - Use a condition to update this field only if a value > 0
$sql = "UPDATE test_accs SET " .
($owner_id > 0 ? "acc_owner = '$owner_id', " : "") .
"acc_policy_version = '$version', " .
"acc_policy_last_update = '$approved', " .
"acc_policy_next_update = '$renewed' " .
"WHERE acc_id = '1'";
Note : Be carrefull, your variables seems not correctly securised and you have risks of mysql injections. See http://php.net/manual/fr/mysqli.real-escape-string.php.
And, maybe you should think about use the PDO php extension (http://fr2.php.net/manual/en/intro.pdo.php) for you mysql developpement or any orm ?
You should verify all values that came from a html form. Than, if you mysql field can be NULL, just set NULL to php var:
if (strlen($owner_id) == 0) {
$owner_id = NULL;
// OR
$owner_id = 0;
} else {
$owner_id = addslashes($owner_id);
}
$sql = "UPDATE test_accs SET
acc_owner = '$owner_id',
acc_policy_version = '$version',
acc_policy_last_update = '$approved',
acc_policy_next_update = '$renewed'
WHERE acc_id = '1'";
You can initialize variables holding values for optional fields with default values according to their respective data types.
Please refer the code snippet mentioned below.
$owner_id=0;
$version=0;
$approved='';
$renewed='';
if($_SERVER['REQUEST_METHOD']=='POST')
{
extract($_POST);
}
$sql = "UPDATE test_accs SET
acc_owner = '$owner_id',
acc_policy_version = '$version',
acc_policy_last_update = '$approved',
acc_policy_next_update = '$renewed'
WHERE acc_id = '1'";
I have 2 variables that contain a a string of text. I need to update them in the table, but out of the 20 + different variations of about 5 different scripts that I've tried out, it just doesn't update!
I can update using this:
mysql_query("UPDATE cart SET quantity = $q WHERE sessionid='" .session_id(). "' AND description = '$d'") or die(mysql_error());
but I am now working on a different page, where I need a slightly different update query. Which is:
UPDATE cart SET quantity = $q WHERE sessionid = $somethin AND description = $desc
And for that I have:
mysql_query("UPDATE cart SET quantity = $q WHERE sessionid = $o AND description = $d") or die(mysql_error());
(I have tried many variations with different quotes in different places for the above query, but nothing works!)
I have also tried:
$conn = mysql_connect("my01..com", "dbase", "2354ret345ert");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'UPDATE cart
SET quantity="'.$q.'"
WHERE sessionid="$o" AND description = "$d"';
mysql_select_db('mysql_94569_dbase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
That last one doesn't display any errors, in fact, it even tells me that it has successfully updated! But it's lying. It hasn't updated anything.
Can someone please help me out here, I am really getting sick of reading tutorial after turorial and never learning anything because they all have differnt syntax and none of it seems to work.
What I would like to do is:
UPDATE table SET columnname = $this WHERE thiscolumn = $this AND thiscolumn = $that
$this = $var
Thank you
You are missing the quotes in description and SessionID, do it like this:
mysql_query("UPDATE cart
SET quantity = '".$q."'
WHERE sessionid = '".$o."' AND description = '".$d."'");
In order to save you confusion, I would recommend start using concatenation operator (eg 'UPDATE '.$table .' SET ...')instead of writing variables directly to strings (eg. "UPDATE $table SET ...").
in this case your query would look like:
mysql_query("UPDATE cart SET quantity = ".$q." WHERE sessionid='" .session_id(). "' AND description = '".$d."'") or die(mysql_error());
This might help you to find problems with quotes and parenthesis quicker
BAD:
I had this query in php:
$query = "UPDATE users SET username = ".$nume." WHERE id = ".$userID;
That did this SQL:
UPDATE users SET username = elev WHERE id = 2
GOOD: For it to work I changed it to this php:
$query = "UPDATE users SET username = ".'"'.$nume.'"'." WHERE id = ".$userID;
That did this SQL:
UPDATE users SET username = "elev" WHERE id = 2