get previous next row using PDO to create links - php

i've got some bad sytax in my query where i'm trying to create 'prev_id' to pull into the $row result link. any ideas on a better way of doing this?
edit: the error is "Check the manual that corresponds to your MySQL server version for the right syntax to use near 'prev_id'."
function traversePhoto($the_selected_id) {
global $pdo;
$id = $the_selected_id;
$stmt_a = $pdo->prepare("
(SELECT * FROM images WHERE id < '.intval($id).' ORDER BY id DESC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MAX(id) FROM images)) LIMIT 1 prev_id");
$stmt_b = $pdo->prepare("
(SELECT * FROM images WHERE id > '.intval($id).' ORDER BY id ASC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MIN(id) FROM images)) LIMIT 1 next_id");
// $vars = array(':id' => $id);
$prev = $stmt_a->execute();
$next = $stmt_b->execute();
if ($prev) {
while($row = $stmt_a->fetchObject()) {
echo 'Previous';
}
} else {
echo 'no previous';
}
if ($next) {
while($row = $stmt_b->fetchObject()) {
echo 'Next';
}
} else {
echo 'no next';
}
}

Try it like this
<?php function traversePhoto($the_selected_id) {
global $pdo;
$id = $the_selected_id;
$stmt_a = $pdo->prepare("
(SELECT * FROM images WHERE id < ? ORDER BY id DESC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MAX(id) FROM images)) LIMIT 1");
$stmt_b = $pdo->prepare("
(SELECT * FROM images WHERE id > ? ORDER BY id ASC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MIN(id) FROM images)) LIMIT 1");
// $vars = array(':id' => $id);
$prev = $stmt_a->execute(array( (int)$id ));
$next = $stmt_b->execute(array( (int)$id ));
if ($stmt_a->rowCount() > 0) {
while($row = $stmt_a->fetch(PDO::FETCH_ASSOC)) {
echo 'Previous';
}
} else {
echo 'no previous';
}
if ($stmt_b->rowCount() > 0) {
while($row = $stmt_b->fetch(PDO::FETCH_ASSOC)) {
echo 'Next';
}
} else {
echo 'no next';
}

Related

How to save the count() group by from mysql into a php variable

I need to save the count(activity_type) group by user_posted_to into a variable from mysql query
$query = "
SELECT user_posted_to, COUNT(*)
FROM activity_log_table
WHERE
post_type = 'discussion'
AND activity_type = 'Like' ";
$query .= "AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY AND activity_type <= CURRENT_DATE ";
$query .= "GROUP BY user_posted_to ORDER BY activity_timestamp DESC LIMIT 25";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
$user_posted_to = (int)$row['user_posted_to'];
$timestamp = time();
// I need to insert the count into this table for number_assert
$query2 = "INSERT INTO top_weekly (user_id, number_assert, timestamp) VALUES ($user_posted_to, $timestamp)";
$result2 = mysqli_query($connection, $query2);
$confirm_query2 = confirm_query($result2);
if($confirm_query2) {
echo "success query 2";
} else {
echo "failed query 2";
}
}
i expect to save the count() group by into a php variable and to be able to use it later on the page
You want to alias the « COUNT(*) » to something else, like « cnt ». Then you can access the column by name after fetching, as demonstrated below :
$query = "
SELECT
user_posted_to,
COUNT(*) as cnt
FROM activity_log_table
WHERE
post_type = 'discussion'
AND activity_type = 'Like'
AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY
AND activity_type <= CURRENT_DATE
GROUP BY user_posted_to
ORDER BY activity_timestamp DESC
LIMIT 25";
$result = mysqli_query($connection, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "user_posted_to: " . $row["user_posted_to"]. " - Count: " . $row["cnt"] . "<br>";
}
} else {
echo "0 results";
}
Add and AS label to the COUNT(*) then you will be able to readout that label in the row you get.
$query = "SELECT user_posted_to, COUNT(*) AS varCount FROM activity_log_table WHERE post_type = 'discussion' AND activity_type = 'Like' ";
$nummerOfCount = $row['varCount']

Outputting the number of records in a database column and assign it as a variable

I am wanting to count the id field in my users table in my current query and output that. How can I change my query or my output, so that if there are 40 id's in my user table with the same WHERE conditions apply, that I can output it with a variable?
$member = mysqli_query($con,"SELECT * FROM users WHERE `group` IN (2, 3, 4, 5) ORDER BY id DESC LIMIT 1");
$numrows_member = mysqli_num_rows($member);
if($numrows_member > 0){
while($row_member = mysqli_fetch_assoc($member)){
$memberid = $row_member['id'];
$member_username = $row_member['username'];
}
} else {
$no_members = "No Members Found...";
}
Try this code :
Warning : also rename group column because group is reserve keyword of mysql database in example i renamed it as groupid.
<?php
$member = mysqli_query($con,"SELECT * FROM users WHERE `groupid` IN (2, 3, 4, 5) ORDER BY id DESC LIMIT 1");
$numrows_member = mysqli_num_rows($member);
if($numrows_member > 0){
$totalRecord=null;
while($row_member = mysqli_fetch_assoc($member)){
$memberid = $row_member['id'];
$member_username = $row_member['username'];
$group_id = intval($row_member['groupid']);
if($group_id > 0){
$totalRecord = getTotalRow($con,$group_id);
}
}
echo 'ID : '.$memberid.' UserName : '.$member_username. ' Total records : '.$totalRecord;
} else {
echo $no_members = "No Members Found...";
}
function getTotalRow($con,$id){
$record=0;
$result = mysqli_query($con,"SELECT count(id) as total FROM users WHERE groupid = $id ");
while($row = mysqli_fetch_row($result)){
echo $record = $row[0];
}
return $record;
}
?>

mysql random entries from the top200

is there a better way to return random entries from the TOP 200 bestselling tshirts (tshirt_sales from shop_tshirts) that could just query just 6 entries instead of 200 ?
$SQL = "SELECT * FROM shop_tshirts WHERE shop = 'nidieunimaitre' AND online='1' ORDER BY tshirt_sales DESC LIMIT 200";
$Result = mysql_query($SQL)
or die('A error occured: ' . mysql_error());
$Rows = array();
while ($Row = mysql_fetch_assoc($Result))
$Rows[] = $Row;
shuffle($Rows);
$i = 0;
foreach($Rows as $Data){
$i++;
if($i >= 6) { break; }
}
Try this:
SELECT *
FROM
(SELECT *
FROM shop_tshirts
WHERE shop = 'nidieunimaitre' AND online='1'
ORDER BY tshirt_sales DESC
LIMIT 200) as tableAlis
ORDER BY RAND()
LIMIT 6;
Return first 200 results and after order by rand and return only six results.

Previous or Next 10 links for search results page

I am trying to create a PDO database results page with a previous and next for the previous 10 or next 10 records. I just can't figure out what should go in the 4 ????? areas below. I have tried several different approaches with all sorts of incorrect results. Any ideas on the missing pieces to make this work?
$results = $dbh->prepare("select
stories.SID,
stories.story_name,
stories.category,
stories.genre
FROM stories
WHERE stories.category = :cat OR stories.genre = :gen LIMIT 10");
$results->bindParam(':cat', $scategory, PDO::PARAM_STR);
$results->bindParam(':gen', $sgenre, PDO::PARAM_STR);
$results->execute();
$row = $results->fetchAll(PDO::FETCH_ASSOC);
}
if ($row) {
echo '<table>';
echo '<tr>';
foreach ($row as $all) {
echo '<tr>';
echo "<td>$all[story_name]
</td>";
echo "<td>$all[category]</td>";
echo "<td>$all[genre]</td>";
}
echo '</table>';
}
//get all results from PDO SQL query and pass to previous & next links
$id = $row;
$stmt_a = $pdo->prepare("
(SELECT * FROM stories WHERE ???? ORDER BY id DESC LIMIT 1)
UNION (SELECT * FROM stories WHERE id = (SELECT MAX(id) FROM stories)) LIMIT
1 prev_id");
$stmt_b = $pdo->prepare("
(SELECT * FROM stories WHERE ????? ORDER BY id ASC LIMIT 1)
UNION (SELECT * FROM stories WHERE id = (SELECT MIN(id) FROM stories)) LIMIT
1 next_id");
// $vars = array(':id' => $id);
$prev = $stmt_a->execute();
$next = $stmt_b->execute();
if ($prev) {
while($row = $stmt_a->fetchObject()) {
echo 'Previous';
}
} else {
echo 'no previous';
}
if ($next) {
while($row = $stmt_b->fetchObject()) {
echo 'Next';
}
} else {
echo 'no next';
}
Here is a blog that discusses many aspects of what you are doing:
http://mysql.rjweb.org/doc.php/pagination
It also shows how to do "pagination" in a scalable way.

mySQL Order by Most Commented and Least Commented

I'm trying to order a list of items based on the amount of comments for each topic as shown below:
$page = $_GET['page'];
$query = mysql_query("SELECT * FROM topic WHERE cat_id='$page' LIMIT $start, $per_page");
if (mysql_num_rows($query)>=1)
{
while($rows = mysql_fetch_array($query))
{
$number = $rows['topic_id'];
$title = $rows['topic_title'];
$description = $rows['topic_description'];
//get topic total
$sqlcomment = mysql_query("SELECT * FROM comments WHERE topic_id='$number'");
$commentnumber = mysql_num_rows($sqlcomment);
// TRYING TO ORDER OUTPUT ECHO BY TOPIC TOTAL ASC OR DESC
echo "
<ul>
<li><h4>$number. $title</h4>
<p>$description</p>
<p>$topictime</p>
<p>$commentnumber</p>
</li>
</ul>
";
}
}
else
{
echo "<p>no records available.</p><br>";
}
What would be the best way to order each echo by $num_rows (ASC/DESC values)? NOTE: I've updated with the full code - I am trying to order the output by $commentnumber
The first query should be:
SELECT t.*, COUNT(c.topic_id) AS count
FROM topic AS t
LEFT JOIN comments AS c ON c.topic_id = t.topic_id
WHERE t.cat_id = '$page'
GROUP BY t.topic_id
ORDER BY count
LIMIT $start, $per_page
You can get $commentnumber with:
$commentnumber = $rows['count'];
You don't need the second query at all.
First of all you have error here
echo "divs in order from least to greatest "number = $num_rows"";
It should be
echo "divs in order from least to greatest number = " . $num_rows . "";
And about the most commented try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY column DESC/ASC";
Or if there is not count column try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY COUNT(column) DESC/ASC";

Categories