for example I have this while loop and gives 4 values:
while($get = mysql_fetch_assoc($result)) {
echo $get['anything'];
echo '<div class="seperatorrrr"></div>';
}
Question: I dont't want class separator to be shown after the last $get['anything'] value. How can I do it ?
$iii=1;
while($get = mysql_fetch_assoc($result)) {
if ($iii!=1) {
echo '<div class="seperatorrrr"></div>';
}
echo $get['anything'];
$iii=$iii+1;
}
Related
I'm trying to identify whether I am looking at the first column in the array.
I haven't tried anything, but googled plenty and cannot find a solution.
while($row = mysqli_fetch_row($sql)) {
echo '<tr>';
foreach ($row as $col) {
if () //NEED CODE HERE
echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
}
echo '</tr>';
}
mysqli_fetch_row fetches "one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero)." So the key of the column is the same as column order.
So you can do this:
while($row = mysqli_fetch_row($sql)) {
echo '<tr>';
foreach ($row as $key => $col) {
if ($key === 0) {
echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
}
}
echo '</tr>';
}
But column is subjected to changes in database structure and SQL query changes. I would personally prefer mysqli_fetch_assoc or mysqli_fetch_object so I can use the column by name instead of order number. Its less error prone. For example,
while($row = mysqli_fetch_assoc($sql)) {
echo '<tr>';
foreach ($row as $key => $col) {
if ($key === 'ip_address') {
echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
}
}
echo '</tr>';
}
Note: $sql here should be a mysqli_query result instead of the actual SQL string.
I'm pulling data from mssql database into an array called
$results2
I need to echo out each 'Item' only one time, so this example should only echo out:
"52PTC84C25" and "0118SGUANN-R"
I can do this easily with:
$uniqueItems = array_unique(array_map(function ($i) { return $i['ITEM']; }, $results2));
The issue is when i try to echo out the other items associated with those values. I'm not sure how to even begin on echoing this data. I've tried:
foreach($uniquePids as $items)
{
echo $items."<br />";
foreach($results2 as $row)
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
}
}
This returns close to what I need, but not exactly:
This is what I need:
Assuming your resultset is ordered by ITEM...
$item = null; // set non-matching default value
foreach ($results2 as $row) {
if($row['ITEM'] != $item) {
echo "{$row['ITEM']}<br>"; // only echo first occurrence
}
echo "{$row['STK_ROOM']}-{$row['BIN']}<br>";
$item = $row['ITEM']; // update temp variable
}
The if condition in the code will check if the ITEM has already been printed or not.
$ary = array();
foreach($results2 as $row)
{
if(!in_array($row['ITEM'], $ary))
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
$ary[] = $row['ITEM'];
}
}
I have a foreach loop that runs perfectly without flaw.
foreach ($row AS $row) {
echo $row['id'];
}
There are times that there are no rows returned. I want to echo out 'there are no rows'; when there are no rows. The problem is if I try to do something like as follows:
foreach ($row AS $row) {
if (!isset($row['id'])) {
echo 'there are no rows';
} else {
echo $row['id'];
}
}
It never returns the echo "there are no rows". I assume this is because when there are no rows, the foreach loop doesn't run. The question becomes, how do I echo "there are no rows" if and only if there are no rows while not interfering with the foreach when there are rows.
I have also tried code such as:
$row1 = $stmt->fetch();
$row = $stmt->fetchAll();
if (isset($row1['id'])) {
foreach ($row AS $row) {
Still no luck
So the desired outcome would be something as follows:
When loop runs:
1
2
3
4
When loop doesn't run:
there are no rows
you should check before the loop like so
if(count($row)>0){
//foreach ...
}else{
echo 'no data';
}
Test if the array is empty:
if (empty($row)) {
echo "there are no rows";
} else {
foreach($row as $row) {
...
}
}
Issue:
I've continuously looked over my code and cannot find why the array is duplicating the data. A single entry into the database has a correct output, however if there is more than one it will duplicate those before it as well as the next one.
My Code:
global $connection;
//Query database & retrieve results.
$search = $connection->query('SELECT * FROM users WHERE country= "'.$country.'"');
echo '<table><tr><th>Username</th><th>Email</th><th>Country</th></tr>';
while ($result = $search->fetch_assoc())
{
$total[] = $result;
foreach ($total as $rows)
{
echo '<tr>';
echo '<td>'.stripslashes($rows['username']).'</td>';
echo '<td>'.stripslashes($rows['email']).'</td>';
echo '<td>'.stripslashes($rows['country']).'</td>';
echo '</tr>';
}
}
echo '</table>';
Output:
This will return the following form -
Username Email Country
exampleUser1 exampleEmail1#example.com United States
exampleUser1 exampleEmail1#example.com United States
exampleUser2 exampleEmail2#example.com United States
You can see the first line is repeated then the new entry is there, it will continue on from this the more it goes on.
Additional Info:
This is placed inside of a function and is executed when $_POST['country'] is submitted - $country is just $_POST['country'] with a real_escape_string.
$connection is just a new mysqli(localhost, user, pass, database) referenced in the script - it is globalised because this is wrapped inside a function.
Any help would be appreciated.
<?php
//... Your code
while ($rows = $search->fetch_assoc()) {
$rows = array_map('stripslashes', $rows);
echo '<tr>';
echo '<td>'.$rows['username'].'</td>';
echo '<td>'.$rows['email'].'</td>';
echo '<td>'.$rows['country'].'</td>';
echo '</tr>';
}
//... Your code
if you need to save and return from function this rows just create array $total and add $total[] = $rows; after echo '</tr>';
As mentioned in my comment, put the foreach outside your while loop like this:
echo '<table><tr><th>Username</th><th>Email</th><th>Country</th></tr>';
while ($result = $search->fetch_assoc()) {
$total[] = $result;
}
foreach ($total as $rows) {
echo '<tr>';
echo '<td>'.stripslashes($rows['username']).'</td>';
echo '<td>'.stripslashes($rows['email']).'</td>';
echo '<td>'.stripslashes($rows['country']).'</td>';
echo '</tr>';
}
echo '</table>';
Another solution is to just redeclare your $total all the time.. Just keep your code then and do:
$total = $result;
I'm working on the following code:
function form_Subcat_Picker() {
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (!$mysqli) {
die('There was a problem connecting to the database.');
}
$catPicker = "SELECT Subcatid, Subcatname, Parentid
FROM ProductSubCats
ORDER BY Subcatid";
if ($Result = $mysqli->query($catPicker)){
if (!$Result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while ($row = $Result->fetch_assoc()) {
echo '<div class="parentid'.$row['Parentid'].'">';
echo '<select name="Subcatid">';
echo '<option value="'.$row["Subcatid"].'">'.$row["Subcatname"]."</option>";
echo '</select>';
echo '</div>';
}
}
$mysqli->close();
}
What I want to do, is in the line:
while ($row = $Result->fetch_assoc()) {
echo '<div class="parentid'.$row['Parentid'].'">';
If the $row['Parentid'] part is the same as the previous iteration, I want to ignore that particular line (adding the div class)
So that if for example in the first run $row['Parentid'] is 1, and in the next loop it is 1 again, I want to not create a new div, just echo everything else and thus keep it in the same div.
Is this possible? Alternatively, how could I make multiple sub category id's and names appear in the one div, if they share a common parentid (there are multiple parent ids)
For the line:
echo '<option value="'.$row["Subcatid"].'">'.$row["Subcatname"]."</option>";
Maybe this would work:
$last_id = 0;
while ($row = $Result->fetch_assoc()) {
if ($last_id != $row['Parentid']) {
echo '<div class="parentid'.$row['Parentid'].'">';
echo '<select name="Subcatid">';
echo '<option value="'.$row["Subcatid"].'">'.$row["Subcatname"]."</option>";
echo '</select>';
echo '</div>';
$last_id = $row['Parentid'];
}
}
However, I think the best solution is to filter them out in the SQL statement, maybe the GROUP BY clause, but I'm not 100% sure how to do it :).
Regards,
That is just something basic for looping. Let's see your current loop:
while ($row = $Result->fetch_assoc()) {
...
}
As you want to skip with a specific condition, let's just introduce this skipping (not taking much care about the condition first):
while ($row = $Result->fetch_assoc()) {
if ($condition) continue;
...
}
Now let's formulate the condition. As we want to look into the last $row we need to keep a copy:
$last = null;
while ($row = $Result->fetch_assoc()) {
if ($condition) continue;
...
$last = $row;
}
Now we've got the data we need to have to create the condition, $last can contain the last row (if there was one) and therefore the comparison can be done:
$last = null;
while ($row = $Result->fetch_assoc()) {
$condition = $last && $row['Parentid'] === $last['Parentid'];
if ($condition) continue;
...
$last = $row;
}
And that is it basically. Depending on the logic, you might want to switch to a for loop:
for ($last = null; $row = $Result->fetch_assoc(); $last = $row) {
$condition = $last && $row['Parentid'] === $last['Parentid'];
if ($condition) continue;
...
}
This for example does ensure that for each iteration (even the skipped ones), the $last is set to the $row at the end of the loop.
Instead of continue you can naturally do different things, like not outputting the <div> or similar.
Hope this helps.
This is the way I'd write it.
// add a variable to hold the previous value
$previous_parent_id = "";
while ($row = $Result->fetch_assoc()) {
// then add an if statement to see if it's the previous statement
if ($row['parent_id'] != $previous_parent_id){
echo '<div class="parent_id'.$row['parent_id'].'">';
$previous_parent_id = $row['parent_id'];
}
}
So going in a loop on these records
ID ParentID
1 0
2 0
3 1
4 1
4 2
4 2
the output would be:
<div class="parent_id0">
<div class="parent_id1">
<div class="parent_id2">