Loop through divs with for loop and sql COUNT - php

CODE :
$result= mysql_query ("SELECT COUNT(post_id) AS postCounter FROM headlines WHERE user_id= '$_SESSION[user_id]' ");
$numrows = mysql_num_rows ($result);
if ($numrows!=0){
while ($row = mysql_fetch_array ($result))
$postCounter = $row['postCounter'];
for ($i=1; $i<=$postCounter; $i++){
echo "$i";
}
}
Now, what I want to know is "How could I use for-loop to echo div's depending on the COUNT result?"
So if $postCounter above was "4" I need to display 4 divs for it .

In your for loop, echo a DIV instead of just echoing the number.
for ($i = 1; $i <= $postCounter; $i++) {
echo "<div>$i</div>";
}

An other way you can do by FOREACH to embed html into php
<ul>
<?php foreach($postcounter as $post) { ?>
<li><?php echo $post; ?></li>
<?php } ?>
</ul>
Hope this help

Related

How to echo result in list using php

I want to print sql result in list using php.
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
while ($row = $q->fetch_assoc()) {
$hh=$row['name'];
}
?>
<ul id="myUL">
<li><?php echo $hh ?></li>
</ul>
like:-
.Mango
.Apple
.Banana
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
echo "<ul id="myUL">";
while ($row = $q->fetch_assoc()) {
echo "<li> <a href='#'>".$row['name']."</a></li>";
}
echo "</ul>";
?>
Generate the HTML in the for loop
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
$hh = ''; //empty string first
while ($row = $q->fetch_assoc())
{
$hh .= '<li>' . $row['name'] . '</li>';
// ^--------------------- concat with the previous result
}
?>
<ul id="myUL">
<?php echo $hh; /* display */ ?>
</ul>
$hh will be the last fetched value because it's being rewritten on every loop cycle. You need to append to that instead. Take a look at this:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$query = "SELECT name FROM tablename";
$query = mysqli_query($con, $query)or die("Failed to fetch data");
$lis = "";
// as long as row is not empty
while ($row = $q->fetch_assoc()) {
$lis .= "<li> <a href='#'>".$row['name']."</a></li>";
}
echo "<ul>$lis</ul>";
?>
The issue is that $hh is always the last row since while($row = $q->fetch_assoc()) over writes the value of the variable with each row.
In order to output a column value in each row, you need to place the output inside of the while loop: it will do it once for each record.
You can use conditional statements for readability:
<!-- Start of List -->
<ul id="myUL">
<?php
$query = "select name from plant ";
$q = mysqli_query($con,$query) or die("Could Not Perform the Query");
while ($row = $q->fetch_assoc()):
?>
<!-- Option -->
<li><?= $row['name']; ?></li>
<?php endwhile; ?>
</ul>
<!-- End of List -->
Like referenced by #Cid in the comments, each element needs to be added inside of the list. Keep your <ul> outside of the loop.
In pseudo code, so you can understand better, it would look like this:
list
foreach row do:
output option
end foreach
end list

Selecting from database error mysqli_query / mysqli_fetch_array

I'm trying to get this information out of the database:
$query = "SELECT * FROM station_control WHERE station_no > 0 ORDER BY station_ord";
it then says it expects parameters in these two lines:
$station_result= mysqli_query($query);
$num= mysqli_fetch_array($station_result);
this is what I want to output, basically to pull every station name from the database called station_ord and the names are under station_name:
$i=0;while ($i < $num) {
$station_name1=mysqli_result($station_result,$i,"station1_name");
$station2_name= mysqli_result($station_result, $i,"station2_name");
$station3_name= mysqli_result($station_result, $i,"station3_name");
$station4_name= mysqli_result($station_result, $i,"station4_name");
$station5_name= mysqli_result($station_result, $i,"station5_name");
echo "<b>
$station1_name $station2_name2</b> <br>
$station3_name<br>
$station1_name4_name<br>
$station5_name<hr> <br>";
$i++;
}
I haven't put in the station_name yet as im confused to where and how I configure that.
Any ideas how to help?
Not sure what you try to do, but try
<?php
$station_result= mysqli_query($query);
$records = mysqli_fetch_array($station_result);
foreach ($records as $record) :?>
<b><?php echo $record['station_name']; ?></b><br/>
<?php endforeach; ?>
ref : http://ch1.php.net/manual/en/mysqli.query.php
and http://www.php.net/manual/en/mysqli-result.fetch-array.php for examples
Something like this should work.
$station_result= mysqli_query($query);
$results= mysqli_fetch_array($station_result);
foreach ($results as $row) {
// echo whatever you want here
echo $row['station_name'];
}

MYSQLI fetch_array not working

I am trying to figure out why my mysqli query is not returning all the rows. For some reason it returns 3 results when there are 4 in the database. It is completely skipping the first record in the database. Here is my query.
$results = "SELECT * FROM `results` LIMIT 10";
$result = $conn->query($results);
if ($result) {
?>
<div id="tableResults">
<div class="row1 bg">Predicted Sex</div>
<div class="row2 bg">Suggested Baby Boy Name</div>
<div class="row3 bg">Suggested Baby Girl Name</div>
<div class="breaker"></div>
<?php
/* fetch object array */
$i = 0;
$count = count($result->fetch_array());
while ($row = $result->fetch_array()) {
?>
<div class="row1 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['sex']; ?></div>
<div class="row2 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['boy_name']; ?></div>
<div class="row3 <?php if (!$i == $count - 1) { echo 'customborder'; } ?>"><?php echo $row['girl_name']; ?></div>
<?php
$i++;
}
}
$conn->close();
?>
As was stated in the comments $count = count($result->fetch_array()); this will not work as expected and makes you lose one row (as it has been fetched). Instead you can use num_rows like the following
$count = $result->num_rows;
while ($row= $result->fetch_array()) {
//...
}
To go into detail, when you read the manual on fetch_array(), you'll find this part
mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both
A result row (in words: one) will be fetched any time this function is called. So currently your code is similar to:
fetch one row -> do nothing with it
while:
fetch one row -> display it

Getting sub categories from mysql for the main category

I am having some problem in retrieving sub categories from mysql database.I want to display the sub-categeories for the parent categories.I am able to get only the last sub category of a main category. The first sub-categories are not displaying **. In my table **i have category_id and category_parent_id.where category_parent_id will be '0' for parent category. .Thanks in advance
<ul class="betterList">
<?php
$con = mysql_connect("localhost","root","pwd") or die('couldnot connect to database'.mysql_error());
mysql_select_db("DB",$con);
$result=mysql_query("select * from table ")or die("No table available with this name"."<br/><br/>".mysql_error());
while($row=mysql_fetch_array($result))
{
$parent_id=$row['category_parent_id'];
$category_id=$row['category_id'];
if($parent_id==0)
{
?>
<li>
<?php echo $row['category_id'].$row['name_en-GB'];
$result1=mysql_query("select * from table where category_parent_id=".$category_id)or die("No data available with this name"."<br/><br/>".mysql_error());
echo $num_row = mysql_num_rows($result1);
if($num_row>0) {
for($i=0;$i<$num_row;$i++)
{
while($row1=mysql_fetch_array($result1))
{
?>
<ul style="margin:0px;padding:0;">
<li><?php echo $row1['name_en-GB']?></li>
</ul>
<?php
}
}
}
?>
</li>
<?php } ?>
<?php }?>
</ul>
when i remove <li> tag which is at the end and keep it after at the end of in while i could display all the sub-catgeories but the css is not applying for that. Some thing is going wrong there but i couldn't figuer it out
Remove below and try again:
for($i=0;$i<$num_row;$i++)
{
Wow ! o_O
You're using old mysql_* functions ...
You wrote :
for($i=0;$i<$num_row;$i++)
And After :
while($row1=mysql_fetch_array($result1))
Both of these instructions are looping on each rows you got with this query.
Remove all of that:
echo $num_row = mysql_num_rows($result1);
if($num_row>0) {
for($i=0;$i<$num_row;$i++) {
Cause this is useless.
The only important thing to loop on your results is
while($row1=mysql_fetch_array($result1))
You can also replace mysql_fetch_array() by mysql_fetch_assoc() that is lighter.
Your code will be optimizable but this should solve your problem.
Instead of doing nested loops, get everything with a join:
SELECT t1.category_id parent, t1.`name_en-GB` parent_name,
t2.category_id child, t2.`name_en-GB` child_name
FROM table t1
JOIN table t2 ON t2.parent_category_id = t1.category_id
WHERE t1.parent_category_id = 0
Then your loop would be:
$last_parent = null;
$first_cat = true;
while ($row = mysql_fetch_assoc($result)) {
if ($row['parent'] != $last_parent) {
$last_parent = $row['parent'];
if (!$first_cat) { // Close out the last UL and LI
echo '</ul></li>';
} else {
$first_cat = false;
}
echo '<li>' . $row['parent'] . $row['parent_name'];
echo '<ul style="margin:0px;padding:0;">';
}
echo '<li>' . $row['child_name'] . </li>
}
if (!$first_cat) {
echo '</ul></li>';
}
You had too many nested loops in your code: you had both a for and while loop that were both trying to loop over the rows of the inner query. Also, you were putting each child into its own <ul>, which is probably not what you wanted.
Just try whether this solutions work for u, if it works adjust your code accordingly
$result = mysql_query("select * from table WHERE category_parent_id = 0 ");
while($row=mysql_fetch_array($result)) {
$parent_id = $row['category_parent_id'];
$query = mysql_query("select * from table where category_parent_id = {$parent_id}");
while($sub_cats=mysql_fetch_array($query)) {
echo '<pre>'.print_r($sub_cats).'</pre>';
}
}
just by adding internal <ul> before while loop i could get subcategories.
<?php
echo "<ul>";
while($row1=mysql_fetch_array($result1))
{
?>
<li><?php echo $row1['name_en-GB']?></li>
<?php
}
echo " </ul>";

New row if a number of cells have been reached

I'm trying to make a table of iframes (2 per row) and I query everything, but whenever it prints, everything is on a row of it's own even though I only tell every second one to. I can't figure out why this is happening:
<div id="main" style="width:1000px;">
<?php
$query = "SELECT * FROM scripts";
mysql_connect("localhost", "root", "");
mysql_select_db("scriptsearch");
$results = mysql_query($query);
$num = mysql_num_rows($results);
mysql_close();
?>
<table border="0">
<?php
for($i = 0; $i <= $num; $i++){
if($i % 2 == 0) //is this the second one? if so, make a new row
echo '<tr>';
else{
?>
<td><iframe src="scriptpreview.php?id=<?php echo $i;?>" style="width: 350px; height: 230px;" frameBorder="0" scrolling="no">Your browser needs to support iFrames for this website.</iframe></td>
<?php }if($i % 2 == 0) echo '</tr>';/*end the row*/ } ?>
</table>
</div>`
Edit: I've tried Krynble's solution, but no matter how I modify it, it still doesn't show up how I expect.
There's an error in your loop.
Try this:
<?php
for($i = 0; $i <= $num; $i++){
if($i % 2 == 0) //is this the second one? if so, make a new row
echo '<tr>';
?>
<td><iframe src="scriptpreview.php?id=<?php echo $i;?>" style="width: 350px; height: 230px;" frameBorder="0" scrolling="no">Your browser needs to support iFrames for this website.</iframe></td>
<?php if($i % 2 == 1) echo '</tr>';/*end the row*/ } ?>
<?php if($i % 2 == 1) //close last row in case we haven't done it yet.
echo '</tr>';?>
You should print the iframe unconditionally, not inside an else. Besides, the closing </tr> should be printed when $i is odd.
Other people have commented on the php/html part, let me focus on the query part:
Don't do this:
$query = "SELECT * FROM scripts"; (1) select all ?
mysql_connect("localhost", "root", ""); (3) don't connect as root!
mysql_select_db("scriptsearch");
$results = mysql_query($query); (4) no check for errors?
$num = mysql_num_rows($results); (2) when you only want 1 count?
Do this instead:
$query = "SELECT count(*) as rowcount FROM scripts";
mysql_connect("localhost", "user1", "password");
mysql_select_db("scriptsearch");
if ($results = mysql_query($query)) {
$row = mysql_fetch_row($results);
$num = $row['rowcount'];
} else { echo "error....." }
You don't have an opening <tr> tag in your table. You need to have a table row before you can put data in it.

Categories