Fetch last row first in displayed array without using SELECT command? - php

I have used foreach loop to display the rows in myphp database, however I would now like to display this in DESC order (display last row first) however research tells me not to use the SELECT command in arrays? is there another way? Many thanks.
index.php:
<?php
include("app/database/db.php");
$posts = selectAll('posts', ['published' => 1]);
?>
<?php foreach ($posts as $post): ?>
<div class="post">
<div class="col-lg-6">
<!-- HEADLINE -->
<h1><strong><?php echo $post['title']; ?></strong></h1>
<!-- TEXT BODY -->
<!-- <h4></?php echo $post['body']; ?></h4> displays the full body -->
<h4 class="mainbody"><?php echo html_entity_decode(substr($post['body'], 0, 100) . '...'); ?></h4>
<!-- IMAGE -->
<div class="col-lg-6">
<img src="<?php echo '/assets/images/' , $post['image']; ?>" style="width: 550px; height: 350px; object-fit: cover;">
</div>
</div>
<?php endforeach; ?>
db.php file:
<?php
function selectAll($table, $conditions = []) {
global $conn;
$sql = "SELECT * FROM $table";
if (empty($conditions)) {
$stmt = $conn->prepare($sql);
$stmt->execute();
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
return $records;
} else {
$i = 0;
foreach ($conditions as $key => $value) {
if ($i === 0) {
$sql = $sql . " WHERE $key=?";
} else {
$sql = $sql . " AND $key=?";
}
$i++;
}
$stmt = executeQuery($sql, $conditions);
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
return $records;
}
}
?>

Related

Problem with PHP, using load jquery + GET

I'm currently doing a private chat (style messenger), and I got a problem..
I have a href a link which sends an ID using GET to another page, the thing is that on the other page I load a jquery script which again sends to another page, suddenly it no longer finds the ID GET, what should I do? I want to actualise the page (the messages) thanks (noted that I'm new, I'm not enough good to use ajax or something..)
message.php
message
<?php
// $allUsers = 'SELECT * FROM members WHERE name LIKE "%cc%" ORDER BY id DESC' / SEARCH MEMBERS
$allUsers = $dbh->query('SELECT * FROM members ORDER BY id DESC LIMIT 0, 5');
if ($allUsers->rowCount() > 0)
{
while ($user = $allUsers->fetch())
{
?>
<div id="s_un_main">
<div class="s_un_main_pun">
<img src="../images/avatar/<?php echo $user['avatar'];?>">
<p><?php echo $user['name']; ?></p>
</div>
<div class="s_un_main_pdeux">
<a class="private" target="_blank" href="private.php?id=<?php echo $user['id']; ?>">Message</a>
</div>
</div>
<?php
}
}
else
{
echo "<p>" . "Aucun utilisateur trouvé. " . "</p>";
}
?>
private.php
private
<div id="get_name">
<?php
// USERINFO
if (isset($_SESSION['id']) AND !empty($_SESSION['id']))
{
$getid = $_GET['id'];
$req = $dbh->prepare('SELECT * FROM members WHERE id = :getid');
$req->bindValue('getid', $getid);
$req->execute();
$userinfo = $req->fetch();
}
?>
<div>
<img id="img_header" width="50" src="../images/avatar/<?php echo $userinfo['avatar'];?>">
</div>
<?php echo "<p>" . $userinfo['name'] . "</p>"; ?>
</div>
<section id="zz">
<div id="show_msg">
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
</div>
</section>
<form id="private_form" method="POST" action="">
<textarea name="message"></textarea>
<input type="submit" name="send"></input>
</form>
<script>
setInterval('load_messages()', 1500);
function load_messages()
{
$('#zz').load('private_message.php');
}
</script>
private_message.php
error
<!-- DB -->
<?php include("../db/db.php"); ?>
<!-- DB -->
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
var_dump($getid);
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
var_dump($id) = not found

PHP function not showing data from dropdown menu

Currently creating 2 dropdown menus, one for category and one for subcategory. My current function shows all data on the page only for subcategories but not for categories. Why is this happening?
Current Functionality: User selects a category, page refreshes and is blank. Once user selects SUBcategory it shows all products in that subcategory.
Desired Functionality: User selects a category, page refreshes and shows all products in that category. Once user selects subcategory it shows all products in that subcategory.
function populate_search_catsub()
{
global $link;
$subcatt = "";
$query = 'SELECT * FROM item';
$result = mysqli_query($link, $query);
$catt = $_GET['catt'];
if (isset($_GET['subcatt'])) {
$subcatt=$_GET['subcatt'];
}
$nbprod = mysqli_query($link, "SELECT * FROM `item` WHERE cat='$catt' AND field='$subcatt'");
if (!isset($_GET['catt']) || $_GET['catt'] == '') {
unset($_GET['catt'], $_GET['submitsearchsub']);
populate_main();
} else {
if (isset($_GET['subcatt'])) {
echo '<span>Search results for Category="'.$catt.' And Sub Category='.$subcatt.'"</span><hr>';
}
$result = mysqli_query($link,"SELECT * FROM `item` WHERE cat='$catt' AND field='$subcatt'");
if ($cat = mysqli_fetch_row($result)) {
echo '
<div class="itemlist">
<span><h3>'.$cat[1].'</h3><h6><u>View</u></h6></span>
<div class="col-lg-12" style="background-color: white;"><br>
<div class="row">
<div class="col-lg-12" style="margin-right: 2%;">
<img src="https://via.placeholder.com/160x210">
</div>
</div><br>
</div>
</div>
<hr>
';
while ($cat = mysqli_fetch_row($result))
echo '
<div class="itemlist">
<span><h3 style="display:inline;">'.$cat[1].'</h3><h6 style="display:inline; margin-left: 1%;"><u>View</u></h6></span>
<div class="col-lg-12" style="background-color: white;"><br>
<div class="row">
<div class="col-lg-2" style="margin-right: 2%;">
<img src="https://via.placeholder.com/160x210">
</div>
</div><br>
</div>
</div>
<hr>
';
} else {
if (isset($_GET['subcatt'])) {
echo "<h2 >No results found</h2>";
}
unset($_GET['catt'], $_GET['submitsearchsub']);
populate_main();
}
}
}
First of all, grab $_GET['catt'] and $_GET['subcatt']. Then, you can build a query based on these parameters. And please, use mysqli_num_rows to check if there are more than zero rows returned.
function populate_search_catsub()
{
global $link;
$catt = $_GET['catt'] ?? ''; // Requires PHP 7.0 or upper.
$subcatt = $_GET['subcatt'] ?? ''; // Requires PHP 7.0 or upper.
$query = 'SELECT * FROM `item`'; // Initial query
if (!$catt) {
unset($_GET['submitsearchsub']);
populate_main();
} else {
$query .= " WHERE `cat` = '{$catt}'";
if ($subcatt) {
echo '<span>Search results for Category="' . $catt . ' And Sub Category=' . $subcatt . '"</span><hr>';
$query .= " AND `field` = '{$subcatt}'";
}
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) { // Check if result set is not empty.
while ($cat = mysqli_fetch_row($result))
echo '
<div class="itemlist">
<span><h3 style="display:inline;">'.$cat[1].'</h3><h6 style="display:inline; margin-left: 1%;"><u>View</u></h6></span>
<div class="col-lg-12" style="background-color: white;"><br>
<div class="row">
<div class="col-lg-2" style="margin-right: 2%;">
<img src="https://via.placeholder.com/160x210">
</div>
</div><br>
</div>
</div>
<hr>
';
} else {
if ($subcatt) {
echo '<h2 >No results found</h2>';
}
unset($_GET['catt'], $_GET['submitsearchsub']);
populate_main();
}
}
}

Remove duplicates from foreach

I've got this foreach script and if there is no result found it does show this message "No articles yet" twice, how can i fix this? I've tried to move it out of the foreach but with no success.
Many thanks
$query_show_groupmsg = mysqli_prepare($conn, "SELECT group_message_id, group_message_date, group_message_subject, group_message_body FROM group_messages WHERE group_message_refid = ? ORDER BY group_message_date DESC LIMIT 5");
mysqli_stmt_bind_param($query_show_groupmsg, 'i', $data);
foreach ($id_gruppo as $data) {
mysqli_stmt_execute($query_show_groupmsg);
mysqli_stmt_bind_result($query_show_groupmsg, $group_message_id, $group_message_date, $group_message_subject, $group_message_body);
mysqli_stmt_store_result($query_show_groupmsg);
$groupmsg = mysqli_stmt_num_rows($query_show_groupmsg);
if ($groupmsg > 0) {
while (mysqli_stmt_fetch($query_show_groupmsg)) {
$new_mgsgroup_date = date('d/m/Y, \a\l\l\e h:i a', strtotime($group_message_date));
?>
<div class="item">
<div class="item-head">
<div class="item-details">
<?php
echo ' <a class="item-name primary-link" href="client_blog_app/client_group_post_view.php?id='.$group_message_id.'"> '.ucfirst(strip_tags(mb_strimwidth($group_message_subject, 0, 350, "..."))).'</a>
';
?>
<br><span class="item-label font-blue small">Pubblicato il <?php echo "$new_mgsgroup_date"; ?></span>
</div>
</div>
<div class="item-body"> <?php echo strip_tags(mb_strimwidth($group_message_body, 0, 350,"...")); ?> </div>
</div>
<?php
}
}else{
echo '
<div class="alert alert-info">No articles yet</div>
';
}
}
Add this outside of the for loop and remove the else clause you already have.
<?
if ($groupmsg < 1)
{
?>
<div class="alert alert-info">No articles yet</div>
<?
}
Put the IF ELSE statement outside the FOREACH like this:
$query_show_groupmsg = mysqli_prepare($conn, "
SELECT group_message_id, group_message_date, group_message_subject, group_message_body FROM group_messages
WHERE group_message_refid = ?
ORDER BY group_message_date
DESC LIMIT 5
");
$article_count = 0;
mysqli_stmt_bind_param($query_show_groupmsg, 'i', $data);
foreach ($id_gruppo as $data) {
mysqli_stmt_execute($query_show_groupmsg);
mysqli_stmt_bind_result($query_show_groupmsg, $group_message_id, $group_message_date, $group_message_subject, $group_message_body);
mysqli_stmt_store_result($query_show_groupmsg);
$groupmsg = mysqli_stmt_num_rows($query_show_groupmsg);
if ($groupmsg > 0) {
while (mysqli_stmt_fetch($query_show_groupmsg)) {
$new_mgsgroup_date = date('d/m/Y, \a\l\l\e h:i a', strtotime($group_message_date));
$article_count++;
?>
<div class="item">
<div class="item-head">
<div class="item-details">
<?php echo ' <a class="item-name primary-link" href="client_blog_app/client_group_post_view.php?id='.$group_message_id.'"> '.ucfirst(strip_tags(mb_strimwidth($group_message_subject, 0, 350, "..."))).'</a>'; ?>
<br>
<span class="item-label font-blue small">Pubblicato il <?php echo "$new_mgsgroup_date"; ?></span>
</div>
</div>
<div class="item-body"> <?php echo strip_tags(mb_strimwidth($group_message_body, 0, 350,"...")); ?> </div>
</div>
<?php
}
}
}
if ($article_count == 0){
echo '<div class="alert alert-info">No articles yet</div>';
}
Since your if ($groupmsg > 0) condition is inside the foreach cycle, the else branch can be executed up to count($data) times. Moving the condition out of the foreach loop should fix this. You can keep count of articles inside foreach and after the foreach check if there were any.
However this code is really terrible to read (no comments, random indentation). You should make a minimal working example, remove the useless parts and comment your code, if needed.

php foreach wrap every 2 divs

I need to wrap every 2 divs with another div for a project (a row) so it will look like:
<div class="row">
<div> Item </div>
<div> Item </div>
</div>
<div class="row">
<div> Item </div>
<div> Item </div>
</div>
I have tried a few solutions but they dont work since the items coming in are odd (9 items). Here is what I had:
<?php
$count = 0;
foreach ($contents as $content)
{
//var_dump($content);
$books = $content["tags"];
$book_image = $content['content_image'];
$book_desc = $content['content_social_description'];
++$count;
if($count == 1)
{
echo "<div class='et_pb_row'>";
}
foreach ($books as $book)
{
$book_name = $book['tag_name'];
$book_name_trim = str_replace(' ', '-', $book_name);
?>
<!-- Inside the Book Loop -->
<div class='et_pb_column et_pb_column_1_2 books' style="background: url('https://s3-us-west-2.amazonaws.com/crowdhubproverbs31/<?php echo $book_image ;?>');">
<h2><?php echo $book_name; ?></h2>
<p><?php echo $book_desc; ?></p>
<?php echo $count; ?>
</div>
<?php
}
if ($count == 2)
{
echo "</div>";
$count = 0;
}
}
?>
This works except the second to last row has 3 items even though it dispays the "count" as 2 when I echo it out so it should reset but doesnt. So its:
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>
You should open and close your <rows/> in the books loop, and add a late check for odd books:
<?php
$count = 0;
foreach ($contents as $content)
{
//var_dump($content);
$books = $content["tags"];
$book_image = $content['content_image'];
$book_desc = $content['content_social_description'];
foreach ($books as $book)
{
++$count;
if($count == 1)
{
echo "<div class='et_pb_row'>";
}
$book_name = $book['tag_name'];
$book_name_trim = str_replace(' ', '-', $book_name);
?>
<!-- Inside the Book Loop -->
<div class='et_pb_column et_pb_column_1_2 books' style="background: url('https://s3-us-west-2.amazonaws.com/crowdhubproverbs31/<?php echo $book_image ;?>');">
<h2><?php echo $book_name; ?></h2>
<p><?php echo $book_desc; ?></p>
<?php echo $count; ?>
</div>
<?php
if ($count == 2)
{
echo "</div>";
$count = 0;
}
}
}
if ($count > 0)
{
echo "</div>";
}
?>
Doing so, your $count variable will be incremented only when foreach($books AS $book) loop is run (thus you have at least one book to print)
You can take advantage of array_chunk :
//First make a generator to get all books
function allBooks($contents) {
foreach($contents as $content) {
foreach($content['tags'] as $book) {
yield $book; //Here you can yield whatever you want !
}
}
}
//Then create rows
$itemPerRow = 2;
$rows = array_chunk(iterator_to_array(allBooks($contents)), $itemPerRow, true);
//Display all
foreach($rows as $row) {
echo '<row>';
foreach($row as $book) {
//Display the book !
}
echo '</row>';
}

Wordpress: get_post_field() throws error like it's trying to redefine a function

I have a function called getNews().
I call getNews() like this:
<div class="wrapper" id="blog">
<div class="blogPosts">
<?PHP getNews($postPerPage, 0, $theme_link, $pageNum); ?>
</div>
</div>
The function works until it tries to get the article text from wordpress using get_post_field().
function getNews($numPosts, $offset, $theme_link, $pageNum) {
$offset = $numPosts * $pageNum;
$recent_args = array('numberposts' => $numPosts, 'offset' => $offset,);
$articles = wp_get_recent_posts($recent_args);
foreach($articles as $article){
$article_id = $article['ID'];
...
echo $article_text = get_post_field('post_content', $article_id);
...
}
}
When I run this, I get the error saying Fatal error: Cannot redeclare getNews() (previously declared in /homepages/30/d545089862/htdocs/VintageTroubleMusic/wp-content/plugins/enhanced-text-widget/enhanced-text-widget.php(57)
For some reason, it's running my loop twice.
Any advice?
EDIT
I'm including the full code here: This is written inside of an "Enhanced Text widget" inside of a page.
<?PHP
$theme_link = "/wp-content/themes/thestory-child/";
$pageNum = $_GET['pa'];
$postPerPage = 27;
$qry_numPosts = mysql_query("SELECT * FROM Ykcfdlqhposts WHERE post_status = 'publish' AND post_type = 'post'") or die(mysql_error());
$numPosts = mysql_num_rows($qry_numPosts);
$numPages = ceil($numPosts/$postPerPage) . " pages";
if(!$pageNum){
$pageNum = 0;
}
?>
<!-- START OF THE BODY HERE -->
<h3 class="widget-title" style="float:left;">Headlines</h3>
<div class="wrapper" id="paginate1">
<?PHP paginate($numPosts, $numPages); ?>
</div>
<div class="wrapper" id="blog">
<div class="blogPosts">
<?PHP getNews($postPerPage, 0, $theme_link, $pageNum); ?>
</div>
</div>
<div class="wrapper" id="paginate2">
<?PHP paginate($numPosts, $numPages); ?>
</div>
And inside of the functions.php page
function getNews($numPosts, $offset, $theme_link, $pageNum) {
$offset = $numPosts * $pageNum;
$recent_args = array('numberposts' => $numPosts, 'offset' => $offset,);
$articles = wp_get_recent_posts($recent_args);
foreach($articles as $article){
$article_id = $article['ID'];
$article_link = get_permalink($article_id);
$article_length = 350;
$article_background = get_the_post_thumbnail($article_id);
$article_title = get_post_meta( $article_id, 'short_title', true );
$article_text = "test";
$article_text = get_post_field('post_content', $article_id);
//$article_text = get_post_field('post_content', $article_id);
//$article_text = strip_tags($article_text);
//$article_text_length = strlen($article_text);
/*
if($article_text_length >= $article_length) {
$article_text_pos = strpos($article_text, " ", $article_length);
$article_text = substr($article_text, 0, $article_text_pos)."... ";
}
*/
?>
<div class="article">
<?PHP //Get the article image
if (!$article_background) {
$rand = rand(1, 5);
$img = $theme_link . "images/img" . $rand . ".jpg";
} else {
$img = explode('src="', $article_background);
$img = explode(".jpg", $img[1]);
$img = $img[0] . ".jpg";
}?>
<a href="<?= $article_link; ?>">
<div class="article__image" style="background-image: url('<?= $img; ?>');"></div>
<div class="article__title"><?= $article_title; ?></div>
</a>
<div class="article__details">
<div class="article-text">
<?= $article_text; ?>
</div>
READ MORE
</div>
</div>
<? }
}
function paginate($numPosts, $numPages) {
?>
<div class="page">
<span>Page:</span><?PHP
$i = 0;
while($i < $numPages){
$i++;
if($i == $pageNum){
echo '<span style="background-color:transparent; text-decoration:underline; color:white; cursor:default;">'.$i.'</span>';
} else {
echo "<a href='?pa=".$i."'><span>".$i."</span></a>";
}
}
?>
</div>
<?
}

Categories