Automating output of MySQL rows in PHP - php

Continuing from my other question, I now know how to extract the fieldnames into variables with the result stored in them.
However, lets say I wish to output like this:
<?php
echo "Here is field1: ".$row['field1'];
echo "Here is field2: ".$row['field2'];
echo "Here is field3: ".$row['field3'];
?>
And I have over 40 fields in my table, so to avoid having to type them all out like the above, how can I automate it?

foreach ($row as $key => $value) {
echo "Here is '" . $key . "': " . $value . "<br>\n";
}

<?php
for($i = 1; $i < 40; $i++) {
echo "Here is field" . $i . ": ".$row['field' . $i];
}
?>
But I wonder, why do you have 40 columns in your table? Seems like you should redesign it.

foreach ($row as $key => $value) {
echo "Here is ".$key.": ".$value;
}
Or I don't get it:)

Related

PHP - Use variable names with numbers through a loop

In my for loop for ($i = 1; $i <= 3; $i++) i have have html code that will be echod 3 times. The html also using PHP objects ($help).
$help has 3 things, $help->url_1, $help->text_1, $help->icon_1. But through the loop, I want it so that when for example $i is at 2, i want to use $help->url_2, etc. How can i sort of increment the variable name in the echo string of in the loop?
<?php
class Help
{
public $url;
public $text;
public $icon;
}
$help1 = new Help();
$help1->url = 'your url';
$help1->text = 'your text';
$help1->icon = 'url to your icon';
$helps[] = $help1;
//Repeat for other helps (help2, help3, etc.)
?>
Once you have an array of objects, you only need to loop into it using a foreach loop :
foreach ($helps as $help) {
echo "<h3>" . $help->url . "</h3>";
echo "<p>" . $help->text . "</p>";
echo "<img src='" . $help->icon . "' alt='your alt'/>";
}

Adding looped data into associative array with readline

Writing a small program to ask some people their dreams for fun. I'm trying to put the data into an associative array. I want it to come out like this (for example three names:
How many people should I ask their dreams?
*number*
What is your name?
*name*
What is your dream?
*dream*
name's dream is: dream
My code is as follows:
<?php
echo "How many people should I ask their dreams?" . PHP_EOL;
$many = readline();
$dreams = [];
if (is_numeric($many)) {
for ($i = 1; $i <= $many; $i++) {
echo "What is your name?" . PHP_EOL;
$dreams[] = readline() . PHP_EOL;
echo "What is your dream?" . PHP_EOL;
$dreams[] = readline() . PHP_EOL;
}
echo "In jouw bucketlist staat: " . PHP_EOL;
foreach ($dreams as $key => $value) {
echo $key . "'s dream is: " . $value;
}
} else {
exit($hoeveel . ' is geen getal, probeer het opnieuw');
}
?>
It keeps returning this:
0's dream is: *name*
1's dream is: *name*
etcetera.
When you read values from the $dreams array with foreach ($dreams as $key => $value), you're expecting names as keys, but that's not how you inserted the values. You can use the name as the array key like this instead:
for ($i = 1; $i <= $many; $i++) {
echo "What is your name?" . PHP_EOL;
// set a name variable here
$name = readline() . PHP_EOL;
echo "What is your dream?" . PHP_EOL;
// then use that variable as the array key here
$dreams[$name] = readline() . PHP_EOL;
}

Loop through associative array and assign values

I have an array:
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
What I want is to loop through this array, which I have done, but I am now confused because I don't know how to get the output I desire.
foreach ($array as $key => $value) {
//echo $key . "\n";
foreach ($value as $sub_key => $sub_val) {
if (is_array($sub_val)) {
//echo $sub_key . " : \n";
foreach ($sub_val as $k => $v) {
echo "\t" .$k . " = " . $v . "\n";
}
} else {
echo $sub_key . " = " . $sub_val . "\n";
}
}
}
The above code loops through the array, but this line of code:
echo $sub_key . " = " . $sub_val . "\n";
gives me:
step_no = 1 description = Ensure that you have sufficient balance step_no = 2 description = Approve the request sent to your phone
when I change it to:
echo $sub_val . "\n";
it gives me:
1 Ensure that you have sufficient balance 2 Approve the request sent to your phone
But I what I truly want is:
1. Ensure that you have sufficient balance
2. Approve the request sent to your phone
Is this possible at all? Thanks.
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction) {
echo $instruction['step_no'] . '. ' . $instruction['description'] . "\n";
}
If it's HTML you may want to use <ol> and <li>.
It smells like you are not running this script in command line but in browser. If so, then \n makes no visual effect (unless within <pre> block) and you u must use HTML tag <br /> instead. Also, drop concatenation madness and use variable substitution:
echo "{$sub_key}. = {$sub_val}<br/>";
You can simple achieve this way
<?php
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction){
echo $instruction['step_no'].'. '.$instruction['description'].PHP_EOL;
}
?>
Alway keep it simple.

PHP 'While' within a ForEach loop pulling from SQL DataBase

I have a little table being duplicated several times based on the number of entries there are in my SQL Database, which let's say is about colours. These tables will go one place to the right with each new entry. Within that, I now want, within each entry, to be able to automate an output for a few fields. For example, a single table entry might be 'reds' and now I want to display the different shades of red, i.e. 'shade1', 'shade2', 'shade3', 'shade4' from that, and then the next entry might be 'yellows' and I would want it to display as many yellows there were added, i.e. 'shade1', 'shade2'. My code is like this:
<?php
error_reporting(E_ALL ^ E_NOTICE);
$stmt = $conn->prepare("SELECT * FROM colours");
$stmt->execute();
$colours = $stmt->fetchALL();
if($colours){
$i = 1;
foreach ($colours as $key => $colour) {
$coloursrow1 .='<table >
<tr><th>' . "<b>{$colour['colour']}</b>" . '</th></tr>
<tr><td>' . "<img src='{$colour['shade1']}' />" . '</td></tr>
<tr><td>' . "<img src='{$colour['shade2']}' />" . '</td></tr>
<tr><td>' . "<img src='{$colour['shade3']}' />" . '</td></tr>
<tr><td>' . "<img src='{$colour['shade4']}' />" . '</td></tr>
</table>';
$i++;
}
}
?>
And I wondered if instead of all the lines like <tr><td>' . "<img src='../colours/reds/shade1.jpg' />" . '</td></tr>, I could put something like
if($colours){
$i = 1; $x = 1;
foreach ($colours as $key => $colour) {
$coloursrow1 .='<table >
<tr><th>' . "<b>{$colour['colour']}</b>" . '</th></tr>';
}
while ($x < 6) {
'<tr><td>' . "<img src='{$colour['shade$x']}' />" . '</td></tr>';
$x++;
}
foreach ($colours as $key => $colour) {
'</table>';
$i++;
}
}
So that it would grab and output them automatically and also giving me the ability to put a cap on how many can be output.
I tried different ways to accomplish this, but I just keep hitting dead ends. I must be doing something wrong(?)
Seems like it would be something like this, since PDO::fetchAll() returns an empty array or false on error. So just iterate over that set directly. Also, the array access is wrong, it should be {$colour['shade'.$x]}.
<?php
error_reporting(E_ALL ^ E_NOTICE);
$stmt = $conn->prepare("SELECT * FROM colours");
$stmt->execute();
$colours = $stmt->fetchALL();
foreach ($colours as $colour) {
$coloursrow1 .= "<table><tr><th><b>{$colour['colour']}</b></th></tr>";
$x = 1;
while ($x < 6) {
$coloursrow1 .= "<tr><td><img src='{$colour['shade'.$x]}' /></td></tr>";
$x++;
}
$coloursrow1 .= '</table>';
}

Parsing a JSON string with multiple arrays

I am trying to parse this JSON string
$json = {"fields":{
"relationshipStatus":[{"fieldId":4,"name":"Committed"},{"fieldId":2,"name":"Dating"},{"fieldId":6,"name":"Engaged"},{"fieldId":3,"name":"Exclusive"},{"fieldId":7,"name":"Married"},{"fieldId":8,"name":"Open Relationship"},{"fieldId":5,"name":"Partnered"},{"fieldId":1,"name":"Single"}],
"ethnicity":[{"fieldId":1,"name":"Asian"},{"fieldId":2,"name":"Black"},{"fieldId":3,"name":"Latino"},{"fieldId":4,"name":"Middle Eastern"},{"fieldId":5,"name":"Mixed"},{"fieldId":6,"name":"Native American"},{"fieldId":8,"name":"Other"},{"fieldId":9,"name":"South Asian"},{"fieldId":7,"name":"White"}],
}}
Using this foreach loop, ultimately I want to be able to take the data and use them as Select / List dropdowns on a form.
foreach($json['fields'] as $item){
foreach($item['relationshipStatus'] as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
foreach($item['ethnicity'] as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}
No matter how I try to pull the data out, I keep getting errors similar to:
Notice: Undefined index: relationshipStatus in
/Applications/MAMP/htdocs/updateprofile.php on line 126 Warning:
Invalid argument supplied for foreach() in
/Applications/MAMP/htdocs/updateprofile.php on line 126
What am I doing wrong?
The first foreach selects already relationshipStatus and ethnicity. Maybe the following changes show what I mean:
foreach($json['fields'] as $key=>$item){
if ($key == 'relationshipStatus')
foreach($item as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
else if ($key == 'ethnicity')
foreach($item as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}
Here, you iterating the JSON Object in a wrong way.The array values you want to fetch is actually under $json['fields']['relationshipStatus'].
var name = $json['fields']['relationshipStatus']['name'];
var fieldId = $json['fields']['relationshipStatus']['fieldId'];
=============================== OR ========================================
As described by the A.fink
foreach($json['fields'] as $key=>$item){
if ($key == 'relationshipStatus')
foreach($item as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
else if ($key == 'ethnicity')
foreach($item as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}

Categories