Two if(isset($_POST) arrays in one update query? [duplicate] - php

This question already has an answer here:
Update query with two post array's
(1 answer)
Closed 7 years ago.
I am trying to bring an id from a hidden form on a previous page and using it as a variable as part of an update query.
The path to this point is....:
Log in to admin area (using a different table)...
Search 'businesses' database for entry...
Entry displays with an update button, the update button has a hidden ID... value that gets posted to this page through "submit"...
if(isset($_POST["submit"]) && isset($_POST["submituname"]))
{
$id = $_POST["id"];
$name = $_POST["uname"];
}
$query = mysqli_query($db, "UPDATE businesses SET username='$name' WHERE id='$id'");
if($query)
{
$msguname = "<p>Your username has now been updated.</p>";
}
Thanks

You need to use isset() on both variables to check them both.
if(isset($_POST['submit']) && isset($_POST["submituname"]))
You're sql query is current open to injection attack, make sure you use PDO or mysqli_real_escape_string().

Few mistakes..
Is that all functions must be inside your IF.. (so they are triggered only when its a post request and etc.
You must set isset to both post params which you are checking
What will you do if id is not set ? In that case I am giving a small easy trick by using filter_input which return NULL on not set param (another thing is escaping but I will leave you small task to learn how to escape vars..)
Last thing is your if($query) .. this is wrong check if you have any success.
Here is a working copy
if(isset($_POST['submit']) && ($_POST["submituname"])) {
$id = filter_input(INPUT_POST, 'id');
$name = filter_input(INPUT_POST, 'name');
$query = mysqli_query($db, "UPDATE businesses SET username='{$name}' WHERE id={$id}");
if(mysqli_affected_rows($db) === 1){
$msguname = "<p>Your username has now been updated.</p>";
}
}

Related

Save button that can also update once the record is already saved on the database

I was wondering how to construct the correct syntax for the if-else statement, or if there's something missing in my code.
<?php
include "../dbcon.php";
session_start();
ob_start();
$sql = mysqli_query($con,"SELECT * FROM clientdocuments WHERE docID = $_POST[docID]");
$rows = mysqli_fetch_array($sql, MYSQLI_ASSOC);
//IF CSS input value is filled
if(!empty($_POST)){
$output = '';
$message = '';
$docID = mysqli_real_escape_string($con, $_POST["docID"]);
$docSIG_Contract = mysqli_real_escape_string($con, $_POST["docSIG_Contract"]);
//I don't get what this "if(isset($_POST["docID"])){" purpose (Sorry very new to php)
if(isset($_POST["docID"])){
if (!empty($docID)) {
$query = "UPDATE clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //UPDATE ONCE docID ALREADY EXIST ON THE DATABASE
} else {
$query = "INSERT INTO clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //INSERT IF THE docID doesn't exist yet
}
$str = mysqli_query($con,$query);
if(!$str){
echo 'FAILED';
}
}else{
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
}
}
?>
remove this if statment: if (!empty($docID)) {
Make sure that u send with each post update the "docID" value
if(isset($_POST["docID"])) statement checks to see whether the input with the name docID has a value.
if(!empty($_POST)) I am not sure whether this will work, my guess is that you are trying to check whether the request method is POST (if the save button was clicked). For this I use
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
I would then check to see whether docID has a value ie
(isset($_POST["docID"])) OR (!empty($_POST["docID"]))
Difference between isset and !empty
What's the difference between 'isset()' and '!empty()' in PHP?
If there is a value, $query would be the update statement
If there is no value $query would be the insert statement In this situation don't enter the DocID value (because then it would always be 0 which will also cause errors)
Hope that makes sense!

Updating database info from php, not saving

I have this code and it seems to be working. The values are updating, but when I reload the page the updated values are without any value. For example now I have set the title as "blablabla" and when I reload the page it's changing to "".
This is the code
<?php
$title = $_POST['title'];
$meta = $_POST['meta'];
$email = $_POST['email'];
$analytics = $_POST['analytics'];
$query = "UPDATE websettings SET title = '$title', meta = '$meta', email = '$email', analytics = '$analytics' WHERE id = '1'";
if(mysql_query($query)){
echo "success";
}
else {
echo "fail";
}
?>
Your code applies $_POST variables to the database, but doesn't check if the client actually posted anything. Better to check if $_POST contains array items (if a form was posted), and check if each of those is set (if the user filled in the right fields), and validate the user input before saving (phone numbers, emails etc formatted correctly).
And as was pointed out in the comments you are vulnerable to SQL injection attack - one of the first things you should address.
Try turning on more PHP errors too - these would flag as unset variables for quicker fixing.

Session Confliction Error

Am creating a website where people can leave their opinions on releases by rating them and this gets stored into a MySQL database which is driven by PHP.
I have a feedback form for one particular release, which (lets say in this example) has the ID of 35. When I send a user another one which has the ID of 36 and the user has both windows open, the PHP processing code stores the responses from ID 35 but with ID 36. The page redirects to the previous page when the database already has a 'reaction_reacted' value of '1'.
Is there a way to solve this?
Here is an example of my code. The $promo_id, reaction_id and username are passed to it from the previous page when submission occurs.
session_start();
include 'connect.php';
mysql_connect($host,$db_user,$db_password);
mysql_select_db($database);
$promo_id = $_SESSION['promo_id'];
$reaction_id = $_SESSION[reaction_id];
$username = $_SESSION['username'];
if(isset($_SESSION['username']))
{
// Check to see if Receipt and DJID values are entered
$queryb = "select reaction_ID from reactiondata where reaction_ID='$reaction_id' AND reaction_username='$username' AND reaction_promoID='$promo_id' and reaction_reacted='1'";
$result2 = mysql_query($queryb) or die(mysql_error());
while($row = mysql_fetch_array($result2)){
header('Location: ' . $_SERVER['HTTP_REFERER']);
// session_destroy();
// exit;
}
if ($reaction_id && $promo_id != null)
{
$p4support = $_POST['DJsupport'];
$p4favouritemix = $_POST['FavMix'];
$p4score = $_POST['score'];
$p4comment = $_POST['DJcomment'];
$query = "UPDATE reactiondata SET reaction_username='$username', reaction_promoID='$promo_id', reaction_support='$p4support', reaction_favouritemix='$p4favouritemix', reaction_score='$p4score', reaction_comment='".mysql_real_escape_string($p4comment)."', reaction_reacted='1' WHERE reaction_ID='$reaction_id'";
mysql_query($query) or die('Error in MySQL query. Here is the error message: '.mysql_error());
$query7 = "UPDATE reactiondata SET reaction_time=NOW() WHERE reaction_ID='$reaction_id'";
mysql_query($query7) or die('Error in MySQL query. Here is the error message: '.mysql_error());
}
Thanks
CP
P.S I know I am using depreciated mysql_query methods, I just want the page to function properly before I start preventing SQL Injection attacks.
The easiest solution (one of the...) is to add the reaction_id as a hidden form field to the form instead of using a session. That way the reaction is always linked to the correct ID when the form is posted.
You should not use a session for that as the session will span all open windows and tabs in the browser so it is not suitable to maintain the state of a specific tab.

Updating only the submitted fields from account settings page

I have an account settings page which will detect any changed fields and submit those fields via jquery.ajax to a php file, the php file intakes it and validates each field on some different cases and if any of them throw an error it returns the error, exits, and requires user to reinput the field. That all works fine... however...
I'm having my problem with how to build a loop to only update the submitted fields. Currently the php file has this structure:
Check for ajax request {
Validate fields...
Update Fields...
}
My "Update Fields" code looks like this and yes it won't work this way, I know:
// grab all variables except passwords
$email = mysql_real_escape_string($_POST['email']);
$newpass = mysql_real_escape_string(md5($_POST['newpass']));
$bname = mysql_real_escape_string($_POST['bname']);
$bemail = mysql_real_escape_string($_POST['bemail']);
$sql = "UPDATE usertable SET email='$email', password='$newpass', bname='$bname', bemail='$bemail' WHERE username = '$user'";
mysql_query($sql);
$msg = "Account updated successfully.";
header('Cache-Control: no-cache, must-revalidate');
header('Expires: '.date('r', time()+(86400*365)));
header('Content-type: application/json');
echo json_encode(array(
'valid' => yes,
'msg' => $msg,
));
exit();
The line in question is the $sql = "Update usertable..." line. How can I write a php loop to grab all the posted variables as an array and somehow use those to build an update query string... if you need anything else let me know. Asking a lot, but I've been thinking for four hours and can't figure out a way to do it without lots of run around non-direct coding.
Also: Is there a way to return ALL the unvalidated fields? General idea, such as using an array and for each loop or something? Currently if let's say, the email field and password field don't validate, it only shows the email field as needing to be re-entered because it shows up first in the php file. I would prefer it to tell them ALL the fields that didn't validate. I know it just had to do with the position of my code and the way I'm just hand coding each validation (which is the long way) so any insight into this will help me a BILLION especially with future pages on the backend.
Thanks for any help guys!
This will only update the fields which are within the $_POST array and defined in $fieldsToUpdate (So you can exclude fields):
$user = mysql_real_escape_string($user);
$fieldsToUpdate = array('email', 'bname','bemail');
$set = array();
foreach($_POST as $key=>$value){
if(in_array($key,$fieldsToUpdate)){
$set[] = $key."='".mysql_real_escape_string($value)."'";
}
}
if(count($set) > 0){
$query = "UPDATE usertable SET ".implode(',',$set)." WHERE username = '$user'";
// rest of your code;
}
Also, mysql_real_escape_string() is deprecated, think about using PDO

Can you use $_POST in a WHERE clause

There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.

Categories