PHP + MySQL: Get result from fetch array and convert to variables automatically? - php

I was wondering. I always do fetch and then create variables when I do loop. Is there a way to do this more efficient? Like as in automatically?
Maybe something like convert_to_variable("name","description","etc") and it'll automatically set variables for me without having to do each manually? Or maybe a single command like convert_to_variable($rows) and it'll do the rest for me.
Here is what I am doing now.
$sql = "SELECT * from projects";
$rows = $db->fetch_all_array($sql);
foreach($rows as $row) {
$name = $row['name'];
$description = $row['description'];
}
Something easier would be
$sql = "SELECT * from projects";
$rows = $db->fetch_all_array($sql);
foreach($rows as $row) {
convert_to_variable($row);
echo $name, $description;
}

extract can do that for you.

Related

Getting multiple results without query inside loop

I'm trying to improve the loading times of images and need to change around the code.
I haven't had any luck finding out how to do this and I'm not sure if it is even possible. In the example below you can see that I use KEY to match it with U_KEY to get FILE_PATH which I then add to a long comma delimited $allPaths string.
I know I should not use queries inside loops but I have no idea how to change this.
<?php
$sql = "SELECT * FROM test_users, image_uploads LIMIT 0, 27";
$result = mysqli_query($mysqli, $sql);
while($value = mysqli_fetch_array($result)) {
$files_key = $value["KEY"];
$allPaths = "";
$inner_query = "SELECT * FROM additional_uploads WHERE U_KEY = '".$files_key;
$inner_result = mysqli_query($mysqli, $inner_query);
while ($row = mysqli_fetch_array($inner_result)) {
$allpaths .= $row['FILE_PATH'].",";
}
// how do I get $allPaths without using a query inside the while loop?
}
?>
If someone could tell me how I can get $allPaths with only one query instead of multiple queries inside the loop as shown above it would probably load the images much faster.
Is this possible?
Edit
I have tried to understand the problem using the suggested answer and additionally I was looking on other forums as well to find out more. However I still cannot find a solution. Since I'm using mysqli_fetch_array the suggested answer really confuses me even further.
<?php
$inner_query = "SELECT * FROM additional_uploads";
$inner_result = mysqli_query($mysqli, $inner_query);
$rows = [];
while ($row = mysqli_fetch_array($inner_result)) {
$rows[$row['U_KEY']] .= $row['FILE_PATH'].",";
}
$sql = "SELECT * FROM test_users, image_uploads LIMIT 0, 27";
$result = mysqli_query($mysqli, $sql);
while($value = mysqli_fetch_array($result)) {
$files_key = $value["KEY"];
$allPaths = $rows[$files_key];
}
?>

Show multiple results from PDO::FETCH_ASSOC

Iwas wondering if someone could help me?
I have a table called markers, in this table it stores multiple records each with a name etc. I would like to echo each name however the below code only shows one results. How can I show more than one. Can someone please help I am new to PDO.
$stmt = $dtb->query('SELECT * FROM markers');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName = $row['name'];
}
Use an array to hold the result, in your code, the variable $markerName is overwrote on each iteration.
$stmt = $dtb->query('SELECT * FROM markers');
$markerName = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName[] = $row['name'];
}
That is because you are overwriting it each and every time , use an array instead.
Rewrite like this...
$markerName = array(); //<---- Add here
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName[] = $row['name'];
}
echo implode('<br>',$markerName); //<---- Implode it up for display
Rewrite like this
$names = $dtb->query('SELECT * FROM markers')->fetchAll();
Being new to PDO, you are supposed to try tag wiki first, where you can find an answer not only to this one but to many other questions.

Generating variables from db content?

I am querying a database to get 6 values in my params table suing this;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$param = $row['value'] ;
}
is this right, if so is their away i can add one to the variable name each time round so i get $param1, $param2....
I dont want to have to send a query to the database for each param, is it possible to get them all like this?
The simpliest way is to use an array:
$result = mysql_query("SELECT * FROM params");
$param = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$param[$i] = $row['value'] ;
$i++;
}
Than you get $param[0], $param[1], ...
You can create variable names like this:
${'var'.1}
${'var'.'1.cat'}
${'var'.$x}
${$y.$x}
and so on.
This seems like a design flaw. But what you can do is:
$count = 1;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$paramname = 'param' . $count++;
$$paramname = $row['value'] ;
}
You may find the list function useful - http://php.net/manual/en/function.list.php
list($param1,$param2,$param3,$param4,$param5,$param6) = mysql_fetch_row($result);
Probably more use when using descriptive variables, just a thought.

php query function / class

It must be Monday, the heat or me being stupid (prob the latter), but for the life of me I cannot get a simple php function to work.
I have a simple query
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
Which I want to run through a function: say:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
while($row = mysql_fetch_array($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}
So that I can call the function in numerious places with differeing "inputs". Then loop through the results with a foreach loop.
Works fine the first time the function is called, but always gives errors there after.
As said "It must be Monday, the heat or me being stupid (prob the latter)".
Suggestions please as I really only want 1 function to call rather than rewrite the query each and every time.
This is the error message
Fatal error: [] operator not supported for strings in C:\xampp\htdocs\functions.php on line 270
function functionname($input){
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$input'");
$result = array('field1' => array()
'field2' => array()
);
while($row = mysql_fetch_array($sql)) :
$result['field1'][] = $row['field1'];
$result['field2'][] = $row['field2'];
endwhile;
mysql_free_result($sql);
return $result;
}
it seems that somewhere the $field1 or $field2 are converted to strings and you cant apply the [] to a string...
i'd say that you have to do:
$field1 = array();
$field2 = array();
before the WHILE loop
The problem is that you so called arrays are strings!
global $field1;
global $field2;
var_dump($feild1,$feild2); //Will tell you that there strings
Read the error properly !
[] operator not supported for strings
And the only place your using the [] is withing the $feild - X values
GLOBAL must work because the error is telling you a data-type, i.e string so they must have been imported into scope.
another thing, why you selecting all columns when your only using 2 of them, change your query to so:
$sql = mysql_query("SELECT feild1,feild2 FROM table WHERE field_name = '$input'");
another thing is that your using mysql_fetch_array witch returns an integer indexed array, where as you want mysql_fetch_assoc to get the keys.
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
What I would do
function SomeFunction($variable,&$array_a,&$array_b)
{
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$variable'");
while($row = mysql_fetch_assoc($sql))
{
$array_a[] = $row['field1'];
$array_b[] = $row['field2'];
}
mysql_free_result($sql);
}
Then use like so.
$a = array();
$b = array();
SomeFunction('Hello World',&$a,&$b);
In my opinion, it's pretty unusual and even useless approach at all.
This function is too localized.
To make a general purpose function would be a way better.
<?
function dbgetarr(){
$a = array();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
$res = mysql_query($query);
if (!$res) {
trigger_error("dbgetarr: ".mysql_error()." in ".$query);
return FALSE;
} else {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
and then call it like this
$data = dbgetarr("SELECT field1,field2 FROM table WHERE field_name = %s",$input);
foreach ($data as $row) {
echo $row['field1']." ".$row['field1']."<br>\n";
}
To understand your issue, we need the error, however, are you sure you are going about this in the right way?
Why do you need to call the function multiple times if you are just changing the value of the input field?
You could improve your SQL statement to return the complete result set that you need the first time.. i.e. SELECT * FROM table GROUP BY field_name;
Not sure if that approach works in your scenario, but in general you should aim to reduce the number of round trips to your database.
I don't know, i right or not. But i advise to try this:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM `table` WHERE `field_name` = '" . $input . "'");
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}

How to put MySQL cell values into variables named after column names in PHP

This code selects cell values in MySQL and manually adds them to PHP variables:
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)) {
$col1 = $rows['col1'];
$col2 = $rows['col2'];
$col3 = $rows['col3'];
.....
}
This is obviously unmanageable for multiple and large tables.
What's a better way to automatically generate the variable names and values without manually entering all the column names on all tables?
I think this is what you're looking for
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($rows as $key => $value) {
$$key = $value;
}
}
You could use extract() for that. But I'd keep the values in the array.
..SELECT x,y,z FROM ..
while( false!==($rows=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
extract($rows);
echo $x;
...
}
Wouldn't it be more convenient having associative arrays? That way you can call your variables with their column name as you describe plus you have the benefit of having them bundled in one unit which is much better if you need to pass more than one of them to any function or view or whatever.
so I would use mysql_fetch_assoc and that's it.
I don't recommend having a variable for each row, I used to do the same to simplify writing HTML later:
echo "<tr><td>$name</td><td>$count</td></tr>";
Instead of:
echo "<tr><td>{$row['name']}</td><td>{$row['count']}</td></tr>";
Until I found a better and more readable way do it using mysql_fetch_object
while ($row = mysql_fetch_object($result)) {
:
echo "<tr><td>{$row->name}</td><td>{$row->count}</td></tr>";
:
}
Use variable variables:
Code example:
$a = 'col1';
$$a = 'somevalue';
echo $col1;
will output 'somevalue'.
http://www.php.net/manual/en/language.variables.variable.php

Categories