Extract MySQL fields of row into PHP variables and array - php

I have a table with a whole bunch of fields and records in it (40+fields).
I use my MySQL result like so:
<?php
$field1 = $row['field1'];
$field2 = $row['field2'];
$field3 = $row['field3'];
?>
As you see, the variable name is the same as the field name.
How can I do this for all fields, without having to type em all out? Would be really awesome for when I add more fields!
I know about the eval function, however I am not sure of how to use it in this case.
Also, how can I generate an array with the results? Like so:
<?php
$arr = array(
'field1'=>$row['field1']
);
?>

You can use extract():
extract($row);
However, take great care you don't pollute your namespace with this function. Say you already have a variable named $car, and you have a field in your database called car. You could be unwittingly overwriting your existing variables!
It may be safer, then, to use:
extract($row, EXTR_SKIP); // don't extract variables that already exist in the namespace
EDIT: In regards to your edit, you don't need to create an array for the results... your $row array is the result. If you construct the array as in your edit, $arr['field1'] = $row['field1'], so why not bypass the construction of this array altogether and just use the original $row?

The extract() function does exactly this:
extract($row);
By default it will override any existing variable (e.g. if you already have a field1 variable, it will override it). You can disable this by passing EXTR_SKIP as second parameter:
extract($row, EXTR_SKIP);
Or you can prefix all variables:
extract($riw, EXTR_PREFIX_ALL, 'row');

Also, how can I generate an array with the results?
$arr = $row;

Related

How do I put 1 variable in an array()?

I need to put a variable within an array.
For example.
$anarray = array("1","3","4");
foreach($anarray as $value){ // do such and such
I need the array() to include a variable instead. To be exact, I need it to contain a variable from my table in my database.
In effect, I would want my array to look like this.
Column 'example' in my users table contains - "1","3","4"
When I rewrite the code to look like this ...
$anarray = array($users['example']);
foreach($anarray as $value){ // do such and such
It doesn't work. What do I need to do to that variable to make it read the exact same as if it were the actual characters?
$anarray=array("1","2","3");
$new_array['example']=array();
for($i=0;$i<count($anarray);$i++){
array_push($new_array['example'],$anarray[$i]);
}

Pushing values from a $_Get query to a value using implode

I am attempting to use a for loop or for each loop to push the values from a get query to another variable. May I have some help with this approach?
Ok here is where I am:
for ($i = 0 ; i < $_GET['delete']; i++) {
$_jid [] = $_GET['delete'];
}
You don't actually need a loop here. If $_jid already is an array containing some values, consider just merging it with $_GET['delete'].
if (is_array($_jid)) {
$_jid = array_merge($_jid, $_GET['delete']);
}
If $_jid is not an array and doesn't exist except as a container for $_GET['delete'] you do can just assign the array. There is no need to loop at all.
$_jid = $_GET['delete'];
Of course in that case, you don't even need to copy it. You can just use $_GET['delete'] directly, in any context you planned to read from $_jid.
Update:
If the contents of $_GET['delete'] are originally 923,936, that is not an array to begin with, but rather a string. If you want an array out of it, you need to explode() it on assignment:
$_jid = explode(',', $_GET['delete']);
But if you intend to implode() it in the end anyway, there's obviously no need to do that. You already have exactly the comma-delimited string you want.
As you can see if you do a var_dump($_GET), the variable $_GET is a hashmap.
You can easily use a foreach loop to look through every member of it :
foreach($_GET as $get) // $get will successively take the values of $_GET
{
echo $get."<br />\n"; // We print these values
}
The code above will print the value of the $_GET members (you can try it with a blank page and dull $_GET values, as "http://yoursite.usa/?get1=stuff&get2=morestuff")
Instead of a echo, you can put the $_GET values into an array (or other variables) :
$array = array(); // Creating an empty array
$i = 0; // Counter
foreach($_GET as $get)
{
$array[$i] = $get; // Each $_GET value is store in a $array slot
$i++;
}
In PHP, foreach is quite useful and very easy to use.
However, you can't use a for for $_GET because it's a hashmap, not an array (in fact, you can, but it's much more complicated).
Hope I helped

How to put data from database to session dynamically

I am pulling data from database and would like to save it into session variables. I would like to name the keys the same that my table cells are named. So for example:
I have a cell named "EMAIL", and I would like to get $_SESSION["EMAIL"]
I already have the data from database saved in an array ($data), which has array keys named after the cells, but I would like to move that data to SESSION array, with same keys...
How can I do this dynamically?
You could either do it like this:
foreach($myArr as $k=>$v) {
$_SESSION[$k] = $v;
}
Or,
$_SESSION['user'] = $myArr;
In the first case, you will access email by doing $_SESSION['EMAIL'], and in the second case, $_SESSION['user']['EMAIL'];
Another alternative is
$_SESSION = array_merge($_SESSION, $myArr);
I'm not sure if this is a good practice though.

PHP - Save value AND name using $_POST

I'm currently using the following format to save a value from an HTML form $item_name=$_POST['item_name'];
This saves the value, but how to I also save the name attribute in a variable?
Thanks in advance!
Assuming you want to store each element of $_POST variable as a key-value pair, then you can try:
$var = array();
foreach($_POST as $key => $val) {
$var[$key] = $val;
}
I'm saving a lot of values and want to avoid typing each one out.
Please, make your mind first.
Global variables are intended to be typed by hand.
If you want some automated processing - just keep them in a form of array.
Looks like rdt.exe's answer is what you're looking for.
maye you noticed you have to use the name to access the $_POST-array and get the value. if you want to store the name in a variable, too, just do:
$item_name_name = 'item_name';
$item_name_value = $_POST[$item_name_name];
you could also use some kind of loop to dynamically create variables with the according names like this:
foreach( $_POST as $name => $value ){
$$name = $value;
}
both ways are some kind of unnecessary and useless in my opinion, but you havn't stated what exactly you're trying to achive - so maybe this helps.
An alternative approach:
$keysarray = array_keys ( $_POST);
print_r( $keysarray);
This will give you all the keys in array
The function you are looking for is called extract.
This will create variables for all the $key=>$val pairs in the array.
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound');
export($_EXAMPLE);
echo $bird; # prints "chicken"
echo $dog; # prints "greyhound"
Watch out though - this is a huge security risk. So are the solutions described in some of the other answers.
The problem with doing something like this is that a user can tamper with the POST data, and set parameters other than the ones she is supposed to set. If they set variables that are actually variable names in your application, those variables can be overwritten.
$is_admin = false;
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound', 'is_admin' => 'true');
export($_EXAMPLE);
if ($is_admin) { # this will now evaluate to true.
# do sensitive stuff...
}

Storing values in PHP

I am trying to store values in php, like a HashTable with multiple keys. For example I am I would want this to return two different values:
$value1=$content['var1']['var2']['var3']['typea'];
$value2=$content['var1']['var2']['var3']['typeb'];
What would be the best way to go about implementing a feature like this?
Instead of building a complicated array, how about you define and use a simple class instead? e.g:
<?php
class beer {
var $brand;
var $ounces;
var $container;
}
$mybeer = new beer();
$mybeer->brand = "Coors";
$mybeer->ounces = 12;
$mybeer->container = "can";
echo $mybeer->brand;
echo $mybeer->ounces;
echo $mybeer->container;
?>
You can set values the same way you get them.
$content['var1']['var2']['var3']['typea'] = $value1;
$content['var1']['var2']['var3']['typeb'] = $value2;
You can take advantage of PHP being a dynamic scripting language by letting it create your desired array structure automatically:
$content['var1']['var2']['var3']['typea'] = "value1";
One way would be to make a unique key based on the various keys and store it in one big array.
Instead of this,
$value1=$content['var1']['var2']['var3']['typea'];
you'd have something like this...
$contentKey = generateKey("var1", "var2", "var3", "typeA");
$value1 = $content[$contentKey];
where generateKey would do something like hash the various inputs, or concatenate them together with some unique delimiter like a quadruple underscore. This would require fewer array lookups than the other solutions, and (in my opinion) is easier to read.

Categories