I am doing PM system for my site. I created subpage for each conversation by two users. I am having hard time programming the front page, where all conversations are printed. I cant get only one and last meassage for each user.
Here is my function:
public function fetch_data($id_uporabnika) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM zs WHERE za = ? ORDER BY datum");
$query->bindValue(1, $id_uporabnika);
$query->execute();
return $query->fetchAll();
}
And here is my code for printing conversations:
<?php
} else {
$zs = new Zs;
$id_uporabnika = $trenutni['id'];
$zsji = $zs->fetch_data($id_uporabnika);
?>
<h2>Zasebna sporočila</h2>
<ul class="vsi-zsji">
<?php foreach ($zsji as $sporocilo): ?>
<?php $od = $oseba->fetch_data($sporocilo['od']) ?>
<li>
<a href="<?php echo $url; ?>zs/poglej/<?php echo $sporocilo['od']; ?>">
<img src="<?php echo $url; ?>inc/timthumb.php?src=<?php echo $od['slika_potem'] ?>&w=60&h=60" alt="">
<p><b><?php echo $od['uporabnisko_ime'] ?></b></p>
<p><?php echo $sporocilo['vsebina'] ?></p>
</a>
</li>
<?php endforeach ?>
</ul>
<?php } ?>
I get 10 PMs from one user, 3 for another. I want to display just the latest one.
Just put a LIMIT clause in your SQL query and order by DESC to get the latest message:
$query = $pdo->prepare("SELECT * FROM zs WHERE za = ? ORDER BY datum DESC LIMIT 1");
something like this should help
SELECT id,datum, max(pm) FROM zs WHERE za = ? group by id,datum
Related
A form showing different posts of user. Posts which is stored in database. Now the problem is the previous pagination works fine but the next pagination is incrementing 2 blank pages and url changes with that page. Can anyone tell me whats wrong with this code .?
php:
<?php
$limitr = ((($page*2)+1)-2)*$perpage;
$query = mysqli_query($dbc, "SELECT SQL_CALC_FOUND_ROWS * FROM final1 LIMIT {$limitr}, {$perpage}");
$records = mysqli_fetch_all($query);
$total = mysqli_query($dbc, "SELECT FOUND_ROWS() as total");
$total = mysqli_fetch_assoc($total)['total'];
$pages = ceil($total/$perpage);
?>
<?php
if($page>1){
?>
<a class="page-link" href="?page=<?php $pagep = $page -1; echo $pagep; ?>" tabindex="-1">Previous</a>
<?php
}
?>
</li>
<li class="page-item">
<?php
if($page<$pages){
?>
<a class="page-link" href="?page=<?php $pagen = $page +1; echo $pagen; ?>">Next</a>
<?php
}
?>
"SELECT SQL_CALC_FOUND_ROWS * FROM final1 LIMIT {$limitr}, {$perpage}");
The first parameter after the LIMIT the offset,, the second is how much records do you want.
But I'm not sure what are you calculating with limitr btw. If you already have which page do you want, it should be simply
LIMIT {($page-1)*perpage}, {$perpage}
Also, the database is unordered, so might miss some records or duplicate others, might wanna add some kind of ORDER BY option.
(SORRY, ORDERS ARE REVERSED WHEN USED WITH COMMA!)
I have searched for about 4 hours today on how to do this.
I want to pull all post titles and categories from the posts table and
essentially want to list the "Funny" category and then list all post that have the funny category under that category. Right now I am getting the following:
Funny
-post title
Funny
-post title
I want to output
Funny
-post title
-post title
<?php
$query = "SELECT post_category,post_title FROM posts ";
$select_categories_sidebars = mysqli_query($connection, $query);
?>
<h4>Blog Categories</h4>
<div class="row">
<div class="col-lg-12">
<ul class="list-group">
<?php
while($row = mysqli_fetch_assoc($select_categories_sidebars)) {
$post_title = $row['post_title'];
$post_tags = $row['post_category'];
echo "<li class='list-group-item'>$post_tags</li><ul>";
echo "<li class='list-group-item'><a href='category.php?category=$post_title'> {$post_title}</a></li></ul>";
}
?>
</ul>
That should do the trick:
First you should sort your query by category:
$query = "SELECT post_category,post_title FROM posts ORDER BY post_category";
Then do this:
<?php
while($row = mysqli_fetch_assoc($select_categories_sidebars)) {
$post_title = $row['post_title'];
$post_tags = $row['post_category'];
$used_tag = null,
// check if you already posted that category/tag. If not, show it:
if($used_tag!=$post_tags) {
echo "<li class='list-group-item'>$post_tags</li>"; // I removed a '</ul>' here
// set this title as 'used'
$used_tag=$post_tags;
}
echo "<li class='list-group-item'><a href='category.php?category=$post_title'> {$post_title}</a></li>"; // I removed a '</ul>' here too
}
?>
BUT
In an ideal world you'd have two tables to accomplish this.
One for the categories, one for the posts. Each table with id's to work with
This way you produce a lot of redundant data, it's more complicated to filter, and so on...
You might want to have a look at relational database design.
Well I basically got it working how I want I just need to format it correctly now, but it is working with some help from this question. PHP Group sql query under the same title
<?php
$query = "SELECT post_category,post_title FROM posts ORDER BY post_tags";
$select_categories_sidebars = mysqli_query($connection, $query);
?>
<h4>Blog Categories</h4>
<div class="row">
<div class="col-lg-12">
<ul class="list-group">
<?php
$title = "";
while ($row = mysqli_fetch_array($select_categories_sidebars)) {
if ($row['post_category'] != $title) {
echo '<li class="list-group-item">'.$row['post_category'].'</li><br>';
$title = $row['post_category'];
}
echo '<li class="list-group-item">'.$row['post_title'];
}
?>
I am trying to make a page which has to get data from two tables. and display on a page. this displayed data is an array. for example if the displayed data is say USA which come from Table A,and if you click on USA...then it should go to Table B and get all the states from Table B related to USA and display it on the page. so how to join the tables?
the code used is as below:
<?php
require("libs/config.php");
$pageDetails = getPageDetailsByName($currentPage);
$stateDetails = getStateDetailsById($page_id);
include("header.php");
?>
<div class="row main-row">
<div class="col-md-8">
<section class="left-content">
<h2><?php echo stripslashes($pageDetails["page_title"]); ?></h2>
<?php echo stripslashes($pageDetails["page_desc"]); ?>
<!--New-->
<?php
$page_id = $pageDetails["page_id"];
if ($_GET["id"] <> "")
{
// if we are on page.php page. get the parent id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_PAGES . " WHERE status = 'A' AND parent = :parent ORDER BY sort_order ASC";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($pageDetails["parent"]));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
elseif ($page_id <>"")
{
// On any other Page get the page id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_PAGES . " WHERE parent = :parent";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($page_id));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
?>
<div class="col-sm-12">
<?php
if (count($pageResults) > 0)
{
?>
<section>
<h2>States</h2>
<div>
<div class="row">
<?php foreach ($pageResults as $rs)
{ ?>
<div class="col-sm-3">
<ul class="state">
<li class="state">
<div class="state-dist"><h3><?php echo stripslashes($rs["page_title"]);?></h3>
<div class="state_img"><img src="images/<?php echo stripslashes($rs["page_image"]);?>"height="50" width="180"</div>
<br />
<br />
<div class="page-actions">
More Details
</div>
</li>
</ul>
</div>
<?php } ?>
</div>
</div>
</section>
<?php } ?>
</section>
</div>
So,
when i click on the link created by the last part of the code then it should go to TABLE.STATES fetch the records and display it. Currently this code goes to the same table TABLE_PAGES.
I know i have to use table joins but I am not able to code it.
Currently this code goes to the same table TABLE_PAGES.
As far as I think, you should change TABLE_PAGES to TABLE_STATES in the following part of your code:
elseif ($page_id <>"")
{
// On any other Page get the page id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_STATES . " WHERE parent = :parent";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($page_id));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
I'm assuming you'll be running the following SQL code:
SELECT * FROM TABLE_STATES WHERE TABLE_STATES.page_id = TABLE_PAGES.page_id
which you can execute to get a list of all the states belonging to the parent (TABLE_PAGES) table.
TIP: Always try to use table names that represent real-world entities AND serve the purpose of the actual data that you want to store. In your case TABLE_COUNTRIES would be a more conventional name for a table that represents the entity country.
You could also run a left join as such:
SELECT TABLE_STATES.* LEFT JOIN TABLE_COUNTRIES ON TABLE_COUNTRIES.page_id = TABLE_STATES.page_id AND TABLE_COUNTRIES.page_id = <your provided value>
I've spent a lot of time looking at methods to do this and functions yet not been able to get the contents to display to screen in reverse.
I want to show the most recent entries in a blog at the top of the list. So here's what I have so far but the array doesn't seem to be reversing and neither is the while loop working that displays the elements that I want (I used print_r and var_dump just for debugging.
<body class="body">
<ul>
<?php
include 'config.php';
include 'opendb.php';
$sql = 'SELECT post_id AS "id", post_title AS "title", post_datetime AS "datetime" FROM posts WHERE post_id IS NOT NULL';
$res = mysqli_query($conn, $sql);
while (($post = $res->fetch_assoc())){
echo current($post);
}
array_reverse_keys($post);
foreach ($post as $value) {
print_r($value);
}
while ($post) {
?>
<li>
<?php
if (isset($post)) {
?>
<a href="#" data-id="<?php echo $post['id'] ?>">
<?php echo $post['title']?></a>
<?php
}
?>
</li>
<?php
}
?>
</ul>
<?php
$conn->close();
?>
</body>
</html>
The function being called reads:
<?php
function array_reverse_keys($ar){
return array_reverse(array_reverse($ar,true),false);
}
?>
Can anyone assist please?
Kind regards,
Mark
Your function is returning the new array, but you're not using the returned value when you call it. It should be:
$post = array_reverse_keys($post);
Change your sql add order by clause
eg:
$sql="SELECT post_id AS "id", post_title AS "title", post_datetime AS "datetime" FROM posts WHERE post_id IS NOT NULL order by id DESC";
Change this line
array_reverse_keys($post);
to
$post = array_reverse_keys($post);
How can i add a pagination system to this simple item display? And how i can add pagination for the results from filter? I just get lost that part and i cant figure it out!
I want to apply CSS on the menu too!
Here's the code:
<?php
include('db.php');
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
$result = mysql_query("SELECT * FROM products where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
else
{
$result = mysql_query("SELECT * FROM products");
}
while($row=mysql_fetch_assoc($result))
{
echo '<li class="portfolio-item2" data-id="id-0" data-type="cat-item-4">';
echo '<div>
<span class="image-block">
<a class="example-image-link" href="reservation/img/products/'.$row['imgUrl'].'" data-lightbox="example-set" title="'.$row['Product'].'""><img width="225" height="140" src="reservation/img/products/'.$row['imgUrl'].'" alt="'.$row['Product'].'" title="'.$row['Product'].'" />
</a>
</span>
<div class="home-portfolio-text">
<h2 class="post-title-portfolio"><font color="#666666">'.$row['Product'].'</font></h2>
<p class="post-subtitle-portfolio"><font color="#666666">Descrição: '.$row['Description'].'
<p class="post-subtitle-portfolio"><font color="#666666">Categoria: '.$row['Category'].'
<p class="post-subtitle-portfolio">Código: '.$row['Price'].'</p><br/></font></p>
</div>
</div>';
echo '</li>';
}
?>
EDITED:
<?php
include('db.php');
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
$result = mysql_query("SELECT * FROM products where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
else
{
$start=0;
$limit=6;
if(isset($_GET['id']))
{
$id = $_GET['id'];
$start = ($id-1)*$limit;
}
$result = mysql_query("SELECT * FROM products LIMIT $start, $limit");
}
while($row = mysql_fetch_array($result))
{
echo '<li class="portfolio-item2" data-id="id-0" data-type="cat-item-4">';
echo '<div>
<span class="image-block">
<a class="example-image-link" href="reservation/img/products/'.$row['imgUrl'].'" data-lightbox="example-set" title="'.$row['Product'].'""><img width="225" height="140" src="reservation/img/products/'.$row['imgUrl'].'" alt="'.$row['Product'].'" title="'.$row['Product'].'" />
</a>
</span>
<div class="home-portfolio-text">
<h2 class="post-title-portfolio"><font color="#666666">'.$row['Product'].'</font></h2>
<p class="post-subtitle-portfolio"><font color="#666666">Descrição: '.$row['Description'].'
<p class="post-subtitle-portfolio"><font color="#666666">Categoria: '.$row['Category'].'
<p class="post-subtitle-portfolio">Código: '.$row['Price'].'</p><br/></font></p>
</div>
</div>';
echo '</li>';
}
echo "</ul>";
$rows = mysql_num_rows(mysql_query("SELECT * FROM products"));
$total = ceil($rows/$limit);
if($id>1)
{
echo "<center><a href='?id=".($id-1)."' class='button'>Anterior</a></center>";
}
if($id!=$total)
{
echo "<center><a href='?id=".($id+1)."' class='button'>Próximo</a></center>";
}
?>
You should have something like this:
// declare a base query
$q = "SELECT * FROM products";
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
// append filter to query
$q += "where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
// check for "page" URL parameter, if not available, go to first page
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// check for "pageSize" URL parameter, if not available, fall back to 20
$pageSize = isset($_GET['pageSize']) ? $_GET['pageSize'] : 20;
// append the pagination to your query
$q += sprintf("LIMIT %d,%d;", ($page-1)*$pageSize, $pageSize);
// execute the constructed query
$result = mysql_query($q);
Note that the code is "pseudoish", not tested, but should give you the base idea.
Also, you can check this SO post about pagination with MySQL.
UPDATE
In PHP if you use an uninitialized variable, then it will have a context-dependent default value. See the documentation about this here. Here is an extract:
It is not necessary to initialize variables in PHP however it is a
very good practice. Uninitialized variables have a default value of
their type depending on the context in which they are used - booleans
default to FALSE, integers and floats default to zero, strings (e.g.
used in echo) are set as an empty string and arrays become to an empty
array.