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.
Related
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.
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;
}
}
hi am building a quiz system and basically i have my questions in an array called $questions and answers in an array $answers i have created an interface in html php to add data questions and answers into this arrays
$question1 = $_POST['question1'];
$question2 = $_POST['question2'];
$ans1 = $_POST['ans1'];
$ans2 = $_POST['ans2'];
$questions = array();
array_push($questions,$question1,$question2);
$answers = array();
array_push($answers,$ans1,$ans2);
so to insert this values in a database this is what i do
$quest_count = count($questions);
for ($i=0;$i<=$quest_count;$i++)
{
$query = "INSERT INTO quiz (question,answer) VALUES ('$questions[$i]','$answers[$i]')";
$result = mysql_query($query);
}
so my problem is this the for loop should add two rows in the database since the questions array contains two values question1 and question2 but it only adds one row. can anyone help me out on this am sure its ('$questions[$i]','$answers[$i]') part that has a problem.
thanks
You're using the <= operator in your loop.
Change it to just less than:
for ($i=0;$i<$quest_count;$i++)
{
$query = "INSERT INTO quiz (question,answer) VALUES ('$questions[$i]','$answers[$i]')";
$result = mysql_query($query);
}
Also, make sure you properly sanitise your input strings.
Please use < than using <= in the for loop, this will ensure that the loop runs twice or the exact of count of question array.
Try this:
Here no need to count array values & for loop. Instead use foreach loop.
Here is the solution:
foreach ($questions as $key1 => $que, $answers as $key2 => $ans)
{
$query = "INSERT INTO quiz (question,answer) VALUES ('$que','$ans')";
$result = mysql_query($query);
}
-
Thanks
i am running a mysql query to return all rows from a temp database, i then need to ammend some of the attributes in those rows so i am trying to return each row to an array so i can then reference the array and amend specific attributes of each row
im just stuck on how to get each row into its own array, im guessing i will need to use a 2d array for this however cannot figure out how to populate it from the mysql query into the 2d array. Im guessing it is something like i have tried below?
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $var;
foreach($row as $key => $var) {
// Insert into array
echo $var;
}
however when trying this i am getting a notice saying:
Notice: Array to string conversion
any help pointing me in the right direction for this would be great
If I understand what you're asking for, you literally want each row from the SQL query to be a single index in the $result_array array?
If that's the case, you're already getting it with $row - you can add that directly to the array:
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $row;
}
You can modify the values inside the array either when you're adding them to the global array, or after:
foreach ($result_array as $index => $row) {
$result_array[$index]['some_key'] = $row['some_key'] . ' [modified]';
}
Side-note (not answer specific)
I would recommend against using the old, deprecated mysql_ functions and instead favor MySQLi or PDO. Both of these are easy to use, more secure than the older methods and offer a large range of features such as prepared statements.
The above can be written with mysqli like:
if ($result = mysqli_query($connection, $query)) {
$results = array();
while ($row = mysqli_fetch_assoc($result)) {
$results = $row;
}
mysqli_free_result($result);
}
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