Obtaining data from query in multidimensional array - php

I have spent a lot of time trying to find ways to do the following, and have researched as much as I can but am still stuck.
I have a table 'pool_a' that at the minute has 2 columns - team_id and team_name.
I need to echo the id and the name into a nested foreach loop.
Now I can do this if I am just worried about the name, but now my query includes the ID too, I can't work out how to get both bits of data for each row in my table.
Here's how I get it to work with team_name...
for ($i=0;$i<$num;$i++) {
$team=mysql_result($result,$i,'team_name');
$team_names[$i] = $team;
echo $team . "<br>";
}
foreach ($team_names as $team) {
foreach ($team_names as $opposition) {
if ($team != $opposition) {
echo "<tr><td>" . $team . "<td><input type=\"text\"<td>versus<td><input type=\"text\">" . $opposition . "</tr>";
}
}
}
This is great, and outputs the correct fixture list and with input boxes for scores, but I need to add a hidden data input with team_id as the value. For example:
Here is what I have so far. Note that I have been learning about PDO's and new 5.5 techniques, so you will notice my style of code will be different in the next snippet.
require_once "pdo_enl_connect.php";
$database=dbNB_connect();
$query=$database->query ("SELECT team_id, team_name from pool_a");
while ($row = $query->fetch(PDO::FETCH_NUM)) {
printf ("%s %s<br>", $row[0], $row[1]);
$teams=array($row[0], $row[1]);
}
foreach ($teams as $key=>$value) {
echo "$key and $value<br>";
}
$database=NULL;
The output I get for the foreach loop is
0 and 5
1 and Silhouettes //silhouettes being the last team in the table.
ANy help would be much appreciated, and please let me know if I can edit my question to make it clearer in any way.
Thanks

Your while loop should look like this:
$teams = array();
while ($row = $query->fetch(PDO::FETCH_NUM)) {
// $row and array($row[0], $row[1]) are the same here
$teams[] = $row;
}

You need to initialize $team = array(); before your loop.
Then add your tuple to the teams array by doing either array_push($teams, array($row[0], $row[1])); or $teams []= array($row[0], $row[1]);`

Related

How to copy an associative array inside another associative array in PHP

Can anyone tell me how to store an array of associative arrays? I thought this code would work, but it's not. I tried researching it but couldn't find an answer.
foreach($rows as $row) {
// Some SQL...
if ($stmt->execute()) {
while ($row2 = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['NestedResults'][] = $row2;
}
}
}
foreach ($rows as $row) {
foreach ($row['NestedResults'] as $results) {
echo $results['Item'] . '<br>';
}
}
PS: I know I shouldn't loop SQL statements like that, but it's a special case.
In your first foreach loop, you need to pass the $row variable by reference, otherwise you are just modifying a copy of the element from $rows stored in $row:
foreach($rows as &$row)
do you think it is workable to put the second loop inside the first one as below?
$row['NestedResults'][] = $row2;
foreach ($row['NestedResults'] as $results) {
echo $results['Item'] . '<br>';
}
not 100% sure...

Php - Array to string conversion

I want to output all records in my database. So far so good, but when I loop through it, php gives me an error " Array to string conversion ".
I added an index to the array but then it does just output obviously the first or secound ( etc. ) column.
$conn = new PDO("mysql:host=localhost;dbname=database","root","");
$stmt = $conn->prepare('SELECT * FROM de');
$stmt ->execute();
$result = $stmt ->fetchAll();
if (is_array($result) || is_object($result))
{
foreach ($result[0] as $value)
{
echo "<table><tr><td>'$value'</td></tr></table>";
}
}
So, with the index, it does work. But I need all records, not just one.
I appreciate every comment and help!
I would start with a nested loop. I also wonder if you want a table for every value
$conn = new PDO("mysql:host=localhost;dbname=database","root","");
$stmt = $conn->prepare('SELECT * FROM de');
$stmt ->execute();
$result = $stmt ->fetchAll();
if (is_array($result) || is_object($result))
{
foreach ($result as $row){ //Go through every row in the result
echo('<table>');
foreach ($row as $value){ //Go through every value in the row
echo "<tr><td>'$value'</td></tr>";
}
echo('</table>');
}
}
This will print every row as a new table, but you can search out the variation you want.
A nested foreach loop should work.
foreach ($result as $values)
{
foreach ($values as $value) {
echo "<table><tr><td>'$value'</td></tr></table>";
}
}
An alternative to nested loops, if you know the number of fields and said number is constant for each execution; A state that's found in most situations; You can use vsprintf () to print out the rows.
Quick example:
$result = {{'John', 'Doe'}, {'Sarah', 'Jane'}};
$output = '<table>';
foreach ($result as $row) {
$output .= vsprintf ("<tr><td>%s</td><td>%s</td></tr>\n", $row);
}
echo $output."</table>";
Cuts down a bit on the code, and quite a bit on the code complexity. The template for the rows themselves can also be extracted to a variable (or template view), outside of the loop, to make the code even cleaner.

PHP to display all MySQL columns without knowing how many there are

I need some PHP code to display all columns (without referencing how many there are, or their names) in a comma separated, one row per line, format.
I am a novice and have only ever worked with examples where I reference the columns by name:
$result = mysql_query("select * from table1");
while($row = mysql_fetch_array($result))
{
echo $row["field1"].','.$row["field2"];
}
In the above code, can I create a looping echo command based on the number of columns (how do I get this value?) to print all the columns – if I can display the column names in the first row of output, great, but it’s not essential. Or, is there a specific command that will achieve the same result?
I think the answer is a foreach($row as....) - but not sure where to go from there.
Yep you can do a foreach but if you just want to display your values in a CSV style you can do :
$firstRow = true;
while($row = mysql_fetch_array($result))
{
if ($firstRow) {
$firstRow = false;
$columns = array_keys($row);
// prints all the column names
echo implode(',', $columns);
}
// print all the values
echo implode(',', $row);
}
If you want more control over what you output you can use a foreach :
while($row = mysql_fetch_array($result))
{
foreach ($row as $column => $value) {
echo $column.' : '.$value."\n";
}
}
You'll want to count the $row array
while($row = mysql_fetch_array($result))
{
$columns = count($row);
for($i = 0; $i < $columns; $i++)
{
echo $row[$i].',';
}
}
Or you can use foreach() as #Dagon has pointed out -
while($row = mysql_fetch_array($result))
{
foreach($row as $column)
{
echo $column . ',';
{
}
Please, stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO.

rewind one step back in mysql_fetch_array()

this is the values in the $result
id name
1 a
2 b
2 c
2 d
3 e
..
I'm creating a loop function using mysql_fetch_array()
while($row = mysql_fetch_array($result)) {
$temp_id = $row['id'];
while($temp_id == $row['id']) {
if($temp_id == $row['id']) {
mysql_fetch_array($result);
}
$temp_id = $row['id'];
echo $row['name'].",";
}
echo "<br/>";
}
this works but the problem is, the mysql_fetch_array jumps on one of the values during the transition of the id's..
I want the values of this to be like these
a
b,c,d
e
my question is, is there a simple rewind function that will step only once in the rows?
I have searched about the mysql_data_seek() but I think this would require additional control variables like $i to locate the address..
thanks.. any suggestions and function samples will be very great!
Use one loop with mysql_fetch_array first to create an array of the rows. Then, iterate over the rows themselves.
Based on the update to your question it seems like you would want to use GROUP_CONCAT in the query, but you can still do it in PHP:
$rows = array();
while($row = mysql_fetch_assoc($result)) {
if (!isset($rows[$row['id']]) {
$rows[$row['id'] = array();
}
$rows[$row['id']][] = $row['name'];
}
foreach ($rows as $row) {
echo implode(',', $row) . "<br>";
}
Try this code
while($row = mysql_fetch_array($result)) {
$temp[$row['id']][] = $row['name'];
}
foreach($temp as $row) {
echo implode(',', $row) . '<br/>';
}

Why is PDOStatement->columnCount not returning the right number?

I'm querying the database first to get all records associated with a certain userid, then i need to go in and modify the array, because one of the fields is an id and i need the name associated with that id.
So i use columnCount to iterate through the resulting array at the index of the id and replace it with the right name, which works fine, for the first six results. columnCount only returns 6, but those first six are renamed as they should be. But outside of that it takes the results from that pdostatement and populates the table normally, with all the relevant data, 17 rows right now.
Why is it returning 6, or what am i doing to get that wrong columncount?
global $__CMS_CONN__;
$timeqry = 'SELECT facility_id, program, date, visit_length, mileage, served FROM timesheet_db WHERE volunteer_id = '.$_SESSION['user_id'];
$stmt = $__CMS_CONN__->prepare($timeqry);
$stmt->execute();
$columns = $stmt->columnCount();
print $columns;
if($stmt)
{
$arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);
for($x=0;$x<$stmt->columnCount();$x++)
{
global $__CMS_CONN__;
$qry = 'SELECT facility FROM facility_db WHERE id = '.$arrValues[$x]['facility_id'];
$stmt1 = $__CMS_CONN__->prepare($qry);
$stmt1->execute();
if($stmt1)
{
$facilityName = $stmt1->fetchAll(PDO::FETCH_ASSOC);
foreach ($facilityName as $item)
{
foreach ($item as $key => $val)
{
$arrValues[$x]['facility_id'] = $val;
}
}
}
}
print "<table style=\"font-size:90%\">\n";
print "<tr>\n";
print "<th style=\"width:100%\">Facility</th>";
print "<th>Program</th>";
print "<th>Date</th>";
print "<th>Visit Length</th>";
print "<th>Mileage</th>";
print "<th>Served</th>";
print "</tr>";
foreach ($arrValues as $row)
{
print "<tr>";
foreach ($row as $key => $val)
{
print "<td>$val</td>";
}
print "</tr>\n";
}
print "</table>\n";
}
You asked for six columns in your first SELECT query:
SELECT facility_id, program, date, visit_length, mileage, served FROM timesheet_db WHERE volunteer_id = $_SESSION['user_id']
So, naturally, columnCount() is 6. It doesn't multiply the column count by the number of rows returned or anything like that.
If you want the number of rows, you need count($arrValues) (the manual says database behavior with rowCount() is inconsistent regarding SELECTs).

Categories