Creating 'Browse user' page - php

I have a table for users already created so for example I will run a query which will SELECT * FROM users WHERE accType='1' and I am looking to run a foreach loop on the results and put each result into this element
<div class="title-desc-wrap col-xs-12 col-md-8">
<div class="title-wrap "><h4>User Name</h4></div>
<div class="excerpt-wrap">PROFILE PICTURE</div>
</div>
I want to restrict the page to only show 8 users on each page. How would I go about structuring this foreach loop in PHP?

Not too sure on foreach but for a for loop, if you are placing the results into an array, you could;
<?php
for($count = 0; $count < 8; $count++) {
$holder = $array_name['$count'];
echo "<a href=LINK TO USERS PROFILE>". $holder['userName'] ."</a>";
echo "<div class=excerpt-wrap>". $holder['ProfilePic'] ."</div>";
}
then for the next page;
<?php
for($count = 8; $count < 16; $count++) {
$holder = $array_name['$count'];
echo "<a href=LINK TO USERS PROFILE>". $holder['userName'] ."</a>";
echo "<div class=excerpt-wrap>". $holder['ProfilePic'] ."</div>";
}
and so on, bit basic but it should work.

Related

Get two results while looping trough associative array in PHP

I want to get two results at a time when using while looping trough a associative array in PHP.
I need to echo two results per row, something like this:
<?
while($row = mysqli_fetch_assoc($result)) {
$client_name = $row['client_name'];
$review = $row['review'];
echo('
<div class="row">
<div>
<p>'.$client_name.'</p>
<p >'.$review.'</p>
</div>
<div>
<p>'.$client_name.'</p>
<p >'.$review.'</p>
</div>
</div>
');
}
}
?>
Right now it's giving me the same result twice rather than the next one.
You can use a counter to control the output of the outside div so that you get two inside div output for each outside one:
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$client_name = $row['client_name'];
$review = $row['review'];
if ($i % 2 == 0) echo '<div class="row">';
echo '<div><p>'.$client_name.'</p><p>'.$review.'</p></div>';
if ($i % 2 == 1) echo '</div>';
$i++;
}

Divide MySQL data into four equal bootstrap row order by alphabet

I have a table of category, I want to show category data into 4 equal bootstraps 4 rows dynamically, and data must be shown in alphabetically order.
First I am counting the number of data and dividing by 4 then run 4 queries to find the first 25 data and in the second query next 25 data and so on, but looking for a better solution.
$catCount = Category::all()->count();
$inOneRow = intval( $catCount / 4);
What I want
Assuming Category is a table of category names - you can select ALL categories at once and use the ORDER BY clause on the query:
$query = 'SELECT name FROM db.categories ORDER BY name ASC;';
You can alternatively use sort on the result-set:
$query = 'SELECT name FROM db.categories;';
/* execute query here... */
sort($resultSet);
Let's assume you did this, the styling would be easy using bootstrap grid (notice mock result-set in fiddles):
<?php
const NUM_COLS = 4;
$numResults = count($dummyResult);
$numPerCol = round($numResults / NUM_COLS);
?>
<div class="container">
<div class="row">
<?php
for($i = 0, $col = 0; $col < NUM_COLS; $col++){
echo '<div class="col">';
for($colLimit = min($numResults, $i + $numPerCol); $i < $colLimit; $i++){
echo '<div class="row">'.$dummyResult[$i]['category'].'</div>';
}
echo '</div>';
}
?>
</div>
</div>
Here is a fiddle
Easier to understand, albeit probably slower example:
<?php
const NUM_COLS = 4;
$numResults = count($dummyResult);
$numPerCol = round($numResults / NUM_COLS);
?>
<div class="container">
<div class="row">
<?php
for($i = 0; $i < NUM_COLS; $i++){
echo '<div class="col">';
foreach( array_splice($dummyResult, 0, $numPerCol) as $row ){
echo '<div class="col">'.$row['category'].'</div>';
}
echo '</div>';
}
?>
</div>
</div>
Here is a fiddle
Note: Container will be 100% width of it's parent, unless styled otherwise.
Column widths will be equal by default. See Bootstrap Grid.

Adding 4 item per row in PHP

I have some HTML in a variable that I'd like to loop 4 time per row. I am making a couple of queries first. In one I get the number of rows and store it in a variable. The second, I am looking to fetch the associated data that I will need to display.
$results = $dbCon->query("SELECT * FROM table WHERE status = '1' ORDER BY id DESC LIMIT $start, $limit");
$total = mysqli_num_rows($results);
$res = $dbCon->query($results);
$data = $res->fetch_assoc();
$link = $data['link'];
$title = $data['title'];
$image = $data['image'];
$imgAlt = $data['imgAlt'];
Third, I store what I want to display in a variable. The HTML I plan on displaying looks something like this
$html = printf("<div style=\"text-align:center; max-width:270px; white-space:normal; word-wrap:break-word; border-left:1em solid transparent; border-right:1em solid transparent; text-overflow: ellipsis; float:left;\">
<a href=\"%s\">
<img style=\"width:270px; height:232px; margin-bottom:40px; border-radius:45px; -moz-border-radius:45px; -webkit-border-radius:45px; box-shadow:0px 0px 3px #fff; -moz-box-shadow:0px 0px 3px #fff; -webkit-box-shadow:0px 0px 3px #fff;\" src=\"images/recentshoots/%s\" alt=\"%s\" />
<p>%s</p> <br /></a>
</div>", $link, $image, $imgAlt, $title);
Next, I would like to loop the 20 items per page in 4 items per row. This is where I am having some trouble. My issue is that the number of characters in the $title are always different so the layout breaks apart. At first a tried a simple way using css and php to do a str_pad() but it doesn't seem to work right with empty spaces. I always get some containers that are taller than others which distorts my row. So I did some research in this platform to model after someone else example.
I m having some trouble with what I found because the examples I've seen have information missing that I need to understand how to modify my own. I have seen it done with foreach and while loops. Can someone help me find a way to understand this better?
How can I loop the data retrieved and make sure that only 4 per row exist in a page of 20 items? Thank you so much for your help. I started with something like this
$startingPoint = 1;
echo "<div class=\"row\">";
foreach($startingPoint < 4){ //this foreach is not even starting the right way, how can I fix this?
echo $html;
}
Can I use a foreach? or a while loop? or do-while?
which one is the best solution and the fastest or most efficient way to go? The shorter the code the better.
Foreach loops are used for array datatypes whilst a while loop can be used for booleans and more.
What you're looking for is a for loop, this allows your to set a counter and each time the loop is ran it adds to a counter. Once the expression is met, it ends the loop.
for($i = 1; $i == 4; $i++)
{
echo 'Loop ' . $i . ': This will loop 4 times';
}
However, you could fix your foreach by using this snippet:
$startingPoint = [1,2,3,4];
foreach($startingPoint as $start)
{
echo $html;
}
Since there are 4 items inside the array, the loop will continue 4 times.
Your SQL is returning more than one row of data thus creating $data to become multidimensional, your loop therefore may not work how its written, you could try this:
for($i = 1; $i >= $limit; $i++)
{
print_f(<!-- html here -->, $data[$i]['column']);
}
You can try this code. Full pagination and view:
Example: index.php
<?php
//get page id for pagination and limit query
$limit = 4;
if(isset($_GET["page"]))
$page = intval($_GET["page"]);
else
$page = 1;
$total = $limit * $page;
$start = $total - $limit;
//GEt data from database. I have used mysqli for testing purpose.
$conn=mysqli_connect("localhost","root","","dbname");
$result = mysqli_query($conn, "SELECT * FROM table WHERE status = '1' ORDER BY id DESC LIMIT $start, $limit");
$total = mysqli_num_rows($result);
?>
<!--Your html code what you want-->
<table>
<tr>
<th>Title</th>
<th>Image</th>
<th>Link</th>
</tr>
<!--loop inside html-->
<?php while($data = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $data['title']; ?></td>
<td><img src="<?php echo $data['image']; ?>" alt="<?php echo $data['imgAlt']; ?>"> </td>
<td>Link</td>
</tr>
<?php } ?>
</table>
<?php
/**======== Pagination Url generate=============*/
$totalPages = ceil($total/$limit);
if($page <=1 ){
" <span style='font-weight: bold;'> < Prev </span> ";
}else{
$j = $page - 1;
echo " <a href='index.php?page=$j'>Prev</a> ";
}
for($i=1; $i <= $totalPages; $i++){
if($i<>$page){
echo " <a href='index.php?page=$i'>$i</a> ";
}else{
echo " <span style='font-weight: bold;'>$i</span> ";
}
}
if($page == $totalPages ){
echo " <span style='font-weight: bold;'>Next ></span> ";
}else{
$j = $page + 1;
echo " <a href='index.php?page=$j'>Next</a></span> ";
}
?>

PHP mysql jquery pagination modification

I have a problem with my pagination, I need your help please.
I have 53 records but with this pagination, I can get 50 records only, I can't see the 3 others
I want to change this code to get all records please, and if I want to make the pagination easy to navigate for big records. Like this (for exp):
<< 1 2 3 4 5 ...... 184 185 >>
Thanks
<?php
include("db.php"); //include config file
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($db,"SELECT id,name,message FROM paginate ORDER BY id ASC LIMIT $position, $item_per_page");
//output results from database
while($row = mysqli_fetch_array($results))
{
echo' <ul class="page_result">
<li class="page_result_img"><img src="images/pic1.jpg" class="img-responsive" alt=""/></li>
<li class="page_result_desc" id="item_'.$row["id"].'">
<h3>'.$row["id"].'.'.$row["name"].'</h3>
<p>'.$row["message"].'</p>
</li>
<p class="no">'.$row["id"].'<br><span>projet</span></p>
<div class="clearfix"> </div>
</ul>';
}
?>
projet.php
<?php
include("db.php");
$results = mysqli_query($db,"SELECT COUNT(*) FROM paginate");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?>
.
.
.
.
<div class="approach" id="app">
<div class="container">
<div class="gallery-head text-center">
<h3>Nos projets</h3>
<p>Trouvez ici tout les projets</p>
<span> </span>
</div>
<ul id="results"></div>
<?php echo $pagination; ?>
</div>
</div>
For correct LIMIT in SQL query must be value of $page_number for the first page equal to 0. But your pagination starts from 1. Then you never get $position = 0 and SQL query skips first $item_per_page records.
Try modify $position calculation:
$position = (($page_number - 1) * $item_per_page);
Second problem is in projet.php. For 53 records (and $item_per_page = 10) is value of $pages = 6. But for cycle stops on 5. It should be:
for($i = 1; $i <= $pages; $i++)
I like to work this way .. So try this code hope it help
$results = mysqli_query($db,"SELECT * FROM paginate");
$get_total_rows = mysqli_num_rows($results); //total records
$item_per_page = 10;
//break total records into pages
$pages = ceil($get_total_rows/$item_per_page);
//create pagination
if($pages > 1)
{
?>
<ul class="paginate">
<?php
for($i = 1; $i<$pages; $i++)
{
if($pages <= 5){
?>
<li><?php echo $i; ?></li>
<?php
}elseif($pages >= $pages - 5){
?>
<li><?php echo $i; ?></li>
<?php
}
}
?>
</ul>
<?php
}

Loop through divs with for loop and sql COUNT

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

Categories