Find $_POST variable with same name as other variable - php

I have a form being passed in $_POST where the names of each field correspond with data in a database
$_POST['test']; (has a value of 1)
$_POST['prod']; (has a value of 2)
Both test and prod are unique names in the database. Is there a way I can dynamically grab a $_POST variable? For example (some code that doesn't work)
$getServerIDs = $link->query("SELECT * FROM servers");
while($row = $getServerIDs->fetch_assoc()){
$serverName = $row['name'];
$newDisplayID = $_POST['$sName'];
$updateDisplayID = "UPDATE servers SET displayID = $newDisplayID WHERE name = $servername";
$runQuery = $link->query($updateDisplayID);
The $_POST['$sName'] is the line of code being the problem. Whats the best way to fix this?

The problem is with line $newDisplayID = $_POST['$sName']; you used single quote and when you put variable in single quote then it is not parsed by php use $_POST[$sName]; or $_POST["$sName"];
Edited
DEMO

Dont use quotes OR use double quotes.
Also be carefull you are using highly insecure code. Google sql injection

You can use array_keys() to get all keys inside and array as $_POST.
$keys = array_keys( $_POST );
But be aware, that your user could add any key there in their submission. So you should in any case filter and sanitize this input!
Down the line you could then use this $keys array to do your output.

Related

Can't $_GET contents of field using quoteid

I am sending myself crazy figuring out what the issue is with the following code. All names within the database are exact as I have them here however I can't seem to get the info from the quote using $quoteid however when I type in an id static e.g. quoteid = 12 I can filter through the data.
Obviously this isn't ideal.
<?php
$quoteid = $_GET["quoteid"];
if ($_GET['quoteid']) {
$quoteid = $_GET["quoteid"];
}
$quote = $db->getRow("SELECT * FROM quotes WHERE quoteid = $quoteid");
?>
Html
<h1><?php echo $quote->description;?></h1>
Any help would be greatly appreciated.
Thanks,
Melissa
Note that you need to put the PHP variables inside single quotes when writing SQL queries. Do it like in the example:
$quote = $db->getRow("SELECT * FROM quotes WHERE quoteid = '$quoteid'");
why you getting again and again $_GET["quoteid"] and also use single for variable when writing SQL queries
<?php
$quoteid = $_GET["quoteid"];
if (!empty($quoteid)) {
$quote = $db->getRow("SELECT * FROM quotes WHERE quoteid = '$quoteid'");
}
else {
echo 'quote id is empty';
}
?>
also use mysql_real_string_escape() to prevent sql injection
You should do the following... basic debugging.
print_r or var_dump for $_GET to see if and how "quoteid" is set up
in the $_GET superglobal
echo your SQL (instead of mysql_query just echo it) and run it in
phpmyadmin if it seems ok -- you might have something you missed out
somewhere
That way you should be able to figure out your issue faster
there is mistake in query syntax with $quoteid variable. you should use this one-
global $db;
$quote = $db->get_row("SELECT * FROM quotes WHERE quoteid ='".$quoteid."'");

Assign POST values to an array in a loop and put array into a database

I have an array containing the names of form input names:
$minmax = array('bed_min', 'bed_max', 'rec_min', 'rec_max', 'bath_min', 'bath_max', 'value_min', 'value_max');
The names are identical to the corresponding columns in a database. Instead of using an sql query like so:
$bed_min=$_POST['bed_min'];
$bed_max=$_POST['bed_max'];
$rec_min=$_POST['rec_min'];
$rec_max=$_POST['rec_max'];
$bath_min=$_POST['bath_min'];
$bath_max=$_POST['bath_max'];
$value_min=$_POST['value_min'];
$value_max=$_POST['value_max'];
$query = "UPDATE first_page SET bed_min='$bed_min', bed_max='$bed_max', rec_min='$rec_min', rec_max='$rec_max', bath_min='$bath_min', bath_max='$bath_max', value_min='$value_min', value_max='$value_max', WHERE email_address='$email' ";
Is there a way to automate all this into a smaller lump of code? I know the POST values should not be added to the query diectly, so maybe a loop to assign the POST values to a corresponding array of variables using something like:
foreach ($minmax as $var){
$var = $_POST[$var]
}
(nb i dont think this snippet will work but ive added it because I think with a bit of editing it might!)
After the list of variables have been assigned the POST values, do the update in the $query using two arrays, one with the list of values and one with the list of database columns. Again I dont know how this will work, so pointers would be helpful!
You don't really need the $minmax array of form input names since you can get those from the keys of $_POST.
If the values are all numbers, like they seem to be, then you could do it all in one line like this:
$query = "UPDATE first_page SET " . vsprintf(implode("='%d', ", array_keys($sanitized_POST))."='%d'", array_values($sanitized_POST))." WHERE email_address='$email'";
That's assuming you have already sanitized the items from $_POST into a new array named $sanitized_POST. I know you said in the above comment to ignore sanitization, but I thought I'd add it so you know I'm not suggesting to use the values straight from $_POST.
You could sanitize the $_POST array with something like this:
$sanitized_POST = array_map(function($item) {
return mysqli::real_escape_string($item);
}, $_POST);
Honestly though, you should try to come up with a solution that uses prepared statements.
On a side note, if you have the sanitized post array, then this one line will essentially do what Quixrick has done with variable variables in one of the other answers:
extract($sanitized_POST);
If you assume that all of the values in post have the same names (array keys) as your columns, then something like this could work for you:
$query = "UPDATE first_page SET ";
foreach ($_POST as $key => $var){
$query .= " $key='$var',";
}
$query = rtrim($query,',') . " WHERE email_address='$email' ";
You probably want to use 'Variable Variables' here. Basically, you'd use a double dollar sign $$ to create a variable with the name of the array value.
$_POST['bed_min'] = 'Rick';
$minmax = array('bed_min', 'bed_max', 'rec_min', 'rec_max', 'bath_min', 'bath_max', 'value_min', 'value_max');
foreach ($minmax as $var){
$$var = $_POST[$var];
}
print "<BR>BED MIN: ".$bed_min;
This outputs:
BED MIN: Rick

Creating a json array using concat with MySql

I'm creating a json array from MySql data using concat like this:
$id = '5705';
$sql = 'select concat("{""type:""colName"",""id"":""$id""}") as myJson from table where etc.;
$stmt = $conn->prepare($sql);
What's happening is, instead of getting data from colName from the table and the value of $id, I'm getting the result as it is in $sql. How do I break out of it and get colName and $id's value?
Current Result
{""type:""colName"",""id"":""$id""}
Desired Result
{""type:""novice"",""id"":""5705""}
//Here novice is data from colName, and 5705 is the value of $id
Please DON'T DO THAT. Trying to format data into JSON in your SQL will be fragile as encoding things into JSON is subtly more tricky that you would expect and you will inevitably get it wrong.
You should use the json_encode function in PHP. It will work reliably whereas your code will almost certainly break.
$dataArray = array();
while($statement->fetch()){
$data = array();
$data['type'] = $typeColumn;
$data['id'] = $id;
$dataArray[] = $data;
}
json_encode($dataArray, JSON_HEX_QUOT);
Also, formatting data to send to a client really shouldn't be part of an SQL query.
You need a better concatenation either in query and php
'select concat("{""type:"",colName,"",""id"":""'.$id.'""}")
Despite it is not really needed you could surround column name with backticks `
Your variables inside your string are not substituted with their values, as you got single quotes. Double quoted strings will expand variables with their values
Thus, you could invert your quotes, like this, in order to get the actual values of your variables:
$sql = "select concat('...')"

How to only update an sql table column if a variable is not empty with php?

I am getting my variables from form fields using php :
$url=$_POST['url'];
$tags=$_POST['tags'];
$skillArea=$_POST['skill_area'];
$description=$_POST['description'];
$slideshowImageFileName=($_FILES['imageNameSlideshow']['name']);
But when I run my sql insert query, I get an error if one of the variables is empty, so I have taken to write if statements to deal with this to rewrite the query string, but surely, that's not the answer? It seems very messy
if(empty($slideshowImageFileName)){
$query1="INSERT INTO portfolio (item_name,image_path,description,url) VALUES('$itemName','$imageFileName','$description','$url')";
}else{
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
}
I suppose you are looking for something like this:
$slideshowImageFileName = (isset($_FILES['imageNameSlideshow']['name']) && !empty($_FILES['imageNameSlideshow']['name'])) ? $_FILES['imageNameSlideshow']['name'] : NULL;
This will check if the name of the slideshowimage is set and not empty. if it is NULL will be assigned to the variable, if its correct the value will be assigned.
You could replace NULL with "" if you want an empty string to be added.
Try to set the value of $slideshowImageFileName to empty string or a single space as your database table will accept, and use the second query always.
if(empty($slideshowImageFileName)){
$slideshowImageFileName = "";
}
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
I am agreed with Mr. Ray. But there is another solution apart from that. Probably slideshow_image_path field on the table doesn't allow null. So you may change the attribute by allowing null and it will work.
I'd probably construct a builder if I'm sure I'll get a lot of optional data.
Like this:
$acceptedKeys = array
('item_name',
'image_path',
'description',
'url',
'slideshow_image_path');
$inserts = array();
foreach($_GET as $key => $var) {
if(in_array($key, $acceptedKeys)) {
// clean and validate your keys here!
$inserts[$key] = $var;
}
}
$customKeys = implode(array_keys($inserts), ',');
$customValues = implode($inserts, ',');
$query = "INSERT INTO portfolio ($customKeys) VALUES($customValues)";
There's a few options to this.
Simplest one is to make sure the variables are always set, even if not passed through:
//Set up your database connection as normal, check errors etc.
$db = mysqli_connect($host,$user,$password,$db);
$url = isset($_POST['url']) ? mysqli_real_escape_string($db, $_POST['url']) : "";
$tags= isset($_POST['tags']) ? mysqli_real_escape_string($db, $_POST['tags']) : "";
Escaping data is good practice :) In your INSERT query you'll still need to wrap the values in quotes, or you could do that in the above code as per your preference.
http://uk3.php.net/manual/en/mysqli.construct.php

Can someone tell me why this isn't a good way to assign $_POST vars?

I am wondering if anyone can suggest a more elegant way to assign variables during PHP/mySQL form submission. This seems clunky
//include("connect.php");
mysql_connect("localhost","root","root");
mysql_select_db("noirTEST");
// assign out vars from the POST vars to get ready for SQL insertion
$thumb_image_location = $_POST['thumb_image_location'];
$large_image_location = $_POST['large_image_location'];
$password = sanitizeString($_POST['password1']);
$firstName = sanitizeString($_POST['firstName']);
$lastName = sanitizeString($_POST['lastName']);
$desc_short = sanitizeString($_POST['desc_short']);
$nationality = sanitizeString($_POST['nationality']);
$speakEnglish = sanitizeString($_POST['speakEnglish']);
$speakGerman = sanitizeString($_POST['speakGerman']);
$mainInst = sanitizeString($_POST['mainInst']);
$inspiration1 = sanitizeString($_POST['inspiration1']);
$inspiration2 = sanitizeString($_POST['inspiration2']);
$inspiration3 = sanitizeString($_POST['inspiration3']);
$inspiration4 = sanitizeString($_POST['inspiration4']);
$inspiration5 = sanitizeString($_POST['inspiration5']);
$desc_long = sanitizeString($_POST['desc_long']);
$link1name = sanitizeString($_POST['link1name']);
$link1url = sanitizeString($_POST['link1url']);
$link2name = sanitizeString($_POST['link2name']);
$link2url = sanitizeString($_POST['link2url']);
$link3name = sanitizeString($_POST['link3name']);
$link3url = sanitizeString($_POST['link3url']);
$email = sanitizeString($_POST['email']);
$proExperience = sanitizeString($_POST['proExperience']);
$haveStudio = sanitizeString($_POST['haveStudio']);
$musicTheory = sanitizeString($_POST['musicTheory']);
$composer = sanitizeString($_POST['composer']);
$teacher = sanitizeString($_POST['teacher']);
$query = "INSERT INTO NOIRusers (thumb_image_location, large_image_location, password, firstName, lastName, desc_short, nationality, speakEnglish, speakGerman, mainInst, inspiration1, inspiration2, inspiration3, inspiration4, inspiration5, desc_long, link1name, link1url, link2name, link2url, link3name, link3url, email, proExperience, haveStudio, musicTheory, composer, teacher ) VALUES ('$thumb_image_location', '$large_image_location', '$password', '$firstName', '$lastName', '$desc_short', '$nationality', '$speakEnglish', '$speakGerman','$mainInst', '$inspiration1', '$inspiration2', '$inspiration3', '$inspiration4', '$inspiration5', '$desc_long', '$link1name', '$link1url', '$link2name', '$link2url', '$link3name', '$link3url', '$email', '$proExperience', '$haveStudio', '$musicTheory', '$composer', '$teacher')";
function sanitizeString($string)
{
$string=trim($string);
$string=strip_tags($string);
$string=htmlentities($string);
$string=stripslashes($string);
return $string;
};
Would something like this work for the long first part?
foreach($_POST as $key => $value){
${$key} = $value;
sanitizeString($key);
}
It seems like every example I am seeing uses the long way or something like it .. so I am sure there is a reason why a shorter way can't / shouldn't be used. But can anyone explain it to me?
For one you should use mysql_real_escape_string as well, inside your sanitizeString function.
Or better yet, use PDO, which will escape your strings for you.
Your alternative does just do the same as enabling register_globals, which is a very bad idea (if you really wanted to do that, you could just use extract together with array_map - but don't.).
I'd suggest either looping through and sanitizing the values in $_POST (preferable in a new array, so that you have control over which values have been filtered and which has not), or by simply using the value filtered in your query (you probably want to take a look at using prepared queries as well). You could also create a list of the expected, set form values, and then loop through that list and check and filter the values as you come across them. This will allow you to check that the value actually is set and that the request contains what you'd expected.
You also want to avoid using stripslashes() unless magic_quotes have been enabled, otherwise you'll lose valid -s in your sanitize function, using strip_tags will remove a bit too much content if your field contain a <, and you want to do HTML escaping output (to HTML), not input.

Categories