Having trouble using foreach to output the contents of a mysql table. The table (tr, td) etc is being printed out for each entry in the mysql table, but there is nothing between the td and /td tags, where each $item should be echoed.
$sql = 'SELECT domain FROM domainsuggestions';
$domains = mysqli_query($link, $sql); // get domain suggestions from table
<table>
<tr>
<td>Domain Suggestions</td>
</tr>
<?php foreach ($domains as $item): ?>
<tr>
<td><?php echo htmlspecialchars($item, ENT_QUOTES, 'UTF-8'); ?></td>
</tr>
<?php endforeach; ?>
</table>
Your logic for working with MySQL is quite off. You need to perform the query first, grab the resource ID of the results, and then loop through the results.
$sql = 'SELECT domain FROM domainsuggestions';
$results= mysqli_query($link, $sql); // get domain suggestions from table
<table>
<tr>
<td>Domain Suggestions</td>
</tr>
<?php while ($item = mysqli_fetch_assoc($results)): ?>
<tr>
<td><?php echo htmlspecialchars($item['domain '], ENT_QUOTES, 'UTF-8'); ?></td>
</tr>
<?php endwhile; ?>
</table>
foreach expects an iterable element, i.e. something that has many entries that it can iterate through. That's typically an array, but can also be an object that implements the Iterable interface.
What you get when running mysqli_query is a resource. That's just a handle on a MySQL result set. The data is not yet in PHP, MySQL just gave you a handle saying "okay, I got the results for you ready, come get them whenever you need to". Calling mysqli_fetch_assoc gets one result row from MySQL. Calling it again gets the next, and the next and so on. This is not a process you can iterate through, you can just keep calling mysqli_fetch_assoc until there are no more results.
That's why foreach does not work.
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 have implemented a table from data tables
Link [https://datatables.net/]
i would like to use two tables in one site with different columns and datas in the columns after the mysqli connection i insert the data sets with a while mysqli fetch array function the first table works properly
"urlaubstage" -> is correct
but table 2
no matter what i do even var_dump i dint not get any reaction but the table is display correctly on the page but with empty columns
This is the html code
<table id="table_id" class="display">
<thead>
<tr>
<th>Urlaubstage Jahr</th>
<th>Urlaubstage Anspruch</th>
<th>Urlaubstage Beansprucht</th>
<th>Urlaubstage Rest</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($sql)){
$urlaubsTage = $row[4];
echo "<tr>";
echo "<td>{$urlaubsTage}</td>";
echo "<td>Anspruch</td>";
echo "<td>Beansprucht</td>";
echo "<td>Rest</td>";
echo "halllo";
}
echo "</tr>";
?>
</tbody>
</table>
!!!!!!!!!!!!<p>HERE STARTS THE SECOND TABLE</p>!!!!!!!!!!!!!!!!!!!!!!!!
<table id="table_id2" class="display">
<thead>
<tr>
<th>Urlaub Antragsdatum</th>
<th>Urlaub Startdatum</th>
<th>Urlaub Enddatum</th>
<th>Urlaubs Status</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($sql)){
var_dump($row); -> EVEn VAR_DUMP IS NOT SHOWN
echo "<tr>";
echo "<td>Antragsdatum</td>";
echo "<td>Startdatum</td>";
echo "<td>Enddatum</td>";
echo "<td>Status</td>";
echo "halllo";
}
echo "</tr>";
?>
</tbody>
</table>
JQUERY CODE
....
$('#table_id').DataTable();
//FUNKTION FÜR ZWEITE TABELLE
$('#table_id2').DataTable();
....
Picture of Code and Table
ok i got the answer by myself, after the first loop runs the query $sql with mysqli_fetch_array($sql) you cant use it anymore on the second loop why? cause it ran on the first loop and its over solution
rename;
$sql = mysqli_query(same query);
$sql2 = mysqli_query(same query);
first loop while($row = mysqli_fetch_array($sql);
second loop while($row = mysqli_fetch_array($sql2);
You don't need to execute the same query twice. You don't need the while loop either. Try to get the results into an array and then loop the array multiple times.
$result = $conn->query($sql)->fetch_all();
//...
foreach ($result as $row) {
//...
}
// Repeat the same loop again without calling query again
//foreach...
as i am a beginner so i want to ask how can i run the multiple queries using PHP for the same row to have multiple data in the table in html. i have tried many attempts but nothing worked i am using MYSQL as backend. I know that i have not written code for the first row and second column i.e. the second <td> on wicket keeper but the thing is that i want all rounder data to come in the second <td> of wicket keeper section. when running this code it is providing the output fine for wicket keeper but for all rounder column the data is starting after the end of wicket keeper data. i know why this problem is occurred but how can i solve this please tell??
CODE HERE:
<?php
$sql="select * from teams where role = 'WicketKeeper'";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
while($row=mysqli_fetch_assoc($result)){
?>
<tr>
<td><?php echo $row["name"] ?></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php } ?>
<?php
$sql="select * from teams where role = 'AllRounder'";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
while($row=mysqli_fetch_assoc($result)){
?>
<tr>
<td></td>
<td><?php echo $row["name"] ?></td>
<td></td>
<td></td>
</tr>
<?php } ?>
Here is a good way to generate the rows of the display you showed.
First, use this query:
SELECT name, role FROM teams ORDER BY role DESC;
It generates rows in the order you want them, wicketkeepers first.
Then, use this php code to generate your display.
<?php
$sql="SELECT name, role FROM teams ORDER BY role DESC";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
while($row=mysqli_fetch_assoc($result)){
$role = $row["role"];
$name = $row["name"];
$wicketkeeper = $role == "WicketKeeper" ? $name : "";
$allrounder = $role == "AllRounder" ? $name : "";
?>
<tr>
<td><?php echo $wicketkeeper ?></td>
<td><?php echo $allrounder ?></td>
<td></td>
<td></td>
</tr>
<?php } ?>
This renders the rows in the result set from your query, placing names in columns according to their roles.
In the general case, this task is known as pivoting a table.
Pro tip 1 Try to avoid SELECT * in queries. Instead give the names of the columns you need. This makes your code easier for a stranger to read, and it may make your queries run faster.
Pro tip 2 Anytime you catch yourself reusing the same query where it only varies by a WHERE clause, try to use a single query. This can make your application run faster.
I really can't figure out what I'm doing wrong here. I'm doing a query to check whether there are records in a DB table called 'newCards'.
With $count I check how many results it's returning: it shows me '1'. But the while loop isn't returning ANY thing. The only things I'm seeing are the <th>'s at the top of the table, but no table records are present, while $count is giving '1' as a result. Which is true, cause there is actually 1 record present in DB.
How can I fix this?
<?php
$query = $db->prepare("SELECT * FROM `newCards` WHERE `company` = :companyID");
$query->bindParam(":companyID", $enterprise['id'], PDO::PARAM_INT);
$query->execute();
$count = $query->rowCount();
echo $count;
if(empty($query->fetch())){
echo "Geen gevonden";
} else {
?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
while($result = $query->fetch()){
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td>2</td>
<td>3</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
$query->fetch() already fetches a record. So next call to fetch() fetches next record or nothing if there're no records. In your case with one record second fetch() fetches nothing, so while never starts.
You can change your code to:
if($count){?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
while($result = $query->fetch()){
// show row
}?>
</table>
} else {
// echo that no rows found
}
I think fetch in first if is executed so that is why second returns empty,
try to assign it to var before conditions or check wit $cont var
I believe you want to return an array indexed by column names with
->fetch(PDO::FETCH_ASSOC)
More information can be found here http://php.net/manual/en/pdostatement.fetch.php
Because fetch() fetches the first row, even when checking in empty(), it will try to fetch the next row when you use while($result = $query->fetch()){. You can either check the value from $count (like shown by u_mulder), but you should beware of the note in the manual for rowCount() (emphasis mine)
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behavior is not guaranteed for all databases and should not be relied on for portable applications.
You can use a do..while structure and check if the fetch was successful or not instead. If you change out if(empty($query->fetch())){ with if (!$row = $query->fetch()) {, you check if there was a row fetched or not (as fetch() returns null on an empty result). Then $row is ready to use, and you can use it before the first loop takes place.
<?php
$query = $db->prepare("SELECT * FROM `newCards` WHERE `company` = :companyID");
$query->bindParam(":companyID", $enterprise['id'], PDO::PARAM_INT);
$query->execute();
$count = $query->rowCount();
echo $count;
if (!$row = $query->fetch()) {
echo "Geen gevonden";
} else {
?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
do {
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td>2</td>
<td>3</td>
</tr>
<?php
} while ($result = $query->fetch());
?>
</table>
<?php
}
PHP.net on PDOStatement::rowCount()
PHP.net on do..while
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!