PHP <BR> After 2 loops - php

I wanted to add <br> after every 2 loops.
The loop will run 8 times and after every 2 loops I want to add <br>
Can anyone help?
The loop will look like this:
while($row = mysql_fetch_array( $result2 )) {
}

Notice: this isn't a pretty good syntax. If you want to achive some style with TD rows you could use new css selector: http://reference.sitepoint.com/css/pseudoclass-nthchild
$i=0;
for(;;) {
$i++;
if ($i%2==0)
echo '<br>';
}

$c=0;
while($row = mysql_fetch_array( $result2 )) {
//PUSH YOUR CODE
$c++;
if($c%2==0)
echo "<br/>";
}

Inside your loop:
$i = 0;
while(whatever){
if($i % 2 == 0){
echo '<br/>';
}
$i++;
}

Related

How can I count the result of a for each loop?

I have a text file from where I parse all lines with the label blue:
foreach($colors as $row) {
if (array_key_exists('blue',$row)){
echo "blue:".$row['blue']."<br>";
}
}
My result:
blue:sky
blue:ocean
blue:orchid
Now I want to count my result. Do I have to put the result into an array before counting?
I tried count($colors); but then of course I get the number of all colors in my text file. I also tried count($row['blue']); but then my result is 0.
Either put the result in an array and print out count() or increment a variable:
Solution 1: (storing the values in an array)
$result = array();
foreach($colors as $row) {
if (array_key_exists('blue',$row)){
$result[] = $row['blue'];
}
}
// after your foreach loop
echo "Results: " . count($result);
Solution 2: (incrementing a variable)
$i = 0;
foreach($colors as $row) {
if (array_key_exists('blue',$row)){
$i++;
echo "blue:".$row['blue']."<br>";
}
}
// after your foreach loop
echo "Results: $i";

Implode results into chunks from mysqli_fetch_assoc where perf1_id cannot be in the same chunk

So I'm trying to retrieve information from my database , and usually tells gives me an array to string error which is why I implode it. Before displaying the data however I would like to break it into groups of 3 where the same perf1_id cannot appear in the same chunk more than once. This is the code that I have tried so far:
My Query to get the information
$query2 = " SELECT * FROM trial_am";
$result2 = mysqli_query($connection, $query2);
How I retrieve it and display it:
<ul>
<?php while($array = mysqli_fetch_assoc($result2)){
$one = array_chunk($array, 3, false);
echo "<li>" ;
echo implode(" ", $one) ;
echo"</li>" ;
} ?>
</ul>
I am still a beginner so any help would be appreciated
I would divide my result sets in subsets as follows:
<?php
$counter = 1;
while($array = mysqli_fetch_assoc($result2))
{
$resuilt_partial[] = $array ;
if($counter % 3 == 0)
{//at each 3rd element append in the final array
$result_set[] = $resuilt_partial ;
$resuilt_partial = array();
}
$counter++;
}
foreach($result_set as $result_divided)
{
//$result_divided - contains 3 elements
//add your code here
}
?>
P.S: mysql_ functions are deprecated
<?php while($array = mysqli_fetch_assoc($result2)){
$one = array_chunk($array, 3, false);
echo "<li>" ;
echo implode(" ", array_map('implode', $one));
echo"</li>" ;
} ?>

Handling PHP array of unknown size

I have the following code that should select all the users in the relevant table in my database:
$hof = mysql_query("SELECT * FROM users");
$name = array();
$website = array();
$i=0;
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
}
$i++;
I want to echo out the names and websites of all in the html section of my script (below the php) which will be a Hall of Frame of sorts. How would i do is? The fact that i do not know the size of the array deters me.
Usually, if i knew the size, i would so something like:
<?php echo $name[1];?>
<?php echo $name[2];?>
//and so on
Many thanks in advance. P.S. I plan to move across to MySQLi when i have the functionality of the website sorted first on localhost. Cheers
Your $i++; statement should be inside while loop
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
$i++;
}
Better You do it like this,
$rows = array();
while($result = mysql_fetch_assoc($hof)){
$rows[] = $result;
}
and you echo them like this,
<?php
$len = count($name);
for($i=0;$i<$len;$i++){
echo $name[1];
}
?>
And for the alternative method use this,
<?php
foreach($rows as $row){
echo $row['name']; // use $row['website'] to echo website.
}
?>
foreach($name as $key=>$value){
echo $name[$key];
echo $website[$key];
}
Also there no need to take $i++, you can use following way
while($result = mysql_fetch_array($hof)){
$name[] = $result['company'];
$website[] = $result['website'];
}
See array in manual
First off the $i++ should be inside the loop.
To output them all, you could use implode(), or maybe foreach.
First, take your data into array
$data = array();
$sql = "SELECT * FROM users";
$res = mysql_query($sql) or trigger_error(mysql_error()."[$sql]");
while($row = mysql_fetch_array($res)){
$data[] = $row;
}
then use it anywhere you wish, say, in the template:
<ul>
<? foreach($data as $row): ?>
<li><?=$row['company']?></li>
<? endforeach ?>
</ul>
How about:
foreach ($name as $val)
{
echo $val;
}
you can use mysql_num_rows() to know the number of results returned by your query
$arrarySize = mysql_num_rows($hof);

If a row is not unique - ignore it - php

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">

How to manipulate first 3 entries in array

I am currently working on a project where i am pulling out data using
while($r = mysql_fetch_array($the_data))
i want to make the first, say 3-4 results a different background color and then leave the rest as already styled, i am sure there is some simple option here but i just don't know where to look really...
Hope you can help, thanks !
Are you looking for something like:
#specialResult {background-color: #fff; }
#normalResult {background-color: #000; }
So when you are looping through your while statement, you will want to keep track of what result number you are on:
$i = 0;
while (...)
{
if ($i < 4) echo "<div class='specialResult'>";
else echo "<div class='normalResult'>";
.... rest of your code
$i++;
}
for shorter looking code you could do:
$i = 0;
while (...)
{
?><div class='<?php echo ($i++ < 4 ?"specialResult":"normalResult); ?>'><?php
.... rest of your code
}
<?php
$i = 0;
$r = mysql_fetch_array($the_data);
foreach($r as $row) {
if($i <= 4) {
// Do special styling...
} else {
// Do normal styling.
}
$i++;
}
?>
Or did I misunderstand?
You can also try something like :
$i = 0;
while ( ( $row = mysql_fetch_assoc ( $result ) ) && $i < 4 ) {
/* Your first 4 rows */
echo 'Special : ' . $row['title'];
++$i; // Don't forget to increment
} while ( $row = mysql_fetch_assoc () ) {
/* Normal way */
echo $row['title'] . ' is already outdated';
}
And prefer mysql_fetch_assoc() instead of mysql_fetch_array() ;)

Categories