while($fetchres = mysql_fetch_array($searchquery)) {
$v1 = $fetchres['v1']; $v2 = $fetchres['v2']; $v3 = $fetchres['v3'];
$v4 = $fetchres['v4']; $v5 = $fetchres['v5'];
$v6 = $fetchres['v6'];
$v7 = $fetchres['v7'];
}
Hi! How can I set this columns automatically? I mean my system automatically adds a column. For example my system adds a new column 'v8'. But in my code, I only inputted until v7. How can I automatically code this fetching of query by depending on how many columns my system automatically made? Thanks.
Use extract.
while ($row = mysql_fetch_assoc($searchQuery))
{
// Extract the keys of the array into the local symbol table.
extract($row);
// Now, all variables exist and you can echo them like this:
echo $v1;
echo $v8;
}
You still need to know the names of the variables. If you just want to echo everything inside, use foreach with a key assingnment:
while ($row = mysql_fetch_assoc($searchQuery))
{
foreach($row as $key => $value)
{
echo "$key: $value\n"; // Will output something like 'v1: foo' and 'v2: bar', separated by newlines.
}
}
If you really want to do this, you can use extract($fetchres).
More info about extract
Example:
$fetchres = array('v1'=>'foo', 'v2'=>'bar');
extract($fetchres);
echo '$v1 is ' . $v1 . 'and $v2 is ' . $v2;
You could use variable variables for that, although I think this is a really bad idea.
I think you actually want this:
while ($fetchres = mysql_fetch_array($searchquery)) {
foreach ($fetchres as $key => $value) {
echo $key . ': ' . $value . PHP_EOL;
}
}
Related
how can i print var name instead var value in php?
Like this code:
$Tree = "abcd";
$str = "zwd";
i want to print something like this:
tree = abcd
str = zwd
please help me
You may want to take a look at compact function
<?php
$city = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";
$location_vars = array("city", "state");
$result = compact("event", "nothing_here", $location_vars);
// print_r($result);
?>
Then print the key and its value,
foreach($result as $key => $value)
{
echo $key . " : " . $value;
}
What you maybe looking for is
echo 'Tree = ' . $Tree;
echo '<br>';
echo 'str = ' . $str;
I am pretty sure OP meant above, btw for expert level programmers, Why this question is paradoxical in nature, is lets say you want to print/output the name of variable $xyz. See....
...did you notice...
....that in order to print the name of a variable you had to actually type the name of the variable in the first place! How else would you refer to that variable!!! And for that the above method of concatenation is best suited :)
Here someone with sane mentality tried to explain better.
I think what you want is this:
$array = array('Tree' => 'abcd', 'str' => 'zwd');
foreach ($array as $name => $value) {
echo $name . ' = ' . $value;
}
If you want to print variable names not writing it by yourself you should use get_defined_vars() as follow :
$var1 = 'I am ';
$what = array_search($var1, get_defined_vars(), true);
printf($var1.'%s', $what); // I am var1
I have an HTML-table, where various selections can be made. The selected variables that contain the respective values, build the array $data[]. Now, with this array I would like to make an SQL request where all selected criteria should be met. This means, that I need the following request:
SELECT * FROM fruitgroups
WHERE $selection[1] = $value[1]
AND $selection[2] = $value[2]
AND $selection[3] = $value[3]
etc ...
Can anybody please help me with the loop that generates exactly the string:
...
$selection[1] = $value[1]
AND $selection[2] = $value[2]
AND $selection[3] = $value[3]
... etc ...
...that I need for the request?
Thank you in advance!
You can make a SQL request like this:
$selection = array("one", "two", "three");
$value = array("Tone", "Ttwo", "Tthree");
$concat = array();
foreach($selection as $key => $var){
$new = $selection[$key] . " = " . $value[$key];
array_push($concat, $new);
}
$concat = implode(" AND ", $concat);
$request = 'SELECT * FROM fruitgroups WHERE ' . $concat . ';';
echo $request;
Run example
Similar to the answer above, but keep it simple and don't forget the single quotes around the values:
$clauses = [];
foreach ($values as $i => $value) {
$conditions[] = "{$selection[$i]} = '$value'";
}
$query = "SELECT * FROM fruitgroups WHERE " . implode(' AND ', $conditions);
Even better, use an ORM like Eloquent:
$conditions = [];
foreach ($values as $i => $value) {
$conditions[$i] = $value;
}
$result = App\FruitGroups::where($conditions)->get();
I'm assuming you are sanitizing your inputs first, of course.
I am using a URL to fetch data stored/shown within URL. I get all the value of variable using $_REQUEST['v_name'] but if there is a array in URL how can i retrieve that value.
For Example:
WWW.example.com/rooms?&hid=213421&type=E
I got the value hid and type using
$hid=$_REQUEST['hid'];
but in URL like:
WWW.example.com/rooms?&rooms=2&rooms[0].adults=2&rooms[0].children=0&rooms[1].adults=2&rooms[1].children=0
how can i retrieve value of adults and children in each room.
please help.
Thanks in Advance
You could also try something like this, since most of your original $_REQUEST isn't really an array (because of the .s in between each key/value pair):
<?php
$original_string = rawurldecode($_SERVER["QUERY_STRING"]);
$original_string_split = preg_split('/&/', $original_string);
$rooms = array();
foreach ($original_string_split as $split_one) {
$splits_two[] = preg_split('/\./', $split_one);
}
foreach ($splits_two as $split_two) {
if (isset($split_two[0]) && isset($split_two[1])) {
$split_three = preg_split('/=/', $split_two[1]);
if (isset($split_three[0]) && isset($split_three[1])) {
$rooms[$split_two[0]][$split_three[0]] = $split_three[1];
}
}
}
// Print the output if you want:
print '<pre>' . print_r($rooms, 1) . '</pre>';
$valuse = $_GET;
foreach ($valuse as $key=>$value)
{
echo $key .'='. $value. '<br/>';
}
I am in need of a PHP-program which will take all values from a HTML-link (with GET), regardless of how much one changes things in the address-bar, and then prints it out on the page. The code I have now is this:
HTML:
Link
PHP:
<?php
Echo "Value1: "; Echo $_GET["a"]; Echo "\n";
Echo "Value2: "; Echo $_GET["b"]; Echo "\n";
Echo "Value3: "; Echo $_GET ["c"];
?>
It works as intended for just these values, but it cannot cope with, for example, another variable being added in the address bar. I need some kind of PHP-function which can look for all kinds of variables through the GET-function.
Any help is appreciated!
Use a loop (modify as needed):
foreach ($_GET as $num => $value)
{
echo 'Value ' . $num . ': ' . htmlentities($value). "<br>" . PHP_EOL;
}
References:
Control structures
htmlentities()
Something like this:
<?php
foreach ($_GET as $key => $value) {
echo htmlspecialchars($key) . " - " . htmlspecialchars($value) . "<br>";
}
?>
<?php
print_r($_GET);
?>
Use a foreach loop
foreach ($_GET as $key => $val){
echo htmlentities($key).": ".htmlentities($val)."<br />\n";
}
or simply -
echo "<pre>".print_r($_GET,1)."</pre>";
To get all values and their corresponding names:
foreach($_GET as $key => $value)
{
echo $key . ' - ' . $value;
}
$my_get = array(); // store $_GET vars
if ('GET' == $_SERVER['REQUEST_METHOD']) // check that request method is "get"
foreach ($_GET as $key => $val)
{
$my_get[$key] = $val; // store
}
output $my_get:
array (
'a' => 'value1',
'b' => 'value2',
'c' => 'value3',
)
Since $_GET is nothing but an array, you can use for each loop to get the elements of it.
you get all $_GET values using print_r($GET) ...
otherwise you could to something like this
foreach(array_keys($_GET) as $key) {
echo htmlspecialchars($_GET[$key]);
}
Later Edit : took into account the security issue exposed in the comment
using this method is good because you know what kind of variable you have then you could do something cool like :
if ($key == 'a') do this
if ($key == 'b' && $_GET[$key] == 'bar') do that
I have the array example below that I am using to dynamically create an SQL query based on the options ticked in a form. The code below tests whether there is a value, if so, append it to the array:
if ($lookchild) { $val[]='lookchild'; }
if ($mentalcap) { $val[]='mentalcap'; }
if ($mentalheal) { $val[]='mentalheal'; }
if ($olderpeople) { $val[]='olderpeople'; }
if ($palcare) { $val[]='palcare'; }
I am then looping through the array and adding the rest of the SQL statement:
foreach ($val as $r){
echo $r.'=1 AND ';
}
This produces:
olderpeople=1 AND palcare=1 AND lookchild=1 AND
When the loop reaches the last entry, I don't want it to append the AND to it as the SQL statement needs to close after that point.
How I want it to complete:
olderpeople=1 AND palcare=1 AND lookchild=1
Implode
In these situations you can use implode
It 'glues' an array together.
implode ( string $glue , array
$pieces )
Example:
echo implode('=1 AND ', $val);
echo '=1';
A common trick is to use 'WHERE 1=1' then you can append ' AND foo = bar' without a syntax error.
WHERE 1=1 AND olderpeople=1 AND palcare=1 AND lookchild=1
This is what implode() is for:
$result = array();
foreach ($val as $r){
$result[] = "$r=1";
}
$result = implode($result, ' AND ');
Live Example
Just don't print the AND for the last value of the foreach loop. Here is the code to use:
foreach ($val as $r){
echo $r.'=1';
if (next($val)) {
echo ' AND ';
}
}
use the implode function
$sql = implode("=1 AND ", $array)."=1";
and you wont have to use a for loop :)
Instead on assigning palcare to $val[], assign $val[] = "palcare = 1" etc. Them
implode(" AND ", $val);
Try this :
$isFirst = true;
foreach ($val as $r){
if(!$isFirst){
echo ' AND ';
}else{
$isFirst = false;
}
echo $r.'=1';
}
I would remove the last 4 characters of the string with:
$r = '';
foreach ($val as $r){
$r.'=1 AND ';
}
$r = substr($r, 0, -4);
echo $r;
Checkout http://ca3.php.net/manual/en/function.substr.php, quick and easy
If you have to do it with a foreach (and for some reason you cant use implode, which is a good suggestion) you will need a way to keep track of where you are.
I thought to add the "AND" before anything but the first item, instead of adding it after anything but the last item, something like this:
$sqlwhere = "";
foreach ($val as $r){
if($sqlwhere ==""){
$sqlwhere = $r;
}
else {
$sqlwhere .= " AND " . $sqlwhere;
}
}
echo $sqlwhere;
I used a varable instead of just echoing it out too, which I find useful in complicated sql statements anyway.
Use implode. But if for some reason you need to loop (such as you need to do more logic than just joining the strings), use a separator approach:
$seperator = '';
$result = '';
foreach ($array as $value) {
// .. Do stuff here
$result .= $seperator . $value;
$seperator = ' AND ';
}
The benefit is both brevity and flexibility without checking conditions all the time...
Since you are using an array, you can also use count to figure out how many are in the array and if you are on the last item, don't append the 'AND'.
$result = array();
$totalcount = count($val);
$currentCount = 0;
foreach ($val as $r){
$currentCount ++;
if ($currentCount != $totalcount){$result[] = "$r=1 AND ";}else{$result[] = "$r=1";}
}