Okay So for awhile I have been attempting to set GET POST and REQUEST variables dynamically.
I store the variables I want it to get or post or request inside an sql table. each variable has it's own column. In this same row it records the type I want it to try to use(GET,POST,REQUEST). I am telling you this so you see how I want to go about doing this.
Source
$snmpbq=$os_DB->query("SELECT * FROM `spiders` WHERE site = '".$site_name."'") or die(mysql_error());
$num=$os_DB->num($snmpbq);
if($num == 1)
{
//get row as an associative array
$pb=$os_DB->fetch($snmpbq);
//data request type
$req_type = $pb['net_req_type'];
$a1 = $pb['a'];
$b1 = $pb['b'];
$c1 = $pb['c'];
$d1 = $pb['d'];
$e1 = $pb['e'];
$f1 = $pb['f'];
if($req_type == "get")
{
$a = $_GET[$a1];
$b = $_GET[$b1];
$c = $_GET[$c1];
$d = $_GET[$d1];
$e = $_GET[$e1];
$f = $_GET[$f1];
}
You can accomplish this in a much cleaner way by replacing the blocks with 1 block... rather then checking the request type.
If you remove all your blocks and replace with:
$a = $_REQUEST[$a1];
$b = $_REQUEST[$b1];
$c = $_REQUEST[$c1];
$d = $_REQUEST[$d1];
$e = $_REQUEST[$e1];
$f = $_REQUEST[$f1];
As per the PHP Documents here
The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and therefore could be modified by the remote user and cannot be trusted. The presence and order of variables listed in this array is defined according to the PHP variables_order configuration directive.
Sounds like you need to use a variable variable.
$result = 'someDataBaseQueryResult';
$$result = 'cool'; // now $someDataBaseQueryResult === 'cool'
You question is a bit confusing, but you could take this to the nth degree.
Idea for the sample code:
$sReq = $pb['net_req_type'];
foreach($pb as $key => $value) {
if($key == 'net_req_type')
continue;
${$key} = $_GET[$value];
}
It's a little late, and I'm a little drunk, but I think that may be close. Haven't executed it though...
Related
<?php
include('dbLink2.php');
$quizqr = $_GET['quizQR'];
$recordsID1 = $_GET['recordsID1'];
$recordsID2 = $_GET['recordsID2'];
$m_array1=array();
$m_array=array();
$sql = "SELECT quizQR, recordsID FROM `registertestactivity` WHERE (quizQR = '$quizqr' OR recordsID = '$recordsID1' OR recordsID = '$recordsID2') LIMIT 1";
$result = #mysqli_query($link, $sql) or die();
if (#mysqli_affected_rows($link) > 0) {
while($row = #mysqli_fetch_assoc($result))
{
$m_array[]=$row;
}
} else {
$m_array1 += ["quizQR" => "NoRecords"];
$m_array1 += ["recordsID" => "NoRecords"];
$m_array[0] = $m_array1;
}
echo json_encode($m_array);
#mysqli_free_result($result);
#mysqli_close($link);
?>
Can someone help me out, i have tried the mysqli_real_escape_string and it still doesnt work :(
The $quizqr value has a '#' character in the string and this is the error msg that pops when the ajax call this php:
Because you have a # in the URL you're dealing with a URL Fragment which means that everything past the # is not available in the query string. PHP offers a flag, PHP_URL_FRAGMENT for its parse_url() function which can help you get what you need from the string.
Here is one example using the URL you provided:
$fragment = parse_url($url, PHP_URL_FRAGMENT);
echo $fragment;
$fragmentSection = explode('&', $fragment);
print_r($fragmentSection);
foreach($fragmentSection AS $section) {
if(0 != strpos($section, '=')) {
$sectionParts = explode('=', $section);
$queryParts[$sectionParts[0]] = $sectionParts[1];
}
}
print_r($queryParts);
This ultimately returns two array members which could then be used in your query:
Array
(
[recordsID1] => records_001
[recordsID2] => records_002
)
The best thing to do would be to write a function to which you pass the URL to return the elements you need.
Keep in mind that this is not fool-proof. If the URL is in a different format then what I have done here will have to be modified to work as you would like it to.
Additionally you have been given some warnings and guidance in the comments you should follow to keep your code safe and efficient, so I will not repeat them here.
I started writing this code to determine which value within 3 date of births was the highest. As I got to as far as you can see I realised this was a silly way of doing it. There will at times be 4 values or even 5 values so writing every combination like this is sloppy.
$new_date_year1 etc are pre defined from a html form.
Can someone recommend another way of doing this.
$valuename1 = "Tom";
$valuename2 = "Jack";
$valuename3 = "Fred";
if ($amount == "3") {
if ($new_date_year1 > $new_date_year2 and $new_date_year1 > $new_date_year3 and $new_date_year2 > $new_date_year3) {
$highest_amount = $valuename1;
$second_amount = $valuename2;
$third_amount = $valuename3;
}
else if ($new_date_year1 > $new_date_year2 and $new_date_year1 > $new_date_year3 and $new_date_year3 > $new_date_year2) {
$highest_amount = $valuename1;
$second_amount = $valuename3;
$third_amount = $valuename2;
}
}
Thanks is advance for any help
just in html form replace variable names from $new_date_year1 into $new_date_year[] etc.
then in php You will have array that is sortable, so:
$new_date_year[] = '2015';
$new_date_year[] = '2018';
$new_date_year[] = '2016';
You can insert data to the array in this way as well(using array_push):
// implementing an empty array.
$new_date_year = [];
//using array_push
//you can pass multiple values to the array for explain it further i will pass '2015','2016','2018' to the array.
array_push($new_date_year,'2015','2016','2018');
After adding the values to the array you can sort the array using rsort which ,
sorts an array in reverse order (highest to lowest).
rsort($new_date_year);
$highest_amount = $new_date_year[0];
$second_amount = $new_date_year[1];
$third_amount = $new_date_year[2];
I can't figure out why my loop isn't working at all. I have successfully connected to my clients directory and I am able to fetch some users. I have followed the PHP instructions. But this tutorial doesn't include example for fetching all users only the default page size of 100 users.
I am aware of the skipToken (explained here) but for some reason I am not been able to get it work with my loop.
Basically first I define an array, and two sub arrays.
$myArray = array();
$myArray['skipToken'] = "";
$myArray['users'] = "";
Then I'll perform the first fetch so I can get skipToken and bunch of users that come along.
require_once("GraphServiceAccessHelper.php");
$users = GraphServiceAccessHelper::getFeed('users');
Pushing values into already existing arrays.
$myArray['skipToken'] = $users->{'odata.nextLink'};
$myArray['users'][] = $users->{'value'};
Now they are filled with information. Now its time to loop!
for($i = 0; $i < 2; $i++){
if($myArray['skipToken'] != ""){
$skipToken = $myArray['skipToken'];
require_once("GraphServiceAccessHelper.php");
$users = GraphServiceAccessHelper::getNextFeed('users', $skipToken);
$myArray['skipToken'] = $users->{'odata.nextLink'};
$myArray['users'][] = $users->{'value'};
}
}
Console fires up from error, that points to loop skipToken defining part:
Notice: Undefined property: stdClass::$odata.nextLink
$myArray['skipToken'] = $users->{'odata.nextLink'};
Okay I figured it out.
First I had to remove everything before actual token.
$skipToken = $users->{'odata.nextLink'};
$skipToken = substr($skipToken, strpos($skipToken, "=") + 1);
Then inside the loop use that get new skipToken and do the same like above:
$new = GraphServiceAccessHelper::getNextFeed('users', $skipToken);
if(isset($new->{'odata.nextLink'})){
$skipToken = empty($new->{'odata.nextLink'});
} else{
break;
}
$skipToken = substr($skipToken, strpos($skipToken, "=") + 1);
$myArray['tokens'] = $skipToken;
$myArray['users'][] = $new->{'value'};
By checking if 'odata.nextLink" exists I can easily stop the while loop since lastpage doesn't contain 'odata.nextLink'.
if(isset($new->{'odata.nextLink'})){
$skipToken = empty($new->{'odata.nextLink'});
} else{
break;
}
I am appending each 100 user array to another array that I can call easily use it outside PHP.
I have a form page in which many of the elements are saved to different tables and different rows in my db. In order to minimize db calls I would like to compare the data before and after form submission, then I can write a function which will only update data that has been changed. To accomplish this I am saving the array that I used to build the form in a session file:
$this->session->set_tempdata('form_values_'.$item['id'],json_encode($item), 86400);
On form submission I retrieve this data and compare it to the $_POST:
$pre_post = json_decode($_SESSION['form_values_'.$_POST['id']], true);
Everything works great except in a few textareas where there is a "." in my test data. For some reason these fields come back as not equal even though I'm not changing the data.
It is definitely the period that is causing the problem, when I remove it it works fine. On the other hand there are other textareas that have periods that are not causing problems.
I thought it might be codeigniter's XSS filtering, but I removed that and it made no difference.
Originally i was using serialize to encode the array for storage, but I switched to json_encode and again it made no difference.
Here is the code I am using to compare the values:
$pre_post = json_decode($_SESSION['form_values_'.$_POST['id']], true);
$post = $this->security->xss_clean($_POST);
foreach ($post as $key => $value) {
if( !isset($pre_post[$key]) || trim($value)!=trim($pre_post[$key]) ){
$post_post[$key] = $value;
}
}
Any ideas?
Try this code may be it help you
$select = "SELECT * FROM ".$table_name." WHERE ".$field_name ." = '".$value."'";
$result_latest = mysql_query($select) or trigger_error(mysql_error());
while($row = mysql_fetch_array($result_latest,MYSQL_ASSOC))
{
$data_new = array_intersect_key($row,$data);
foreach($data_new as $k=>$v)
{
if(strcmp($row[$k],$data[$k]) != 0)
{
$string .= '`'.$k.'` = "'.$data[$k].'" ,';
}
}
}
$string = rtrim($string, ",");
if($string != NULL){
$update_sql = "UPDATE ".$table_name." SET ".$string." WHERE ".$field_name." = "."'".$value."'";
$query = $CI->db->query($update_sql);
}
I know how to get a mysql-row and convert it to json:
$row = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM table WHERE id=1"));
echo json_encode($row); // it's an ajax-call
but:
the db-row has different types like int, float, string.
by converting it using json_encode() all results are strings.
Is there a better way to correct the types than this:
$row['floatvalue1'] = 0+$row['floatvalue1'];
$row['floatvalue2'] = 0+$row['floatvalue2'];
$row['intvalue1'] = 0+$row['intvalue1'];
I would like to loop through the keys and add 0 because:
first coding rule: DRY - dont repeat yourself
but i can't because:
row has also other types than numbers (string, date)
there are many columns
design is in dev, so columns-names often changes
Thanks in advance and excuse my bad english :-)
EDIT (to answer the comment-question from Casimir et Hippolyte):
I call this php-code using ajax to get dynamically sql-values. in my javascript-code i use the results like this:
result['intvalue1'] += 100;
lets say the json-result of intval1 is 50, the calculated result is:
"50100", not 150
The code below is just a proof of concept. It needs encapsulation in a function/method and some polishing before using it in production (f.e. call mysqli_fetch_field() in a loop and store the objects it returns before processing any row, not once for every row).
It uses the function mysqli_fetch_field() to get information about each column of the result set and converts to numbers those columns that have numeric types. The values of MYSQLI_TYPE_* constants can be found in the documentation page of Mysqli predefined constants.
// Get the data
$result = mysqli_query($db, "SELECT * FROM table WHERE id=1");
$row = mysqli_fetch_assoc($result);
// Fix the types
$fixed = array();
foreach ($row as $key => $value) {
$info = mysqli_fetch_field($result);
if (in_array($info->type, array(
MYSQLI_TYPE_TINY, MYSQLI_TYPE_SHORT, MYSQLI_TYPE_INT24,
MYSQLI_TYPE_LONG, MYSQLI_TYPE_LONGLONG,
MYSQLI_TYPE_DECIMAL,
MYSQLI_TYPE_FLOAT, MYSQLI_TYPE_DOUBLE
))) {
$fixed[$key] = 0 + $value;
} else {
$fixed[$key] = $value;
}
}
// Compare the results
echo('all strings: '.json_encode($row)."\n");
echo('fixed types: '.json_encode($fixed)."\n");
something like
$row['floatvalue1'] = reset( sscanf ( $row['floatvalue1'] , "%f" ));
$row['floatvalue2'] = reset( sscanf ( $row['floatvalue2'] , "%f" ));
$row['intvalue1'] = reset( sscanf ( $row['intvalue1'] , "%d" ));
json_encode($row);
If you're simply trying to make sure that your values are operable with respect to their type, you need to first cast their type correctly.
Unless you need them server-side, I would just pass-on the json directly to the front-end and do the work there.
In Javascript, you could make an attempt at casting the numbers like so:
function tryNumber(string){
return !isNaN( parseInt(string) ) ? parseInt(string) : string;
}
function tryDate(string){
return !isNaN( new Date(string).getTime() ) ? new Date(string) : string;
}
tryNumber('foo'); // "hello"
tryNumber('24'); // 24
tryDate('bar'); // "bar"
tryDate('December 17, 1995'); // "Sun Dec 17 1995 00:00:00 GMT+0000 (GMT)"
These two lines attempt to cast the values as a Date/Number. If they can't be cast, they will remain String's.
A MySQLi OO version based on #axiac's answer, that produces a JSON array ($jsnAll) containing all records. In this code snippet, the method FixSQLType is called to fix a row. Note, it should be wrapped in a try{}catch{} block and "objMySQLi" has already been instantiated:
$lcAllRows = array();
// Make an SQL SELECT statement
$SQL = "SELECT * FROM $lcName WHERE $lcWhere";
// Run the query
$this->sqlResult = $this->objMySQLi->query($SQL);
// Fetch the result
while( $row = $this->sqlResult->fetch_assoc()){
$lcCount = count($lcAllRows) ;
// Call to fix, row
$fixedRow = $this->FixSQLType($row);
$lcAllRows[$lcCount]= $fixedRow;
}
$jsnAll = json_encode($lcAllRows);
The FixSQLType method. This is almost identical to #axiac's answer, except for the call to $this->sqlResult->fetch_field_direct($i). "fetch_field" seemed to get itself lost, using "fetch_field_direct" overcame that problem.
private function FixSQLType($pRow){
// FROM https://stackoverflow.com/a/28261996/7571029
// Fix the types
$fixed = array();
$i = 0;
foreach ($pRow as $key => $value) {
$info = $this->sqlResult->fetch_field_direct($i);
$i++;
if (in_array($info->type, array(
MYSQLI_TYPE_TINY, MYSQLI_TYPE_SHORT, MYSQLI_TYPE_INT24,
MYSQLI_TYPE_LONG, MYSQLI_TYPE_LONGLONG,
MYSQLI_TYPE_DECIMAL,
MYSQLI_TYPE_FLOAT, MYSQLI_TYPE_DOUBLE
))) {
$fixed[$key] = 0 + $value;
} else {
$fixed[$key] = $value;
}
}
return $fixed;
}