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

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>';
}

Related

Create a bidimensional array in php

I confess that I am a beginner. My goal is to be able to summarize in a two-dimensional table the amount per month (in column) for each class (in line). After doing a lot of research, I arrived at this stage in my project.
My problem is , I get the result with months repeating in columns like here.
Here is my code.
This is my sql code : "SELECT classe, mois, sum_ec FROM journal"
This is my php code :
<?php
$tableau = array();
$tblClasse = array();
$rt = mysqli_query($db, $req_sit);//execute la requete
while ($row = $rt->fetch_assoc()){ //forme le tableau
$tableau[$row['classe']][$row['mois']] = $row['sum_ec'];
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
}
echo '<table border="1">
<tr>
<th> </th>';
foreach ($tblClasse as $classe) {
echo '<th>' . htmlspecialchars($classe) . '</th>';
}
echo '</tr>';
foreach ($tableau as $mois=>$value) {
echo '<tr>';
$new_line = TRUE;
foreach ($tblClasse as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
$display = isset($value[$classe]) ? $value[$classe] : " ";
echo '<td>' . $display . '</td>';
}
echo '</tr>';
}
?>
Can someone tell me what mistake I made?
The problem is in this part of your code:
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
You are adding months (Fev, Mar) to the array and trying to check if it contains classes (PS, MS etc.) which is impossible, and this condition always returns true, so Feb is added to the $tblClasse array at each iteration. You must either check months or classes and add months or classes to the array respectively. And if you want the array to contain unique values (for example, months), use keys instead of values:
if (!array_key_exists ($row['mois'],$tblClasse)) {
$tblClasse[$row['mois']] = 1;
}
Where 1 can be replaced with any other value.
In the further part of your code use the keys, not values of $tblClasse array to form the table heading.
foreach (array_keys ($tblClasse) as $mois) {
echo '<th>' . htmlspecialchars($mois) . '</th>';
}
Eureka! It worked. I just had to change the line for the values ​​to "array_keys"
foreach (array_keys($tblClasse) as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
as well and boom! It's perfect. Thank you very much my dear. You have given me a lot of happiness.

Select MySQL entry with arrays

I got this code, which creates a table listing all the files of my directory $filedir. I also got a SQL database which lists the names and custom IDs of every file uploaded. For some reason, it only links me to the subpage with the cusom ID on the first file. The other ones link me to my xampp dashboard. I'd appreciate any kind of help/tips.
<?php
$myDirectory = opendir($filedir);
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
$dirArray2 = array_diff($dirArray, array('.', '..'));
array_splice($dirArray2, 1, 0);
closedir($myDirectory);
$indexCount= count($dirArray2);
echo("<TABLE id=myTable class=table-fill>\n");
echo("<thead><TR><th width=100px>---</th><th width=740px>Name</th><th width=160px>Last Modified</th></TR></thead>\n");
$j = 1;
echo "<tbody id=table class=fixed>";
if (count($dirArray2) == 0) {
echo("<TR>");
echo("<td> -- </td>");
echo("<td>No files uploaded yet</td>");
echo("<td> -- </td>");
echo("</TR>\n");
} else {
for ($i = 0; $i < $indexCount; $i++) {
echo("<TR>");
echo("<td><center><b>" . $j++ . "</b></center></td>");
$filename = $dirArray2[$i];
$owner = $user_data['username'];
$result = mysql_query("SELECT `url` FROM `uploads` WHERE `name` = '$filename' AND `owner` = '$owner'") or die(mysql_error());
$row = mysql_fetch_array($result);
echo("<td class=contextMenu>" . $dirArray2[$i] . "</td>");
echo("<td>" . date("m/d/Y h:ia", filemtime($filedir . $dirArray2[$i])) . "</td>");
echo "</tr>";
}
}
echo "</tbody>";
echo("</TABLE>\n");
?>
Note that I am quite new to PHP and SQL, so be kind please :)
I think there is something wrong with your query. Replace the "`" with "'". This sometimes happens if copy and pasting goes wrong. Also you need to put the variables in between the query, not in the string.
Like so:
"SELECT 'url' FROM 'uploads' WHERE 'name' = '".$filename."' AND 'owner' = '".$owner."'"
If that doesn't solve your problem see how many rows your query returns. You can just run it in your database program.
What I also recommend you do is run a 'select * from uploads', then looping the returned array with a foreach loop.
Something like this:
$content = "";
$result = mysql_query("SELECT * FROM 'uploads'");
$row = mysql_fetch_array($result);
$content.= "<table>";
$content.= "<th>Column1</th><th>Column2</th><th>Column3</th>";
foreach($row as $index => $value){
$content.= "<td>$value[$index][1]</td>";
$content.= "<td>$value[$index][2]</td>";
$content.= "<td>$value[$index][3]</td>";
}
$content.= "</table>";
print $content;
This should return a 3 column table with your data in. Not sure though, haven't tested it.

I am trying to loop through a multidimentional array and display info in a contact card, but can't get all the info to show

So I just want to go through the $rows array, display $rows[0] as one contact and $rows[1] as another. For some reason, the information in is not looped, it only shows the second entry (or if there are more than two, whatever the last entry is). The thing I am not understanding is why when I echo the information without a div, it loops through and displays information for both entries. I've tried using both foreach loops and for ($i=0; $i
$rows[0] = array(
'picture' => 'userImage',//$jpeg[$i],
'givenname' => '',//$info[$i]["givenname"][0],
'sn' => '',//$info[$i]["sn"][0],
'mail' => '#.com',//$info[$i]["mail"][0],
);
$rows[1] = array(
'picture' => 'userImage',//$jpeg[$i],
'givenname' => '',//$info[$i]["givenname"][0],
'sn' => '',//$info[$i]["sn"][0],
'mail' => '#.com',//$info[$i]["mail"][0],
);
//User contact card
for ($i=0; $i<count($rows); $i++){
$strCard[$i] = '';
$strCard[$i] .= " <div class='search-card'>" . $rows[$i]['picture'] . "
<p><b>" . $rows[$i]['givenname'] . " " . $rows[$i]['sn']. "</b></p>
<p><a href='mailto:" . $rows[$i]['mail'] . "'>" . $rows[$i]['mail']. "</a></p>
<div class='member-roles'>";
$strCard[$i] .= "<table>";
$strCard[$i] .= "<tr><th>Role</th><th>Centre</th></tr>";
echo $i.'===='.$rows[$i]['picture'].'<br />';
echo $i.'===='.$rows[$i]['givenname'].'<br />';
echo $i.'===='.$rows[$i]['sn'].'<br />';
echo $i.'===='.$rows[$i]['mail'].'<br />';
}
foreach ($strCard as $key => $value) {
return $strCard[$key];
}
}
}
this is because you are probably executing this code inside of a function and using return instead of echo....taken from the php manual:
"If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call...."
http://us3.php.net/return
I think you should use the value of the foreach loop like this
foreach ($strCard as $value) {
return $value
}
Im not sure how is this useful for you, if you want to return the whole string you can try something like this
$string = '';
foreach ($strCard as $value) {
$string.=$value;
}
Not 100% sure, but it seems like maybe you're wanting this
for ($i=0; $i<count($rows); $i++){
$strCard[$i] = '';
$strCard[$i] .= " <div class='search-card'>" . $rows[$i]['picture'] . "
<p><b>" . $rows[$i]['givenname'] . " " . $rows[$i]['sn']. "</b></p>
<p><a href='mailto:" . $rows[$i]['mail'] . "'>" . $rows[$i]['mail']. "</a></p>
<div class='member-roles'>";
$strCard[$i] .= "<table>";
$strCard[$i] .= "<tr><th>Role</th><th>Centre</th></tr>";
}
foreach ($strCard as $cardEntry) {
echo $cardEntry;
}
Or to simplify it
for ($i=0; $i<count($rows); $i++){
$strCard = '';
$strCard .= " <div class='search-card'>" . $rows[$i]['picture'] . "
<p><b>" . $rows[$i]['givenname'] . " " . $rows[$i]['sn']. "</b></p>
<p><a href='mailto:" . $rows[$i]['mail'] . "'>" . $rows[$i]['mail']. "</a></p>
<div class='member-roles'>";
$strCard .= "<table>";
$strCard .= "<tr><th>Role</th><th>Centre</th></tr>";
echo $strCard;
}
$strCard[$i] = ''; needs to be outside the loop to start the variable, otherwise everytime the loop starts, it writes over the contents.

mssql_fetch_array only displays one row if columns are put into variables

I'm still a PHP noob, so I apologize if this is something simple.
I am creating a fairly basic search facility for a website using PHP and mySQL. I have connected to the database, selected the database, queried the table and have fetched the table columns;
$k = htmlspecialchars($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
while ($results = mssql_fetch_array($select)) {
$title = $results['Title'];
$link = $results['Link'];
$description = $results['Description'];
}
}
When I put the $results[''] columns into variables and then try to echo out each variable like so;
if( isset($noResults)) {
echo $noResults;
} else {
echo '<li>' . '<h2>' . '' . $title . '' . '</h2>' . '<p>' . $link . '</p>' . '<p>' . $description . '</p>' . '</li>';
}
it only echo's out one row matching that query however, If I was to just simple echo out the columns like so;
echo $results['Title'];
echo $results['Link'];
echo $results['Description'];
all rows matching the query will be displayed..
I'm not sure why this is happening. If someone could help me out that would be great!
You need to use a loop:
$k = mysql_real_escape_string($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
$results= array();
while ($result = mssql_fetch_array($select)) {
$results[]= $result;
}
}
if( isset($noResults)) {
echo $noResults;
} else {
echo "<ul>";
foreach($results as $result){
echo '<li>' . '<h2>' . '' . $result['title'] . '' . '</h2>' . '<p>' . $result['link'] . '</p>' . '<p>' . $result['description'] . '</p>' . '</li>';
}
echo "</ul>";
}
Do you execute the output in the while-loop?
If you execute the while-loop and call the echo after that, each resultset will overwrite the previous, and the echo will output the last resultset which was fetched.
If you call the echo in the Loop, every result set will generate "his own" output line.
If you want to hold every resultset in a variable you can use an array, which is declared in front of the loop and gets filled in the loop.
a few things are not clear from your question, but i am assuming that you are echo'ing the variables outside the loop since you are checking isset($noResults). that means you are reassigning the variables with new values in each loop of while. so ultimately you get the last one assigned to the variables. you have to either use an array to hold the values or echo it with in the loop.

how to display only 5 records?

What i want to do is read rssfeed, so I already did it, but I display as foreach loop, so how can I only display 5 records ? now I get more than 10 records, but I only need top 5 records, Isn't anyway php, javascript or jquery make it only show 5 records?
here is my code to read the rss file:
function getrssFeed($feed_url) {
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
echo "<ul>";
foreach($x->channel->item as $entry) {
echo "<li><a href = '$entry->link' title='$entry->title'><h3>" . $entry->title . "</h3></a>" . $entry->pubDate . "<br /><br />" . strip_tags($entry->description) . "</li>";
}
echo "</ul>"; }
getrssFeed("http://thestar.com.my.feedsportal.com/c/33048/f/534555/index.rss");
thank you
the easiest way would be to stop your loop after 5 iterations:
$i = 0;
foreach($x->channel->item as $entry) {
// do something
$i++;
if($i==5){
break;
}
}
another (more beautiful) way would be to use a for-loop instead of foreach:
for($i=0; $i<=min(5, count($x->channel->item)); $i++) {
$entry = $x->channel->item[$i];
// do something
}
EDIT :
thanks to Juhana, i changed the code to take that into account.
Try putting a counter in your foreach loop with an if statement to check when the counter is over 5. If the counter is under 5 -> display RSS post, counter++. Else -> Exit loop.
Why not use a simple for loop instead?
for($i = 0, $i <= 5, $i++) {
echo "<li><a href = '$x->channel->item[$i]->link' title='$x->channel->item[$i]->title'><h3>" . $x->channel->item[$i]->title . " </h3></a>" . $x->channel->item[$i]->pubDate . "<br /><br />" . strip_tags$x->channel->item[$i]->description) . "</li>";
}
You can use jQuery feed Plugin.
$('div.feed').Feed({
count:5;
});
<div class="feed" link="http://thestar.com.my.feedsportal.com/c/33048/f/534555/index.rss" ></div>
Feeds would be loaded to container feed.

Categories