db table names as alias in php GET-paramter? - php

I am looking for a possibility to pass db table name and column name via php and GET parameter.
I have a data grid with following structure:
table_name1.column1, table_name2.column1, table_name2.column1.
There is a search function for the grid, where I need those parameters.
From the url "?table_name1.column1=22" I am getting through the $_GET only table_name1_column1=22
How would you solve that?

Encode the variable with base64 and decode before you use.
I know that's dirty.
But php variables doesn't support periods (dots)

This is a documented feature of PHP. Its basically because PHP cannot have variable names with dots in them.
$x.y = 1 // is an invalid variable name
MANUAL Convert dots to _ in GET & POST

You can use serialize function of php to pass the text "table_name1.column1" in url. But for that you need to do few coding to get the result. Below I have given code which you can use:
Page1.php
<?php
$test = serialize('table_name1.column1=11::table_name2.column2=22');
?>
<a href='Page2.php?qs=<?php echo $test?>'>test</a>
Use this $test to pass as query string. In above example, I am passing on anchor tag click.
Page2.php
use following code to Unserialize the query string and use the values.
<?php
$test2 = unserialize($_GET['qs']);
$ex = explode('::',$test2);
$new_arr = array();
foreach($ex as $val)
{
$ex2 = explode('=',$val);
$new_arr[$ex2[0]] = $ex2[1];
}
echo $new_arr['table_name1.column1']; //print 11
echo $new_arr['table_name2.column2']; //print 22
?>
Hope this will help you :)

You need to seperate each parameter with &.
So: ?table=table_name1&column=column1

Related

extract specific data from array in mysql database using php

This is the data that i need to extract like example profile_contact_numbers
so the output will be +639466276715
how can i do it in php code??
any help will do regards
a:2:
{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}
I'm not sure 100% this can go into an array but try the unserialize function
$json_resp = {your values};
$array[] = unserialize($json_resp);
To check if it has gone into an array print_r on $array.
Read this link if the code above doesn't work
http://php.net/manual/en/function.unserialize.php
I have managed to fix it
$serialized = array(unserialize('a:2:{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}'));
var_dump($serialized);
use code :
$var = preg_split('["]','{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}');
echo $var[1].'='.$var[3]; // profile_contact_numbers=+639466276715
echo $var[5].'='.$var[7]; // profile_position=Courier

How to get my word from following string?

I have two strings in PHP:
$Str1 = "/welcome/files/birthday.php?business_id=0";
$Str2 = "/welcome/index.php?page=birthday";
I have to get word birthday from this two string with a single function.
I need a function which returns birthday on both case.
example
function getBaseWord($word){
...
return $base_word;
}
getBaseWord('/welcome/files/birthday.php?business_id=0');
getBaseWord('/welcome/index.php?page=birthday');
both function call should return "birthday".
How can i do it.
If I correctly understand what you are trying to do then this should do what you need:
function getWord(){
return $_GET['page'];
}
or $_GET['business_id'];
I think $_GET is an associative array made from the GET request that was sent to the page. An associative array is one where you access something like ['name of the element'] instead of [1] or [2] or whatever.
So what you will need to do is get all of the actual GET variables extracted from the string:
//Seperate the URL and the GET Data
list($url,$querystring) = explode('?', $string, 2);
//Seperate the Variable name from its value
list($GETName, $GETValue) = explode("=", $querystring);
//Check to see if we have the right variable name
if($GETName == "page"){
//Return the value of that variable.
return $GETValue;
}
NOTE
This is very BASIC and will not accept more then one GET parameter. You will need to modify it if you plan on have more variables.
I have no idea what you are talking about but, you can cut the word "birthday" with str_replace and replace with another word, or you can find the position with stripos, I have no idea what we are trying to do here, so those are the only things come to my mind

Getting PHP session array values into Javascript

I have stored array values in PHP session.
Now I want to retreive this array and convert it to javascript aray.
This is how I set PHP session:
var listone = ["one", "two", "three"];
function setSession(listone){
$.get(
"setSession.php",
{listone:listone}
);
}
So if once these values are set and I refresh the page, I check if the session has been set. If set, I want to do something like this:
<?php
session_start();
if(isset($_SESSION['listone']))
{
?>
listone = Array('<?php echo json_encode($_SESSION['listone']) ?>');
<?php
}
?>
When I do this, the 'listone' array is showing me like this:
listone[0] = [
listone[1] = "
listone[2] = o
listone[3] = n
listone[4] = e
listone[5] = "
.... etc
I know I am doing something wrong.
Is it the way I am storing the array in PHP session?
or
Is it the way I am retrieving it back to JS?
Thanks for any pointers. I am willing to dig more if guided properly :)
You may be trying to do one of two things here- either something to do with AJAX, which is expecting a JS response, or you're trying to access a session variable directly in JS.
If you simply wish to switch a PHP variable into a JS readable array, you can do:
json_encode($_SESSION['myarray']);
This would need to be a response readable & interpreted elsewhere by a JS script (e.g. an AJAX response).
PHP session variables arent accessable through JS directly, however, you can construct JS within PHP, wrapping the two together so you use PHP to output JS populated with the data held within your PHP session variable. The key here is the order of the code, and how your JS is structured- i.e. you will probably want to reference a global JS variable so the values are accessible by your other JS- or call a function etc...
So, you could have:
session_start();
if(!isset($_SESSION['myarray'])){
$_SESSION['myarray']=array('one', 'two', 'three');
}
echo "<script type='text/javascript'>
var myJSvariable = new Array();";
foreach($_SESSION['myarray'] as $key=>$value){
echo "myJSvariable[".$key."]=".$value.";";
}
echo "</script>";
Try to change your php file to this or a similar one
<?php
session_start();
$result = array();
if(isset($_SESSION['listone'])) {
$result['listone'] = $_SESSION['listone'];
}
echo json_encode($result);
?>
json_encode translate your array into a json array and you don't need to create a new one.
Plus I would put the required variables into an hash array and return just the json_encode of that array in order to have a cleaner code.

How to pass an array of objects from javascript to PHP

If I have, in javascript, something like:
entriesObj1 = new Object();
entriesObj1.entryId = "abc";
entriesObj1.mediaType = 2;
entriesObj2 = new Object();
entriesObj2.entryId = "def";
entriesObj2.mediaType = 1;
var entries = new Array();
entries[0] = entriesObj1;
entries[1] = entriesObj2;
What is the best method to pass it to php through an HTTP POST?
I've tried a jQuery plugin to convert the array to JSON. I've tried to create multiple hidden fields named "entries[]", each one with the JSON string. Somehow, I can't seem to decode my data with PHP's json_decode.
EDIT:
I tried changing the JSON plugin used to the one #Michal indicated and the results I get are the same:
Javascript
[
{"disciplina":"sdfsdfsdfsd","titulo":"sdfsdfsdf","componentes":"Bloco Completo"},
{"disciplina":"sdfsdfsdfsd","titulo":"sdfsdfsdf","componentes":"Bloco Completo"}
]
PHP Vardump:
string(756) "
[
{\"disciplina\":\"sdfsdfsdfsd\",\"titulo\":\"sdfsdfsdf\",\"componentes\":\"Bloco Completo\"},
{\"disciplina\":\"sdfsdfsdfsd\",\"titulo\":\"sdfsdfsdf\",\"componentes\":\"Bloco Completo\"}
]
"
When I use PHP's json_decode, I get NULL.
var_dump(json_decode($_REQUEST['entries']));
Output:
NULL
You need to convert JSON to a string (use JSON stringifier (https://github.com/douglascrockford/JSON-js) and POST the string (as a field value) to the PHP script which does json_decode()
Concat it using some characters like _ or %% then pass it to PHP.
In PHP file:
$ar = array();
$ar = explode('special_char',string pass from js);
echo "pre";print_r($ar);
echo "/pre";
well, the trouble seemed to be with the quotes that were being passed in the post, so i just replaced the quotes with open strings to my $_REQUEST.

How to grab a value from a url with multiple values using PHP. [2 Part Question]

This is a two part question. First how can I grab the last url value from a link when I dont know how deep the value is, for example how can I grab
the last value of sub_4 from the link example below using PHP? And second how can I grab the url value cat=3 and the last url value sub_4 using PHP?
I'm kind of new to PHP so a detailed step by step example would help me out a lot if its not too much trouble.
Thanks in advance!
Here is an example of a URL value.
http://www.example.com/categories/index.php?cat=3&sub_1=sub1&sub_2=sub2&sub_3=sub3&sub_4=sub4
All variables from the hook will be returned on $_GET. So if you want to get that value from the URL, just use:
$_GET['sub_4']
If you want to get a list of all of the possible values:
array_keys($_GET)
This will give you all of the variables.
UPDATE: I just reread your question. I think I better understand what you are looking for. Correct me if I am wrong, but you are not certain how to get the last element of the string? Is that right? So you could potentially have sub_5, sub_6, sub_7 etc. Here is how to get the last element from the string:
end($_GET);
$key = key($_GET);
$last_item = $_GET[$key];
$last_item will now have sub_4 (or what ever the last item is).
Extracting URL Parameters
Query parameters (anything in the URL with ?name or &name) are saved in the $_GET superglobal.
If sub is a hierarchy, you should probably just write it as such. For instance: ?sub=path/to/sub or ?sub=path:to:sub
From this you can explode() on your separator (/ or :) to get the different parts of the sub parameter. $sub_array = explode('/', $_GET['sub']);
You can then iterate over the array using a foreach or directly access the highest branch of the hierarchy using count():
$sub_array[count($sub_array-1)];
Building URL Parameters
If you have an array of subs that you want to use to generate a URL, you can use implode() to build your URL params. $sub_params = implode('/', $_GET['sub']);
You might construct that array by appending each sub to the $sub_array.
$sub_array[] = 'sub1';
$sub_array[] = 'sub2';
$sub_array[] = 'sub3';
etc.
Inspect the Data
If you get lost, use var_dump($_GET) or var_dump($variable) to see what's inside it.
Each cat=3 or sub_1 value can be retreived by $_GET['cat'] and $_GET['sub_1'] respectively. To elaborate, $_GET['NAME_OF_PROPERTY'] would look like php.net/index.php?NAME_OF_PROPERTY=whatever
It seems like both questions were on how to grab the value from the URL, so I hope that answers both.
In your example url http://www.example.com/categories/index.php?cat=3&sub_1=sub1&sub_2=sub2&sub_3=sub3&sub_4=sub4
echo $_GET['cat']; // 3
echo $_GET['sub_1']; // sub1
echo $_GET['sub_2']; // sub2
echo $_GET['sub_3']; // sub3
echo $_GET['sub_4']; // sub4
For the first part; you should use the $_GET[] array which contain every parameter passed in the url $_GET['cat'], $_GET['sub_1'].
For the second part, in your case you should try send an array in parameter like this :
http://www.example.com/categories/index.php?cat=3&sub[1]=sub1&sub[2]=sub2&sub[3]=sub3&sub[4]=sub4
And then use the $_GET['sub'][] array $_GET['sub'][1], $_GET['sub'][2], ...
Now you can determine the length of the array and know the last item in it.
This example is under the assumption you want to find the very first variable in the GET query, and the very last:
<?php
// Here, you separate all the variables
$parameters = explode("&", $_SERVER['QUERY_STRING']);
// Get the last key's index
$last_key_index = count($parameters)-1;
// Easy way for PHP 5.3
$first_key = strstr($parameters[0], "=", true);
$last_key = strstr($parameters[$last_key_index], "=", true);
// Bit longer otherwise
$first_key = substr($parameters[0], 0, strpos($parameters[0], "="));
$last_key = substr($parameters[$last_key_index], 0, strpos($parameters[$last_key_index], "="));
// Test it here
echo($first_key);
echo($last_key);
?>

Categories