mysqli_fetch_array using a foreach loop - php

Ive got a pretty basic table named 'customers' with four columns:
ID (primary Auto Increment)
businessName
contactName
contactEmail
I call it with:
$result = mysqli_query($con, "SELECT * FROM customers");
and was using mysqli_fetch_array to display it on the page with a foreach loop:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}
Which gives you an array like:
Array ( [id] => 1 [businessName] => Microsoft [contactName] => Bill Gates [contactEmail] => bill#microsoft.com ) Array ( [id] => 2 [businessName] => Amazon [contactName] => Jeff Bezos [contactEmail] => jeff#amazon.com )
Is it possible to display results differently based on which column (technically now position in the array) they are in? I would like to make a
a href="mailto:bill#microsoft.com"
link when it gets to contactEmail.
What if I wanted to display just one key or value instead of using foreach?
It doesn't seem possible to call
$row['contactEmail']
in the foreach loop
which confuses me since below that I am able to create a link to
$row['id']
If anyone has any ideas how to do this, or if there is a better way to be displaying this information, I'm open to suggestions, as I'm not very good at programming, especially PHP.

Yes! you can just add like this:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
foreach ($row as $key => $value) {
if($key == "contactEmail"){
$mailUrl = "mailto:".$value;
echo "<td>".$value."";
}
else{
echo "<td>" . $value . "</td>";
}
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}

Yes, You can able to mysqli_fetch_array retrieve data directly using foreach loop. like bellow :
<?php
$result = mysqli_query($con, "SELECT * FROM customers");
?>
<table>
<tr>
<td>Business Name</td>
<td>Contact Name</td>
<td>#</td>
</tr>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>".$row['businessName']."</td>";
foreach ($row as $key => $value) {
$newValue = $key == "contactEmail" ? ''.$value.'' : $value;
echo "<td>" . $newValue . "</td>";
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}
?>
</table>

Related

Foreach associative array table

**Edit: We got there in the end, Thanks guys! It was the HTML tables confusing me.
<tr>
<td><?php echo $row['owner_firstname'];?></td>
<td><?php echo $row['owner_surname'];}?></td>
</tr>**
I am trying to put some information into a table and I don't want to do it using this method...
<tr>
<td><?php echo $rows[0]['owner_firstname'] ; ?></td>
<td><?php echo $rows[0]['owner_surname'] ; ?></td>
<td><?php echo $rows[0]['owner_contantno'] ; ?></td>
</tr>
I want to use a foreach loop but I am struggling to get it working, Each person from the database is [0],[1],[2] etc in my array.
Here is a print_r of my dataset
Array
(
[0] => Array
(
[ID] => LEI12345
[owner_firstname] => Shanel
[owner_surname] => **********
[owner_contantno] => *******
[owner_address] => ********
[band_firstname] => Nathan
[band_lastname] => **********
[band_disability] => *******
[band_emergencycontact] => ********
[band_description] => ************
)
)
$data = $yourDataSet; // your data set here
// check data
if($data) {
foreach($data as $val) {
$str = "";
$str = "<tr>";
$str .= "<td>" . $val['owner_firstname'] . "</td>";
$str .= "<td>" . $val['owner_surname'] . "</td>";
// add other td here if there's more
// end of tr
$str .= "</tr>";
echo $str;
}
}
try this one, i hope this one would help
from your for each you can grab results like this
get your results to an array
$rows = mysql_fetch_array($query);
foreach($rows as $key=> $row){
if(is_array($row))
foreach($row as $id => $val)
echo '<td>'.$val.'</td>';
}

PHP Associative Array To Table

I am trying to sort an associative array in ascending in order and then transfer it to a HTML table and I am currently stumped at an error. I looked for guidelines here on SO and followed instructions on some posts:
PHP display associative array in HTML table
But still no luck, here is my attempt:
<?php
function format($g){
array_multisort($g, SORT_ASC);
echo "<table>";
foreach($g as $key=>$row) {
echo "<tr>";
foreach($row as $key2=>$row2){
echo "<td>" . $row2 . "</td>";
}
echo "</tr>";
}
echo "</table>";
}
$bib = array("Luke"=>"10",
"John"=>"30",
"Matt"=>"20",
"Mark"=>"40");
format($bib);
?>
My debugger is telling me there is an error at my for each loop but I don't see how it is wrong unless there is some syntax error that I am not seeing? The error is saying Invalid argument supplied for foreach()
Because your $bib is only single array but you use two foreach to loop this array
At 2nd loop, your $row variable is a string, you can't use foreach for this type
Can you try that for single array ?
<?php
function format($data) {
array_multisort($data, SORT_ASC);
echo "<table>";
foreach($data as $k => $v) {
echo "<tr>";
echo "<td>$k</td>";
echo "<td>$v</td>";
echo "</tr>";
}
echo "</table>";
}
$bib = array("Luke"=>"10",
"John"=>"30",
"Matt"=>"20",
"Mark"=>"40");
format($bib);
?>
$k is Luke John Matt and Mark,
$v is 10 30 20 and 40
You can see the foreach example here: http://php.net/manual/en/control-structures.foreach.php
Hope this helpful ^^
You can try this
<?php
function format($data){
array_multisort($data, SORT_ASC);
echo "<table>";
foreach($data as $key => $row) {
echo "<tr>";
echo "<td>" . $key . "</td>";
echo "<td>" . $row . "</td>";
echo "</tr>";
}
echo "</table>";
}
$bib = array(
"Luke"=>"10",
"John"=>"30",
"Matt"=>"20",
"Mark"=>"40"
);
format($bib);
?>

New line after multiple columns

Hi all i'm not very experienced with programming so this is probably easy to achieve.
I am pulling data from a mysql table using php i want to display the output like so:
$row[1] $row[2] Line break
$row[3] $row[4] Line break
$row[5] $row[6] Line break
And so on
Any help would be appreciated thanks
$user_table = select_table( "users", "user_name ASC" );
$rows = array( );
while( $row = mysqli_fetch_assoc( $user_table ) ) {
$rows[] = $row;
}
$user_groups = array_chunk( $rows, 2 );
foreach ( $user_groups as $user_group ) {
echo "<tr>";
foreach( $user_group as $row ) {
echo "<td class=\"user-box\">{$row["user_name"]}</td>";
}
echo "</tr>";
}
This is my working code. Thanks Tim
Loop through your results and start counting again after 2.
here's an example using a simple array and a table so you can see how it works
<?php
$results = array('one','two','three','four');
echo '<table border="1">';
foreach(array_chunk($results,2) as $row) {
echo '<tr>';
foreach($row as $value) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</table>';

Output each mongodb record to an html table

I'm building an app which pulls records from a MongoDB. I've built the thead>tr>th as follows:
// building table head with keys
$cursor = $collection->find();
$array = iterator_to_array($cursor);
$keys = array();
foreach ($array as $k => $v) {
foreach ($v as $a => $b) {
$keys[] = $a;
}
}
$keys = array_values(array_unique($keys));
// assuming first key is MongoID so skipping it
foreach (array_slice($keys,1) as $key => $value) {
echo "<th>" . $value . "</th>";
}
This gives me:
<thead>
<tr>
<th>name</th>
<th>address</th>
<th>city</th>
</tr>
</thead>
This works very well, it grabs all the keys and builds the table head. I don't have to specify anything and the thead is built dynamically from the data. The part I'm unable to figure out is building all of the tr>td's
I can easily grab the info and build it like this:
$cursor = $collection->find();
$cursor_count = $cursor->count();
foreach ($cursor as $venue) {
echo "<tr>";
echo "<td>" . $venue['name'] . "</td>";
echo "<td>" . $venue['address'] . "</td>";
echo "<td>" . $venue['city'] . "</td>";
echo "</tr>";
}
Doing so requires me to modify my php every time I add a new field. How can I build the tr>td's automagically based on the data from mongodb like I am with the thead?
My data looks like this:
{
"name": "Some Venue",
"address": "1234 Anywhere Dr.",
"city": "Some City"
}
Have you try to use second foreach as below
$cursor = $collection->find();
$cursor_count = $cursor->count();
foreach ($cursor as $venue) {
echo "<tr>";
foreach (array_slice($keys,1) as $key => $value) {
echo "<td>" . $venue[$value] . "</td>";
}
echo "</tr>";
}

How to put array into session?

This is assignment so not looking for anything perfectly safe and secure, just working.I have table in SQL database, I'm printing down all records, all records have unique reference number, for each row of the database I printed down I gave checkbox with value of the row's ref. number, when I submit them by "POST" everything is working and printing out:
if (!$_POST['checkbox']) {
echo "Your basket is empty.";
} else {
echo "<table border='0' id='games_table' cellspacing='1'>";
echo "<tr id='basket_table_row'>";
echo "<td colspan='3'>" . "Logged: " . $_SESSION['user'] . "</td>";
echo "<td colspan ='2'>" . "OS used on this machine: " . "<script type='text/javascript'>document.write(yourOS())</script><noscript>Computers</noscript>" . "</td>";
echo "</tr>";
echo "<tr id='basket_table_row'>";
echo "<td colspan='5'>" . "You put into the basket these games: " . "</td>";
echo "</tr>";
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket']=array($value);
$res=pg_query($conn,"select * from CSGames where refnumber='$value'");
while ($a = pg_fetch_array ($res)) {
echo "<tr id='games_table_row'>";
echo "<td>" . $a["refnumber"] . "</td>";
echo "<td>" . $a["title"] . "</td>";
echo "<td>" . $a["platform"] . "</td>";
echo "<td>" . $a["description"] . "</td>";
echo "<td>" . $a["price"] . "</td>";
echo "</tr>";
}
}
echo "</table>\n";
}
but only think which stays recorded in $_SESSION['basket'] is value of the last checkbox but I need all of them (60 or 70).
what Am I doing wrong?
You are overwriting te value of $_SESSION['basket'] at each iteration of the loop.
The last value is the only one stored.
Currently, you are only storing the last value, if you wish to store every value, you should add it like this:
$_SESSION['basket'][] = $value;
foreach($_POST['checkbox'] as $value){
$_SESSION['basket']=array($value);
}
every iteration of your loop is overwriting the value in $_SESSION['basket'], hence you only seeing the last checkbox value.
In every step of foreach, you create a new array in $_SESSION['basket'] with only one item, the current value of $value. It is corrected like this:
// ...
$_SESSION['basket'] = array();
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket'][] = $value;
// ...
}
// ...
You can directly do it like this
$_SESSION['basket'] = $_POST['checkbox'];
because the data of $_POST['checkbox'] is an array anyway.
What you are doing is looping the $_POST['checkbox'] and saving each data as array to a session.
this $_SESSION['basket'] = $_POST['checkbox'];
and
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket'][]=$value;
}
will have the same value.
What you have right only saves the last value of $_POST['checkbox']

Categories