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
Related
This question already has an answer here:
How to get column names from PDO's fetchAll result?
(1 answer)
Closed 2 years ago.
The following code works perfectly well unless there is only one result, in which case only the <tr> containing the column names displays in the web page. Further, a search for the name 'Bracker' produces the result as described above but a search for 'Bra' works correctly while 'Brac' does not. The same does not apply to the name 'Dawe' which, if there is only one result, only appears amongst many others when a search for 'Da' is undertaken.
<?php
include 'connect.php';
if (isset($_POST['submit-keyword'])) {
$keyword = ($_POST['keyword']);
$qry = "SELECT * FROM Ely_NBR WHERE Founder LIKE ? ORDER BY DATE";
$stmt = $con->prepare($qry);
$stmt->execute(["%$keyword%"]);
print "<table>";
$result = ($stmt);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print " <tr>";
foreach ($row as $field => $value){
print " <th>$field</th>";
} // end foreach
print " </tr>";
//second query gets the data
$data = ($stmt);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr>";
foreach ($row as $name=>$value){
print " <td>$value</td>";
} // end field loop
print " </tr>";
} // end record loop
print "</table>";
}
?>
You are using your first result row to display the column headings. When you call PDOStatement::fetch() it moves its internal cursor on the result set.
Therefore your loop to display the data starts printing the results from the 2nd row.
See PDOStatement::fetch() documentation: Fetches the next row from a result set.
If you want to get the column names you may want to look at:
PDOStatement::columnCount()
PDOStatement::getColumnMeta()
And print headings like this:
for ($i = 0; $i < $stmt->columnCount(); $i++) {
$columnInfos = $stmt->getColumnMeta($i);
echo '<th>' . $columnInfos['name'] . '</th>';
}
I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.
I have an app that records months and years by one CSV entry, i.e. db column named answer1 is jan,2008 and column answer2 is feb,2013. I want to use a specific month (jan) in html but it only gives me the last array data.
<?php
foreach ($row as $colName => $colValue )
{
if($colName === answer1 || $colName === answer2)
{
//break apart date data
$myArray = explode(',', $colValue);
echo '<div id=" ' .$colName . $myArray[0] . ' ">test</div> ';//this works
};
};
?>
I'd like something like this in another php block later in the doc.
<?php echo '<div id=" '.$colName[answer2] . $myArray[0] . ' ">test</div> ';?>
This is probably a lot easier. We're exploding (or pulling two substrings) from the original columns in MySQL before we get to PHP. Then you can use them however you would like:
$query = "SELECT SUBSTRING_INDEX(answer1,',',1) as a1_month,
SUBSTRING_INDEX(answer1,',',-1) as a1_year,
SUBSTRING_INDEX(answer2,',',1) as a2_month,
SUBSTRING_INDEX(answer2,',',-1) as a2_year from my_table";
$result = mysqli_query($query);
$answers = array();
$x = 0;
while ($row = mysqli_fetch_array($result)){
$answers[$x]['answer1_year'] = $row['a1_year'];
$answers[$x]['answer1_month'] = $row['a1_month'];
$answers[$x]['answer2_year'] = $row['a2_year'];
$answers[$x]['answer2_month'] = $row['a2_month'];
$x++;
}
print_r($answers);
If for some reason you still want the concatenated strings you can do this:
$answer1 = $answers[0]['answer1_month'].','.$answers[0]['answer1_year'];
$answer2 = $answers[0]['answer2_month'].','.$answers[0]['answer2_year'];
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
This one is confusing me. I have two different mySQL tables I need to pull information from and I am creating a html dropdown table and trying to populate the value from a variable. It works the first time through the loop, but not after that. I get a warning (when viewing the html):
b>Warning</b>: array_combine() expects parameter 1 to be array, integer given in <b>/MY URL</b> on line <b>56</b><br />
<br />
Easier to just show the code, so here it is:
$UserID = "118";
$UndefinedEvents = array();
$EventDates = array();
$UserTimelines = array();
$query = "SELECT * FROM events WHERE UserID='$UserID' AND ParentEventID IS NULL";
$result = mysql_query($query);
$query2 = "SELECT * FROM timelines WHERE UserID='$UserID'";
$result2 = mysql_query($query2);
//Getting the Timeline names and their IDs
while($row = mysql_fetch_array($result2))
{
$UserTimelines[] = $row['TimeLineName'];
$TimelineID[] = $row['TimeLineID'];
}
//Getting and events that have a NULL value
while($row = mysql_fetch_array($result))
{
echo $row['UserID'] . " ".$row['EventName']. " " . $row['ParentEventID'];
$UndefinedEvents[] = $row['EventName'];
$EventDates[] = $row['StartDate'];
}
//Iterating through events with NULL value and telling user which events are NULL
foreach (array_combine($UndefinedEvents, $EventDates) as $event=>$dates){
echo "This Event does not have a Timeline associated with it: " .$event . " on ".$dates. '<br>';
echo "Choose a Timeline:<br>";
?>
<select>
//THIS IS LINE 56: Iterating through the timelines and creating a dropdown for the user to choose a timeline.
<?php foreach (array_combine($TimelineID, $UserTimelines) as $TimelineID=>$timeline){
echo "<option value=".$TimelineID."> ".$timeline. "</option>";
}
echo " </select><br><br>";
}
?>
<?php
mysql_close($con);
?>
Like I said, it works the first loop, and is properly putting the values in, but each loop after just creates the above warning.
In your second foreach, you are overwriting your $TimelineID variable:
foreach (array_combine($TimelineID, $UserTimelines) as $TimelineID=>$timeline){
Just use something else like:
foreach (array_combine($TimelineID, $UserTimelines) as $temp_TimelineID=>$timeline){
Just to check... in this code, you get the ID and name from one row, and put them into two separate arrays...
//Getting the Timeline names and their IDs
while($row = mysql_fetch_array($result2))
{
$UserTimelines[] = $row['TimeLineName'];
$TimelineID[] = $row['TimeLineID'];
}
...then you combine those arrays together later to generate the option value/description?
Why not store both values from each row in one element of an array (an array of arrays)? or use an associative array - with the id as the key, and the text as the value? (or better yet, map the rows to objects)
http://php.net/manual/en/language.types.array.php