How to Show row number for every row fetched from mysql - php

I want to show row number for every row fetched from database. can someone help me to do this.
My Code to fetch rows is:
$query="
select id
, title
, description
, url,votes
from posts
order
by votes desc
";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = $row;
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
My code displays post, title, post votes and post controls (Vote up or Down).
I want to show row number for every row fetched.
My Code to Display posts is:
<ul class="thumbnails" ng-controller="votingCtrl">
<li ng-repeat="post in posts" class="clearfix">
<div class="col-md-1 voting well">
<div class="votingButton" ng-click="upVote(post);">
<i class="glyphicon glyphicon-chevron-up"></i>
</div>
<div class="badge badge-inverse">
<div>{{post.votes}}</div>
</div>
<div class="votingButton" ng-click="downVote(post);">
<i class="glyphicon glyphicon-chevron-down"></i>
</div>
</div>
<div class="well col-md-11">
<h4>{{post.title}}</h4>
<p>{{post.description}}</p>
</div>
</li>
</ul>
Thanks

try to use ROW_NUMBER() mysql function
select id,title,description,url,votes, ROW_NUMBER() OVER (ORDER BY votes DESC) as row_num from posts order by votes desc

With the current logic, row number can be displayed using {{post.id}} as the SELECT query fetches id along with votes as fields.
In the loop itself, we can display a custom counter like:
$arr = array();
$cntr = 0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
++$cntr;
$row['cntr'] = $cntr;
$arr[] = $row;
}
}
And in view template, you can use {{post.cntr}}.

SELECT
(#row_number:=#row_number + 1) AS num,
id,
title
FROM
Test,
(SELECT #row_number:=0) AS t
LIMIT 5;
Please try above its tested it will work, only need to replace your query with that.

Related

Need Help adding Pagination on divs Thank you

hello is there a way to create pages of loaded divs from sql?
Id like to limit it to 6 per page
I used:
$result = mysqli_query($conn,"SELECT * FROM products ORDER BY ID DESC LIMIT 6"); to limit and I want to display the other ones in next pages.
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
$result = mysqli_query($conn,"SELECT * FROM products where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
else
{
$result = mysqli_query($conn,"SELECT * FROM products ORDER BY ID DESC LIMIT 6");
}
if($result){
while($row=mysqli_fetch_array($result)){
$prodID = $row["ID"];
echo '<ul class="col-sm-4">';
echo '<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<img src="reservation/img/products/'.$row['imgUrl'].'" alt="'.$row['Product'].'" title="'.$row['Product'].'" width="150" height="150" />
</a>
<h2>'.$row['Product'].'</h2>
<h2>₽ '.$row['Price'].'</h2>
<p>Stock: '.$row['Stock'].'</p>
<p>Category: '.$row['Category'].'</p>
<i class="fa fa-search"></i>View Details
</div>';
echo '</ul>';
}
}
?>
Thank you.
Use the LIMIT clause with an offset. For example:
SELECT ... LIMIT 0, 6 -- select the six rows starting at row 0
then
SELECT ... LIMIT 6, 6 -- select the six rows starting at row 6
SELECT ... LIMIT 12, 6 -- select the six rows starting at row 12
...
See the MySQL Manual for more details

Another SQL query in a loop (row) query

I am struggling with my code. I try to make a News Feed.
The news feed is working well but now I want to add a avatar picture on each news row to have a picture from the author. The avatar picture path is in a different table (users).
That means I need to get in the loop the specific user ID ($row['uid']) and with that uid I need to get the related path from the user's avatar in the user table.
If I try to use a query in my loop it shows me only one result instead of 6 as specified in my query.
Do you have any suggestion or advise how I can solve that issue?
Many thanks for your support!
This is my attempt for the moment:
<div class="timeline p-4 block mb-4">
<?php
// Getting the user id and the feedmessage from Table "activity_feed"
$statement = $pdo->prepare("SELECT feed_message, uid FROM activity_feed WHERE cid = :cid ORDER BY id DESC LIMIT 6");
$result = $statement->execute(array('cid' => $cid));
$count = 1;
while($row = $statement->fetch())
{
// Starting the News feed Loop
?>
<?php
// This will repeat now X times as defined in the query above by = LIMIT ?
// Getting the avatar path from the user table
$statement = $pdo->prepare("SELECT avatar FROM users WHERE id = :id");
$result = $statement->execute(array('id' => $row['uid']));
$user_avatar = $statement->fetch();
?>
<style>
#circle_feed {
height:50px;
width:50px;
border-radius:50%;
/* Including the avatar path from query above*/
background-image: url("<?php echo $user_avatar['avatar']; ?>");
background-position:center;
background-size:cover;
}
</style>
<div class="tl-item ">
<div class="tl-dot"><a class="tl-author" href="#" data-abc="true">
<!-- Including the Avatar circle here-->
<span class="w-40 avatar circle gd-warning border" id="circle_feed"></span></a>
</div>
<div class="tl-content">
<div class=""><?php echo $row['feed_message']; ?></div>
<div class="tl-date text-muted mt-1">DATE</div>
</div>
</div>
<?php
// News Feed Loop is ending here
}
?>
</div>
</div>
There is no need to loop. SQL is a set-based language that can give your the results that you want in a single query, using the join syntax:
SELECT
af.feed_message,
af.uid,
u.avatar
FROM activity_feed af
INNER JOIN users u ON u.id = af.uid
WHERE af.cid = :cid
ORDER BY af.id DESC
LIMIT 6
This is much more efficient than running 7 queries (one for the activity feed, then one for each row returned by the first query, in a PHP loop).
You can then fetch the rows of the resultset and use this directly in your application.

Search data from database

I want to display data from database. I created a search form but there is an error to display the result. Attached screenshot of the error.
In the database, consist of staff name and branch. The branch dropdown list, I get it from the database. Example of branch is Faculty Computer Science and Mathematics.
I think the error is in the model.
Can someone help me to fix my code
CONTROLLER
function filter_directory()
{
$search_term = $this->input->post('search_term');
$search_branch = $this->input->post('search_branch');
$data['search_term'] = $search_term;
$data['search_branch'] = $search_branch;
$data['branch_name'] = $this->direktori_model->get_branch_list();
$data['search_term'] = $this->input->get('search_term');
$data['search_branch'] =$this->input->get('search_branch');
$data['results'] = $this->direktori_model->get_directory_results($data['search_term'], $data['search_branch'], $config['per_page'], $page);
$this->load->view('directory/directory_list', $data);
}
MODEL
function get_directory_results($search_term, $search_branch, $limit=10, $offset=0)
{
$sql = "SELECT * FROM Staff_Profile
WHERE Name LIKE '%$search_term%'
AND Branch = {$search_branch}
AND Enabled = 'Y'
AND Lang ='BM'
ORDER BY ID ASC
OFFSET {$offset} ROWS
FETCH NEXT {$limit} ROWS ONlY";
$query = $this->db->query($sql);
return $query->result();
}
VIEW
<?php echo validation_errors();?>
<?php echo form_open("direktori/filter_directory", array('method' => 'get'));?>
<div class="row collapse">
<div class="medium-4 columns ">
<?php echo form_input(array('name' => 'search_term', 'id' => 'search-box', 'value' => $search_term)); ?>
</div>
<div class="medium-4 columns ">
<?php echo form_dropdown("search_branch", $branch_name, "", 'id="branch_id"');?>
</div>
<div class="medium-4 columns ">
<?php echo form_submit('search', 'SEARCH', 'class="button expand"'); ?>
</div>
</div>
<?php echo form_close(); ?>
In your query you must add quote after BRANCH
Your query:
SELECT * FROM staff_profile
where name Like '%anuar%'
and branch = BAHAGIAN KEWAIGAN & PENGURUSAN <-- ERROR
and enabled = 'Y' and lang = 'BM'
order by id asc offset o rows fetch next 10 rows only
Fixed query:
SELECT * FROM staff_profile
where name Like '%anuar%'
and branch = 'BAHAGIAN KEWAIGAN & PENGURUSAN'
and enabled = 'Y' and lang = 'BM'
order by id asc offset o rows fetch next 10 rows only
Error come in near branch. please put branch inside quotes.
$sql = "SELECT * FROM Staff_Profile
WHERE Name LIKE '%$search_term%'
AND Branch = '$search_branch'
AND Enabled = 'Y'
AND Lang ='BM'
ORDER BY ID ASC
OFFSET {$offset} ROWS
FETCH NEXT {$limit} ROWS ONlY";
use codeigniter syntax in the model
function get_directory_results($search_term, $search_branch, $limit=10, $offset=0){
$this->db->order_by('ID','ASC');
$this->db->like('Name',$search_term);
$this->db->where('Lang','BM');
$this->db->where('Enabled','Y');
$this->db->where('Branch',$search_term);
$query=$this->db->get('Staff_Profile',$limit,$offset);
return $query->result();
}
in this format you could port to any other BD and show you more easy the troubles that you have.

Adding arrays together if duplicate values are found?

Okay so I just had a massive long discussion on here trying to get this code to work as it should... I am trying to display a "status" system on my site. So users can post on other users profiles and then comment on these statuses. Finally, we managed to get the 3 databases combined. I will explain the code first, and show the errors below...
Users
Statuses
Comments
Users contains the standard...
userid
username
first_name
last_name
photo
Statuses contains any information about a main status posted from each user, these statuses are displayed on the users profiles. So user 1 could post a status on user2's profile. Here is the statuses table design...
status_id (auto-i)
user_id (The users ID whos profile the post was added too)
sender_id (The user who sent the post or wrote it)
date (Date/Time was sent)
rate (This doesn't matter for a moment)
comments (This will count all the comments and display the number)
status (The actual status written out)
These tables worked fine added together in my script which connected both tables and displayed the users information (the one who posted the status) such as their profile photo and name etc... Here is my current script which has no issues at all, this combines the third table now (comments)...
//// GET STATUSES
$user_id = $profile_data['userid'];
$data = mysql_query("
SELECT -- added alias to your tables so its easier to read
s.status_id,
s.user_id,
s.sender_id,
s.status,
s.date,
u.first_name,
u.last_name,
u.photo,
u.username,
u.userid as uid,
o.userid as oid,
o.first_name as ofn,
c.comment,
c.status_id as csi
FROM statuses s
LEFT JOIN users u ON s.sender_id=u.userid
left JOIN comments c ON c.user_id = u.userid AND c.status_id = s.status_id
left join users o on o.userid = c.sender_id
where s.user_id = {$profile_data['userid']}
ORDER BY c.date DESC, s.date DESC") or die(mysql_error());
while($status = mysql_fetch_array( $data ))//added this
{
$statusid = $status['status_id'];
$date = $status['date'];
$rate = $status['rate'];
$comments = $status['comments'];
$userid = $profile_data['userid'];
$senderid = $status['uid'];
$statusbody = $status['status'];
$username = $status['username'];
$firstname = $status['first_name'];
$lastname = $status['last_name'];
$photo = $status['photo'];
$comment = $status['comment'];
$name = $status['ofn'];
$csi = $status['csi'];
?>
<form action="" method="POST" role="form" enctype="multipart/form-data" id="statusupdate" class="facebook-share-box">
<div class="share">
<div class="panel panel-default">
<div class="panel-heading"><img alt="" align="left" hspace="20" height="70" width="70" src="<? echo 'http://basecentre.co.uk/userimages/',$status["photo"]; ?>"> <font size="+2"><i class="icon icon-comment-o"></i></font> <font size="+2"><?php echo $status['first_name']; ?> <?php echo $status['last_name'] ; ?></font> | <i class="icon icon-clock-o"></i> <a rel="tooltip" href="#" data-original-title="<? echo "". date('F j, Y, g:i a', strtotime($status['date']) + 60*60) .""; ?>"><?php echo "<strong>". date('j F', strtotime($status['date']) + 60*60) ."</strong>"; if ($status['sender_id'] == $_SESSION['userid'] || $status['user_id'] == $_SESSION['userid']){
echo '<form name="deletestatus" action="" method="POST">
<input type="hidden" name="statusid" value="'.$status['status_id'].'" />
<td><input type="submit" value="Delete" onclick="return checkDelete()" class="btn btn-danger btn-xs" name="deletestatus" ></td>
</form>';
} else
echo "";?></a></div>
<div class="panel-body">
<div class="">
<?php echo $status['status']; ?>
</div>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-md-7">
<? echo "".$status['comment']."".$status['ofn']."".$status['csi'].""; ?>
</div>
</div>
</div>
</div>
</div>
</form>
</br>
<?
}
?>
Here is the information and database for "Comments" table.
comment_id (auto-i)
status_id (added depending on which status you comment on. If the comment is on status id #5, the same number will be sent to this to connect the comments with the correct statuses)
sender_id (the id of the user who is sending the comment which would be $_session['userid'];
date (date the comment was sent)
rate (Doesn't matter yet)
comment (the actual comment written out).
MY ISSUE:
The problem I currently have which I am trying to work out is that "statuses" with more than ONE comment come up twice? So you'll have the same status repeated with a different comment below? I need to get all the comments on the same status where the status_id is the same.
In my last discussion we were talking about checking for duplicates and then if the comments table is found to have more than one comment for the same status_id, it should be added to a separate array?
I thought this was a bit off subject for my last post and I have no idea of how I would go about doing this? Would anyone be able to help me out here ? Or even give me some advice on where I would start? Thank you.
You'll probably have to iterate through your results in some way, obviously according to how your arrays are structured. An example would be:
Ex.1, if $results is an associate array with the the keys as the status id.
$data = array();
foreach ($results as $k =>$v)
{
// $k could be a status, for example "status_1"
// if it doesn't yet exist in the data array as a key
// we create an array that will hold comments for that status
if (!isset($data[$k])
{
$data[$k] = array();
}
// this status is already a key in our final data set $data, so we add
// add the comments to the array
else
{
$data[$k][] = <another_comment>
}
}
Ex.2, If $results is not an associative array.
$data = array();
foreach ($results as $v)
{
$status_id = $v['status_id];
// if it doesn't yet exist in the data array as a key
// we create an array that will hold comments for that status
if (!isset($data[$status_id])
{
$data[$status_id] = array();
}
// this status is already a key in our final data set $data, so we add
// add the comments to the array
else
{
$data[$status_id][] = $v['the_comment'];
}
}
Either way, your final array would look something like:
array(
status_1 => array(
[0] => 'some string 1',
[1] => 'some string 2,
)
)

PHP/MySql simpler more efficient code

I am currently using three different queries to output information from a db.. I've put a sample of what I'm doing below, I'm just curious if there is a more efficient simpler way of spitting out this same info.
I have a db table for events, that has a date field, and parent event field. I have to group the events by their date, spit out the events per each date, then spit out each sub-event underneath those events (by using the parent event field).
Below is a sample of how my code it layed out, I'm just not that good in mysql if there is an easier query etc.
Thanks
$result = mysql_query("SELECT * FROM events GROUP BY date");
while ($event_date = mysql_fetch_assoc($result)) {
echo 'Date Header';
$result2 = mysql_query("SELECT * FROM events WHERE date = '" . $event_date['date'] . "' && parent_id = ''");
while ($event = mysql_fetch_assoc($result2)) {
echo 'Event display code';
$result3 = mysql_query("SELECT * FROM events WHERE date = '" . $event_date['date'] . "' && parent_id = '" . $event['id'] . "'");
while ($event = mysql_fetch_assoc($result3)) {
echo 'Sub Event code';
}
}
}
To achieve a markup like the below.
<h3>Date 1</h3>
<div class="top-level-event">
Some code
</div>
<div class="sub-level-event">
some sub level code
</div>
<div class="sub-level-event">
some sub level code
</div>
<h3>Date 2</h3>
<div class="top-level-event">
Some code
</div>
<div class="sub-level-event">
some sub level code
</div>
<div class="sub-level-event">
some sub level code
</div>
You can use one query:
SELECT * FROM events e1
LEFT JOIN events e2 ON e1.id=e2.parent_id AND e1.date=e2.date
WHERE e1.parent_id=''
ORDER BY e1.date

Categories