how to get variables from column names [duplicate] - php

This question already has answers here:
variable variables
(5 answers)
Closed 1 year ago.
how to get variables from column names
$sq = "select * from arts where id = :aid limit 1";
$st = $db->prepare($sq);
$st->execute([":aid" => $id]);
$row = $st->fetch();
now, instead of:
$cat = $row['cat'];
$title = $row['title'];
$subtitle = $row['subtitle'];
... so on
I need something like:
foreach($column_name as $el){
$var_name = $el;
}

There's rarely a good reason to do this, just use the array. However, you can use variable variables from the keys if there is only one row as you show:
foreach($row as $key => $val){
$$key = $val;
}
There is also extract() but may be even worse practice.

Related

PHP: print all the items of an array [duplicate]

This question already has answers here:
MySQL Results as comma separated list
(4 answers)
Comma separated string of selected values in MySQL
(10 answers)
Just need a comma separated list from PHP/MySQL query [duplicate]
(5 answers)
Closed 2 years ago.
My goal: insert into a variable an array of items coming from a query and then print it
steps:
launch the query
do something with php
print the variable $report = 'this is your list: $list';
tried this:
$myquery = mysqli_query($dbconnection, "SELECT ...");
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, "; /* here I've the full list*/
}
$report = 'this is your list:' .$my_array. '.';
echo "$report"; /*I've only one item and not all the list*/
Your first echo is called several times because it is in the loop.
In every iteration you are replacing your content of $my_array.
Instead, try to attach it:
$my_array[] = $row['field'];
For more information see https://www.php.net/manual/de/language.types.array.php
This is normal.
Your while loop doing a "step" for each row found with your query.
You assigned $my_array as the "column" with the name field.
So at the end of the while loop, you'll get only the last column field of the last row.
Instead, try this
$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, ";
$myWholeList .= '$my_array '; // HERE
}
$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE
I've done a string concatenation, but you can do it with array and print_r() function. Have a look on this thread to see how to append data to an array.
mysqli_fetch_array while loop columns
EDIT:
Based on #isabella 's comment, she wants to display 7 items of array.
Two way :
Use print_r() or var_dump() which is the best to display an array (without taking care about rendering)
Add to $myWholeList variable each item.
e.g.
$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, ";
// HERE
foreach($row as $field) {
$myWholeList .= $field . ' ';
}
$myWholeList .= '<br>'; // NEW LINE
}
$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE

Undefined index from a foreach() loop [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
ItemDb class
public function getRandomItem() {
$query = "SELECT * FROM `items` ORDER BY RAND() LIMIT 2";
return $this->query($query);
}
Index.php
$item = new Item();
$result = $item->getRandomItem();
while ($row = $result->fetch_assoc()) {
foreach ($row as $key => $value) {
//I want to put them in a array but the two items need to be separated
}
}
I get two different items out of the database how can I split them and put them in one array separated like:
$array[$key][$value]
Sorry for my English its my second language and I hope you guys understand me.
You need to declare $itemArray[$key] before you use it. So your code needs to look like
$itemArray = array();
while ($row = $result->fetch_assoc()) {
foreach ($row as $key => $value) {
if(!isset($itemArray[$key])) {
$itemArray[$key] = array(); //Declare it
}
$itemArray[$key][] = $value;
}
}

Create an array from values from mysql table [duplicate]

This question already has answers here:
Creating an array from a MySQL table
(2 answers)
Closed 10 years ago.
I am using PHPlot to make a graph.
I have an issue in generating the array from a MySQL table.
Basivally, I want to array is as follows:
$values = array($arrayx);
array('a',-3),
array('b',5),
array('c',7),
array('d',8),
array('e',12),
array('f',-6),
//);
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
Part of the code where I tried to retrieve values from table to feed the array
$query="SELECT * FROM tasks";
$result=mysql_query($query);
//using a for loop to add values to the array
while ($resource=mysql_fetch_array($result)){
$thedate = $resource["date"];
$title = $resource2["title"];
$innerarray = "array('.$thedate.', $title),";
}
$values = array($innerarray).");";
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
//Draw it
$graph->DrawGraph();
}
The way I'm doing the $innerarray and $values seems wrong. Can you please help me fix it?
Thank you
try replacing
$innerarray = "array('.$thedate.', $title),";
with
$innerarray = array($thedate, $title);
$new = array();
while(for condition ){
$new[] = '\''.thedate[$i].''\','.$title[$i].'\';
}
var_dump($new);
this an idea, you need to edit the code to make it working
I assume it is this that you want:
$sql="SELECT datefield, titlefield FROM tasks";
....
while (list($thedate,$thetitle) = mysql_fetch_array($result)) {
$values[] = array($thedate,$thetitle);
}
echo $values[0][0]; // will output your 1st date
echo $values[0][1]; // will output your 1st title

Compare values from array mysql php [duplicate]

This question already has answers here:
Passing an array to a query using a WHERE clause
(17 answers)
Closed 1 year ago.
Hi I'm trying to compare values from 2 arrays with this query, which is the only way I know:
$session = "1,2,3,"
$table_name = "table1";
$column_name = "data1"; // value for test is 1,4,5,
$sql = "";
$sql .= "SELECT * FROM $table_name WHERE ";
$franquia = array();
$franquia = explode(",", $session);
if (!empty($franquia)) {
$final_id = array();
foreach ($franquia as $val) {
if (trim($val) != '') {
$final_id[] = $val;
}
}
$count_data = count($final_id);
foreach ($final_id as $key => $id) {
if ($id > 0) {
$sql .= " $id IN ($column_name) ";
if ($key < $count_data - 1) {
$sql .= "OR ";
}
}
}
}
echo $sql;
I have values 1,2,3 on $session and 1,4,5on $data1 so the comparison between $session and $data1 was suposed to return true due to both of them have value 1, but I don't get any results.
Actually it only works if both arrays are the same, like $session = 1,2,3 and $data1 = 1,2,3
What am I doing wrong?
You are using the IN clause wrong; In a nutshell, instead of
WHERE value IN (column)
The correct usage is:
WHERE column IN (value, value, value)
Which in turn will not help with what you are trying to do (more about the IN clause). Rather, try the following:
foreach ($final_id as $key => $id) {
if ($id > 0) {
$sql .= "$column_name LIKE %$id,%";
if ($key < $count_data - 1) {
$sql .= "OR ";
}
}
}
}
This should work, but there are a couple things you should be aware of. First you probably are vulnerable to SQL Injections, and second you should consider either using a different scheme with your data in your DB, since using LIKE %% to search for numeric values is a waste, or fetch in advance the entry from the DB and search in the resulting string. Consider the code above nothing but a quick and dirty hack that you should rather avoid :)

Can I convert individual fields of a 'mysql_query' to arrays? [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
Likely a remedial question, but in all my days as a PHP user I have yet to encounter an answer. Basically, is there any way to grab a single field of a "mysql_query" as an array? For instance say I have the following:
$query = "Select id,first_name,last_name FROM people";
$result = mysql_query($query);
Is there any way to grab each (id, first_name, last_name) as individual arrays without iterating through the recordset? Can I say something like:
$ids = field_to_array($result['id']);
$first_names = field_to_array($result['first_name']);
$last_names = field_to_array($result['last_name']);
As I said, in the past I've always simply built the arrays as needed, but an existing method would be handy.
mysql doesn't have that as a native function. you could always write your own..
function mysql_convert_cols($dataset) {
foreach ($dataset as $row => $values) {
foreach ($values as $column => $value) {
$return[$$column][$row] = $value;
}
}
return($return);
}
$resultConverted = mysql_convert_cols($result);
$id=$resultConverted['id'];
$firstName=$resultConverted['firstName'];
I'm not sure why do you need this , but you can do it like this :
$resultArray = array();
while($row = mysql_fetch_array($result)){
$resultArray[] = array(
"id" => $row['id'],
"firstName"=>$row['first_name'],
"lastName"=>$row['last_name']
);
}
Check if values are in :
print_r($resultArray);
Then you can foreach or to do the for loop on values.

Categories