I cannot seem to get foreach to work. Maybe I do not understand it correctly.
Here is my code:
$statement = "SELECT * FROM categories ORDER BY name ASC";
$query = mysql_query($statement)
...
...
$cals = array("sports","general","other","clubs");
foreach ($cals as $value)
{
/* echo "<h3>".$value."</h3>";
*/ echo "<table width='100%'>";
while ($array = mysql_fetch_array($query))
{
if ($array['calendar'] == $value)
{?>
<tr>
<td><?php echo $array['name']; ?></td>
<td><a onclick="update_form('<?php echo $array['name']; ?>', '<?php echo $array['calendar']; ?>')" href="#">Edit</a></td>
</tr>
<?php }
}
echo "</table><br />Value: $value";
}
The goal of this is to have the foreach change the if statement. I had planned for the if statement to say: if ($array['calendar'] == "sports") the first time, if ($array['calendar'] == "general") the second time, and so on. However, it shows all of the tables (in the source code), but no table rows are created after the first for each array value. For example, I correctly see the sports table, but I do not see any table rows for general, other, or clubs. There are records in that database that should appear in each of those. Could it be a problem with the while and if statements? If I manually set the $value in the if statement to one of the values in the array, it shows the correct records.
What am I missing?
Sample Data:
in the MySQL database -
categories table.
fields:
id
name
num_events
calendar
calendar_url
All of these fields except the calendar field has dummy data in it.
Currently, I have 5 records in there. Each one has a different calendar value. One is sports, one is clubs, and one is general. Depending on what value I place first in the array, it only shows that one table, of all of the values with whatever the first value in the array is.
Here is the source code from the resulting page:
<table width='100%'><tr>
<td>test4</td>
<td><a onclick="update_form('test4', 'sports')" href="#">Edit</a></td>
</tr>
<tr>
<td>test5</td>
<td><a onclick="update_form('test5', 'sports')" href="#">Edit</a></td>
</tr>
</table><br />Value: sports<table width='100%'></table><br />Value: general<table width='100%'></table><br />Value: other<table width='100%'></table><br />Value: clubs
As jcubic and timdev pointed out, there are a couple problems with the code as written. However, the algorithm you're trying to use is very inefficient because it loops over the entire result set for every calendar type. Instead, you can use a multi-column sort in SQL to do it in one pass:
$query = "SELECT * FROM categories ORDER BY calendar, name";
$results = mysql_query($results)
...
...
$last_cal = '';
while ($array = mysql_fetch_assoc($query))
{
if (!$last_cal) {
echo '<table>';
}
else if ($array['calendar'] != $last_cal) {
echo '</table>';
echo '<table>';
}
?>
....HTML for table row...
<?php
$last_cal = $array['calendar'];
}
First, just a point of style. You might consider renaming your variable $query to something like $results. It's holding the result of a query, not a query itself.
The problem is that you're not resetting $results. After the first table, you've iterated all the way through the array. When you get to the end, and there are no more rows to iterate over, mysql_fetch_assoc() returns false.
So try this:
foreach ($cals as $value)
{
while ($array = mysql_fetch_array($query))
{
if ($array['calendar'] == $value)
{
?>
<tr>
<td><?php echo $array['name']; ?></td>
<td><a onclick="update_form('<?php echo $array['name']; ?>', '<?php echo $array['calendar']; ?>')" href="#">Edit</a></td>
</tr>
<?php
}
}
echo "</table><br />Value: $value";
mysql_data_seek($query,0); // <=== Set the resultsets internal pointer back to zero (the first record).
}
The important bit is the mysql_data_seek() on the second to last line.
You could also stick that mysql_data_seek() right before the while() line, if you prefer. You just need to make sure that for each iteration of the foreach loop, the array pointer is reset before you hit while().
EDIT: s/reset/mysql_data_seek/
Try this instead...
$result = mysql_query($query);
while ($array = mysql_fetch_array($result)) {
...
}
mysql_fetch_array return array indexed by integer if you want asoc array change
while ($array = mysql_fetch_array($query))
to this
while ($array = mysql_fetch_assoc($query))
Related
I am trying to display information taken from a mysql database but i do not want to display the 'id' field in the results. i got the displaying part down just fine. just need to remove a field from the view.
$plantarray = array();
if($result = $mysqli->query($hoyaquery)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$plantarray[] = $row;
}
}
}
The code will return a nested array of results but it includes the tables id field.
its then displayed using:
<?php if (count($plantarray) > 0): ?>
<table>
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($plantarray))); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($plantarray as $row): array_map('htmlentities', $row); ?>
<tr>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
ive tried to loop through the outside array and target the key 'id' but it doesnt do anything at all if i unset the id.
foreach($plantarray as $key){
unset($key['id']);
}
this does nothing at all.
i know the problem is in the looping, because if i set an array with the same data and i unset['id'] then it removes the id.
$p = [ "id" => 3, "Family" => "Apocynaceae", "Genus" => "Hoya", "Species" => "curt" ];
unset($p["id"]);
print_r($p);
i could have this completely wrong. I'm not sure. I'm unsure where its going wrong.
The reason that your loop doesn't work is because you aren't unsetting the values in the array itself, rather in the "copy" that is generated during the foreach loop. If you want to use this solution then the right code looks something like this:
foreach($plantarray as &$key){
unset($key['id']);
}
The & symbol will pass the row by reference which will make your manipulations be kept in the original array.
That said, this is not a performant way of doing this. Ostensibly, you have a query somewhere above this code that looks something like
$hoyaquery = "SELECT * FROM plant-table-name";
Instead, just don't get the id column from the database at all.
$hoyaquery = "SELECT Family, Genus, Species FROM plant-table-name"
That will prevent you from needing to loop through all your results in the first place.
I know how to produce results one after another but how do you separate them? So in my sql I'm selecting * from table and limiting it to 4
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{$rows['id']=$row;};
$price = $row['price'];
I dont seem to get any result, any suggestions, sorry guys beginner
...<?php echo $id ?></font></span>
<h4><?php echo $price ?></h4></div>
<div class="planFeatures"><ul>
<li><h1><?php echo $id=2 ?></h1></li>//how do I echo the next id?
<li><?php echo $price2 ?></li> //also the next price which id now is also 2
//and so on......
How do I display the next increments results in a different area of the same page, within another div?
I do get results if I sql and re-select all over again (and say id=2) but I'm sure there is a better way of doing it because I've already got my 4 results with my limit.
It seems you are not saving the results from the query result properly. Each iteration of the loop overwrites the same bucket in the $rows array. Instead, you need to add elements to the $rows array; this will produce an indexed array. Then you can iterate over it and generate the HTML content.
<?php
// Perform query.
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
// Fetch results
while (true) {
$row = $result->fetch_assoc();
if (!$row) {
break;
}
$rows[] = $row;
}
// Generate HTML content using $rows array.
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row):?>
<tr>
<td>ID: <?php print $row['id'];?></td>
<td>Price: <?php print $row['price'];?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
I took some liberty in the above example and generated a simple HTML table. Of course you can modify this to generate whatever you want.
I hope I've interpreted your question accurately, apologies if not!
I got this list of checkboxes that print out from database. I am able to retrieve data from database if user makes multiple checkbox and display it in table, but i cannot retrieved other information from database and display it in the same table.
This is my code:
<table border='1'>
<tr>
<th>TITLE</th>
<th>PERCENTAGE RESULT</th>
</tr>
<?php
if(isset ($_POST["submit1"]))
{
$selectedcheckbox = $_POST["selectedcheck"];
$query = "SELECT * FROM compareresult where subject=$selectedcheckbox";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($data = mysql_fetch_array($sql_query,MYSQL_ASSOC)){
$result=$data['result'];
}
foreach($selectedcheckbox as $title)
{
echo "<tr>";
echo "<td>".$title."</td>";
echo "<td>".$result."</td>";
}
echo "</tr>";
}
?>
I want to display result after user select multiple checkbox, so I wrote:
echo $result in table
so that the result can be displayed in table beside the selected title, but I am getting an error:
Array to string conversion in C:\xampp\htdocs\sam\c.php on line 31 Error 3 :Unknown column 'Array' in 'where clause'
I am not at the moment in the environment to test your problem, and I do this out of my head, but try something like the following.
if(isset($_POST['submit1'])){
$checkbox = isset($_POST['selectedcheck']) ? $_POST['selectedcheck'] : array();
foreach($checkbox as $title){
$query = "SELECT * FROM compareresult where subject='".$title."'";
$result=mysql_query($query); // <-- to avoid SQL injections, please change your method from mysql_query to mysqli_query (use the mysqli functions instead of mysql)
while($data = mysql_fetch_array($result)){
$result=$data['result'];
echo "<tr>";
echo "<td>".$title."</td>";
echo "<td>".$result."</td>";
echo "</tr>
}
}
}
It checks first if your checkboxes are checked and if they are they put it in an array.
Then it runs the foreach statement, where it sets the checkbox value as title. It runs there if the query if it the title is in the database, if so, spit it out through the while loop. Rinse and repeat until done.
edit
I see you put your open tablerow statement in the foreach but close it outside. So either you want it all printed on one line or is it an error? If its on one line, make sure you open the table row BEFORE the while loop and end it AFTER, else it's like how i spit it out.
I have a slight problem here. I have the following code that I create a search query, and im trying to take "$row" array and create a new array called "$item" so I can echo the values inside my div statement. This code works, and I do echo the $item array with the 'follower_username' values, however only the last value gets echoed out. I have values inside my database Nathan, Brett, Nathan2 and it only echoes Nathan2, or the last value of the array $item.
Here is my code:
$result = mysqli_query($con,"SELECT * FROM followers
WHERE username='$username'");
?>
<?php
while ($row = mysqli_fetch_array($result))
{
$item = $row;
}
?>
<body>
<div id="contentwrap">
<div rel="scrollcontent2">
<?php echo $item['follower_username'];?> <img style="width: 50px; height: auto;"<?php echo '<img src="/user_photo/' . $item['follower_username'] . '.jpeg" />';?>
</div>
I hope I can get this resolved, it is bugging me! Thank you for any help!!
What you're doing is reassigning the value of item to the current row each time.
$row will be an object of table row values from the resulting query so if you want all the rows in an $item variable that would need to be an array to store each result, instead of storing the current row in the same variable for each row.
You will then need to iterate that array to display each result.
$i = 0;
$item = array();
while ($row = mysqli_fetch_array($result))
{
$item[$i] = $row;
$i++;
}
<div>
<?php
foreach ($item as $value)
{
echo $value['follower_username'];
}
?>
</div>
Below is an example to show some shorthand versions of the same idea:
$item = array();
while ($row = mysqli_fetch_array($result))
{
$item[] = $row;
}
<div>
<ul>
<?php foreach ($item as $value): ?>
<li><?php echo $value['follower_username']; ?></li>
<?php endforeach; ?>
</ul>
</div>
while ($row = mysqli_fetch_array($result))
What that does is grab the next row in the result set, and assign it to the variable $row. Each time the loop runs, it assigns the latest row to $item. So to store the whole result set, use
$item[] = $row.
I'm sure what you are trying to accomplish with our next line of code. To show all items you need something like
foreach($item as $singleItem)
{
echo $singleItem['follower_username']."<br>";
}
I have a code that I have used over and over again before and now it's messing up. All I want to do is list information from the database into the table on the page, but now it will only show one result, instead of all the results it has found.
<table>
<tr><td style="background-color:#009745; color:#FFFFFF"><center><strong>Address Book</strong></center></td></tr>
<tr>
<?php
$getids = mysql_query("SELECT id, first_name, last_name FROM accounts WHERE s1='$id' ORDER BY id DESC", $db);
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
?>
<td><?= $ab_id ?> - <?= $ab_fn . " " . $ab_ln ?></td>
<?php
} else {
?>
<td><center>No Contacts</center></td>
<?php
}
?>
</tr>
</table>
please help me with this.
Thank You for your help :)
I love this site!! I can always get answers when I need them.
I saw two thing wrong
you are using mysql_fetch_array and later you are using string indexes to print the result
print the things in loop it is overriding values and just storing last row
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_assoc($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
echo '<td>'.$ab_id.' -'. $ab_fn.''.$ab_ln.' </td>';
}
In this messy code you're closing the while loop too early:
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
Only the last retrieved row is used later on. Also, don't use mysql_fetch_array if you're not accessing the numeric indeces of your result. Use mysql_fetch_assoc instead.