Article title showing multiple times in foreach loop - php

Article title is showing multiple times in foreach loop
Here is the articles.php
<?php
include('functions.php');
$article = new Article;
$articles = $article->fetch_all();
?>
<html>
<head>
<title>Sample Blog</title>
<link rel = "stylesheet" type = "text/css" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div class="col-sm-6">
<h1 class="text-center">Articles</h1> </div>
<ol>
<?php
foreach($articles as $article){?>
<li>
<a href="article.php?id=<?php echo $articles["article_id"];?>">
<?php echo $articles["article_title"];?>
</a>
</li>
<?php
}
?>
</ol>
</div>
</body>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</html>
And here is the functions.php code
<?php
require ('config.php');
if (!$connection) {
echo "Failed to connect to Server!".mysqli_connect_error();
}
class Article{
public function fetch_all(){
$connection = mysqli_connect(host,username,password,database) or die("Unable to connect to the host");
$select = "SELECT * FROM articles";
$result = mysqli_query($connection,$select) or die(mysqli_error($connection));
return (mysqli_fetch_assoc($result));
}
}
?>
Here is the screenshot of the output

The problem is within your loop. You are calling $articles["article_id"] and $articles["article_title"].
You want $article["article_id"] and $article["article_title"].
foreach($articles as $article){?>
<li>
<a href="article.php?id=<?php echo $article["article_id"];?>">
<?php echo $article["article_title"];?>
</a>
</li>
<?php
}

Related

php pagination has some error

I'm trying to materialize pagination. I want to fetch like
$sql2 = "select * from phptest.memo order by num desc limit $start,$start+$scale";
and i used while paragraph to show memo and ripple (ripple database has parent field that what number of memo and it's order num primary field) but I think it seems like typed wrong code what should i do? It's image that I want make
Expected result:
Error:
<?php
session_start();
// echo "<a href='memo.php?page=$i'> $i </a>";
$scale=5; // page per writing
// start recored number newest writing is up
// $page 값에 다른 시작 레코드 넘버값, 가장 높은 글번호(최신글 부터 밑으로)
$start = ($page - 1) * $scale; //0,5,10 ...
if(!isset($_REQUEST["page"]))
{
$page = 1; // initialize seeing page
}else{
$page = $_REQUEST["page"];
}
require_once '../lib/dbconn.php';
$pdo = db_connect();
if(isset($_SESSION["userid"])){
$userid = $_SESSION["userid"];
}else{
$userid = "";
}
// start recored number newest writing is up
try{
//$sql = "select * from phptest.memo order by num desc";
$sql2 = "select * from phptest.memo order by num desc limit $start,$start+$scale";
$stmh = $pdo->query($sql2);
} catch (PDOException $ex) {`enter code here`
print "오류: ".$ex->getMessage();
}
$total_record = $stmh->rowCount();
$number = $total_record - $start;
// 전체 페이지 수 계산..
if ($total_record % $scale == 0)
$total_page = floor($total_record/$scale);
else
$total_page = floor($total_record/$scale) + 1;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8">
<link href="../css/common.css" rel="stylesheet" type="text/css" media="all">
<link href="../css/memo.css" rel="stylesheet" type="text/css" media="all">
</head>
<body>
<div id="wrap">
<div id="header">
<?php include "../lib/top_login2.php"; ?>
</div> <!-- end of header -->
<div id="menu">
<?php include "../lib/top_menu2.php"; ?>
</div> <!-- end of menu -->
<div id="content">
<div id="col1">
<div id="left_menu">
<?php
include "../lib/left_menu.php";
?>
</div>
</div>
<div id="col2">
<div id="title">
<img src="../img/title_memo.gif">
</div>
<?php
// if(isset($_SESSION["userid"])){
?>
<div id="memo_row1">
<form name="memo_form" method="post" action="insert.php">
<?php if(isset($_SESSION['nick'])){ ?>
<div id="memo_writer"><span >▷ <?=$_SESSION['nick'] ?> </span></div>
<?php }?>
<div id="memo1"><textarea rows="6" cols="95" name="content"></textarea></div>
<div id="memo2"><input type="image" src="../img/memo_button.gif"></div>
</form>
</div> <!-- end of memo_row1 -->
<?php // }
while ($row = $stmh->fetch(PDO::FETCH_ASSOC))
{
// $stmh = $pdo->query($sql2);
//$row[$i] = $row;
// $row = $stmh2->fetch(PDO::FETCH_ASSOC);
$memo_id = $row['id'];
$memo_num = $row['num'];
$memo_date = $row['regist_day'];
$memo_nick = $row['nick'];
$memo_content = $row['content'];
$memo_content = str_replace("\n", "<br>", $row['content']);
$memo_content = str_replace(" ", " ", $memo_content);
?>
<div id="memo_writer_title">
<ul>
<li id="writer_title1"><?= $memo_num ?></li> <!--article number -->
<li id="writer_title2"><?= $memo_nick ?></li>
<li id="writer_title3"><?= $memo_date ?></li>
<li id="writer_title4">
<?php
if($userid=="admin" || $userid==$memo_id)
echo "<a href='delete.php?num=$memo_num'>[삭제]</a>";
?>
</li>
</ul>
</div>
<div id="memo_content"><?= $memo_content ?>
</div>
<div id="ripple">
<div id="ripple1">덧글</div>
<div id="ripple2">
<?php
$sql3 = "select * from phptest.memo_ripple where parent=$memo_num";
$stmh3 = $pdo->query($sql3);
while ($row_ripple = $stmh3->fetch(PDO::FETCH_ASSOC))
{
$ripple_num = $row_ripple["num"];
$ripple_id = $row_ripple["id"];
$ripple_nick = $row_ripple["nick"];
$ripple_content = str_replace("\n", "<br>", $row_ripple["content"]);
$ripple_content = str_replace(" ", " ", $ripple_content);
$ripple_date = $row_ripple["regist_day"];
?>
<div id="ripple_title">
<ul>
<li><?= $ripple_nick ?> <?= $ripple_date ?></li>
<li id="mdi_del">
<?php
if($userid=="admin" || $userid==$ripple_id)
echo "<a href='delete_ripple.php?num=$ripple_num'>삭제</a>";
?>
</li>
</ul>
</div>
<div id="ripple_content"> <?= $ripple_content ?></div>
<?php
}
if(isset($_SESSION["userid"])){
?>
<form name="ripple_form" method="post" action="insert_ripple.php">
<input type="hidden" name="num" value="<?= $memo_num ?>">
<div id="ripple_insert">
<div id="ripple_textarea">
<textarea rows="3" cols="80" name="ripple_content"></textarea>
</div>
<div id="ripple_button"><input type="image" src="../img/memo_ripple_button.png"></div>
</div>
</form>
<?php } ?>
</div> <!-- end of ripple2 -->
<div class="clear"></div>
<div class="linespace_10"></div>
<?php
//$number--;
}
?>
<div id="page_num"> ◀ 이전
<?php
// page link num
// 게시판 목록 하단에 페이지 링크 번호 출력
for ($i=1; $i<=$total_page; $i++)
{
if ($page == $i) // ���� ������ ��ȣ ��ũ ����
{
echo "<b> $i </b>";
}
else
{
echo "<a href='memo.php?page=$i'> $i </a>";
}
}
?>
다음 ▶</div>
</div> <!-- end of ripple -->
</div> <!-- end of col2 -->
</div> <!-- end of content -->
</div> <!-- end of wrap -->
</body>
</html>
The SQL doesn't like doing maths in the limit clause. Do it first in PHP:
$sql2 = "select * from phptest.memo order by num desc limit $start," . ($start+$scale);

Cannot redeclare class Application

Here is the index file where i initiate Application class. When i run it i get Fatal error:Cannot redeclare class Application in C:\xampp\htdocs\blog_with_pdo\project\classes\application.php on line 4
<?php
if(!class_exists('Application')) {
require_once'./classes/application.php';
$obj_app=new Application();
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="asset/front_end/css/bootstrap.min.css" />
<script src="asset/front_end/js/jquery.min.js"></script>
<script src="asset/front_end/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<?php
include 'includes/header.php';
?>
<div class="container-fluid">
<div class="row">
<div class="container">
<?php
include_once 'includes/left_sidebar.php';
?>
<div class="col-md-8"></div>
<?php
include 'includes/right_sidebar.php';
?>
</div>
</div>
</div>
<?php
include 'includes/footer.php';
?>
</div>
</body>
</html>
Here is the Application class
<?php
require_once 'db_connect.php';
class Application {
public $pdo;
public function __construct() {
$obj_db = new Db_connect();
$this->pdo = $obj_db->pdo;
}
public function select_all_published_category() {
try {
$query = "SELECT * FROM tbl_category WHERE publication_status='1' ";
$result = $this->pdo->query($query);
return $result;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}
Here is left_sidebar.php where i want to use Application class object.
<?php
$result=$obj_app->select_all_published_category();
?>
<div class="col-md-2" style="border-right: 1px solid #ffcc99; margin: 0; padding: 0;">
<nav class="nav-sidebar">
<ul class="nav tabs">
<li class="sidebar-brand">
<span class="fa fa-home solo">বিষয়ভিত্তিক</span>
</li>
<?php
while ($row=$result->fetch(PDO::FETCH_ASSOC)) { ?>
<li><?php $row['category_name']; ?></li>
<?php } ?>
</ul>
</nav>
</div>

Update Query in PHP - undefined ID error in code

I have a problem with my code in php.
Error: Undefined Variable 'id'.
<?php
include_once '../includes/connection.php';
include_once '../includes/functions.php';
session_start();
$posts = $pdo->query("SELECT * FROM posty ORDER BY post_id DESC");
$j=0;
?>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../sources/css/style.css">
<script type="text/javascript" src="../sources/scripts/time.js"></script>
<script type="text/javascript" src="../sources/scripts/scroll.js"></script>
</head>
<body onload="timeLine(); setInterval('timeLine()', 1000 )" >
<header>
<div class = "menu">
<ul>
<li> Blog </li>
<li> Archives </li>
<li> Contact </li>
<li id="addPost"> Add Post </li>
<li id="editPost"> Edit Post </li>
<li id="deletePost"> Delete Post </li>
<li id="showBlogContent"> Hide Blog </li>
<li id="menuRightLogin"> Logout </li>
<li id="menuRightDate"><?php echo date('jS F Y').' '; ?><span id="clock"> </span> </li>
</ul>
</div>
</header>
<div id="showBlog" style="display: block;">
<div class="container">
<div class="postsContainer">
<?php foreach($posts as $post) {
if ($j <= 5) { ?>
<div class="postBox">
<div class="postTitle">
<br />
<?php echo $post['post_title']; ?>
</div>
<div class="postContent">
<br />
<?php if(($wordCount = str_word_count($post['post_content']) <=50)) {
echo $post['post_content'];?>
Edit Post
<br />
<?php } else {
echo excerpts($post['post_content'], 50).'... <br/> <br/>
Edit Post
<br /> <br />';
} ?>
</div>
<div class="postDate">
<?php echo '<b id="author">Author:</b> '.$post['post_author'].' <b id="posted">posted:</b> '.date('jS F Y', $post['add_date']); ?>
</div>
</div>
<?php $j++; } }?>
</div>
</div>
<footer>
<small> © Copyright 2015, n3stis </small>
</footer>
</div>
</body>
</html>
So from here I'm sending a 'id' to edit form:
<?php
include_once '../includes/connection.php';
include_once '../includes/functions.php';
session_start();
$id = $_GET['id'];
if (isset ($id)) {
if (isset($_SESSION['logged_in'])) {
$query = $pdo->prepare("SELECT * FROM posty WHERE post_id='" . $id . "' LIMIT 1");
$query->execute();
$post = $query->fetch();
if (isset($_POST['post_title'], $_POST['post_content'], $_POST['post_author'])) {
$postTitle = $_POST['post_title'];
$postAuthor = $_POST['post_author'];
$postContent = nl2br($_POST['post_content']);
$postTime = time();
if (empty($post_title) or empty($post_content) or empty($post_author)) {
$error = 'All fields required.';
} else {
$sql = ("UPDATE `posty` SET `post_title` = :title, `post_author` = :author, `post_content` = :content, `edit_date` = :editDate WHERE `post_id` = :postID ");
$query = $pdo->prepare($sql);
$query->bindValue(':title', $postTitle);
$query->bindValue(':author', $postAuthor);
$query->bindValue(':content', $postContent);
$query->bindValue(':editDate', $postTime);
$query->bindValue(':postID', $id);
$query->execute();
header('Location: adminPanel.php');
}
}
?>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../sources/css/style.css">
<script type="text/javascript" src="../sources/scripts/time.js"></script>
<script type="text/javascript" src="../sources/scripts/scroll.js"></script>
</head>
<body onload="timeLine(); setInterval('timeLine()', 1000 )">
<header>
<div class="menu">
<ul>
<li> Blog </li>
<li> Archives </li>
<li> Contact </li>
<li id="#addPost"> Add Post </li>
<li id="#editPost"> Edit Post </li>
<li id="#deletePost"> Delete Post </li>
<li id="showBlogContent"> Hide Blog </li>
<li id="menuRightLogin"> Logout </li>
<li id="menuRightDate"><?php echo date('jS F Y') . ' '; ?><span id="clock"> </span></li>
</ul>
</div>
</header>
<div id="showBlog" style="display: block;">
<div class="container">
<div class="postsContainer">
<?php if (isset($error)) { ?>
<p id="error"><?php echo $error ?> </p>
<?php } ?>
<form action="editPostPanel.php" method="post">
<input type="text" name="post_title" value="<?php echo $post['post_title'];?>"/>
<input type="text" name="post_author" value="<?php echo $post['post_author'];?>"/>
<br/>
<br/>
<textarea name="post_content" rows="15" cols="90"><?php echo $post['post_content'];?></textarea>
<br/>
<br/>
<input type="submit" value="Wyślij post"/>
</form>
</div>
</div>
<footer>
<small> © Copyright 2015, n3stis </small>
</footer>
</div>
</body>
</html>
<?php
} else {
echo 'Error';
} }
else {
echo 'Error';
}
When I send a form I get this:
Notice: Undefined index: id on line 7
I will be very greatfull for yours help :)
change
$id = $_GET['id'];
if (isset ($id))
to
if (isset ($_GET['id'])) {
$id = $_GET['id'];
Your form doesn't have the id parameter in it. You need to change
<form action="editPostPanel.php" method="post">
to:
<form action="editPostPanel.php?id=<?php echo $id; ?>" method="post">
This is in addition to correcting the isset check that the other answers noted:
if (isset($_GET['id'])) {
$id = $_GET['id'];
While I don't have your line numbers, I'd guess that line 7 is $id = $_GET['id'];. This indicates that you don't have a GET (query) param called id set. To fix that Notice, you probably want to swap the two lines as follows:
if (isset($_GET['id'])){
$id = $_GET['id']
But all that will do is start echoing 'Error' back to you. You'll also want to figure out why your line editPostPanel.php?id='.$post['post_id'] is not apparently setting the id as desired.

Sort Foreach Loop after ID

Is it possible to sort the result of a foreach loop after the ID? With the highest ID first and so on... Since it's articles I want the highest ID (newest) to be first :)
My code:
include_once('includes/connection.php');
include_once('includes/article.php');
$article = new Article;
$articles = $article->fetch_all();
?>
<html>
<head>
<title>CMS</title>
<link rel="stylesheet" href="assets/style.css" />
</head>
<body>
<div class="container">
CMS
<ol>
<?php foreach ($articles as $article) { ?>
<li>
<a href="article.php?id=<?php echo $article['article_id']; ?>">
<?php echo $article['article_title']; ?>
</a>
- <small>
Posted <?php echo date('l jS', $article['article_timestamp']); ?>
</small>
</li>
<?php } ?>
</ol>
<br />
<small>Admin Login</small>
</div>
</body>
</html>
You're looking for sorting the array $articles according to article_id field - which can be done using the function usort.
Example:
<?php
function cmp($a, $b)
{
if ($a['article_id'] == $b['article_id']) {
return 0;
}
return ($a['article_id'] < $b['article_id']) ? -1 : 1;
}
usort($articles, "cmp");
foreach ($articles as $article) {
echo "$article: ". $article['article_id']." \n";
}

receiving either value for the navigation menu in php

I have two navigation one is in the header and the other is in the same page, now what I want is to do is be able to pull all the data from the table product a specific product from the sub category when I click the sub category. what I have now, is when I click on the menu that is on the header page that I have included in every page I get the product listed but the menu that is on product page produce an error that the foreach is empty. when I use my other function to pull all the sub category it works fine but I want to pull only the sub category that belong to that particular main category. the code below will make more sense.
header Page:
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');?>
<?php require_once("initi.php");?>
<html>
<head>
<title></title>
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/main.css" />
<link rel="stylesheet" href="css/footer.css" />
<script type="text/javascript" src="/ghaniya.com/javascript/jqu.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".logbtn").click(function(){
$("#login2").hide("show");
$("#login1").slideToggle("slow");
$(this).toggleClass("active");
});
$(".logbtn2").click(function(){
$("#login1").hide("show");
$("#login2").slideToggle("slow");
$(this).toggleClass("active");
});
});
</script>
<style type="text/css">
div#login1{
background-color:#efebee;
margin:0 auto;
width:100%;
display:none;
height:100px;
}
div#login2{
background-color:#f5dce4;
margin:0 auto;
width:100%;
display:none;
height:100px;
}
.size{width:960px; }
.flotl{float:left; font-size:11px; text-decoration:none; height:30px; margin-left:20px;}
div#centerl{ width:960px; margin:0 auto; }
</style>
</head>
<body>
<div id="head">
<div class="size center">
<img src="img/logosmall.png">
<ul id="mainLink">
<li><a class="logbtn">Women</a></li><li><a class="logbtn2" href="#">man</a></li><li>Beauty</li><li>Gifts</li><li>Perfumes</li>
</ul>
<div id="loginBox">
<h3>REGISTER | SIGN IN</h3>
</div>
<div id="search">
<input type="submit"/><input type="text" value="Search"/>
</div>
<div id="bag"></div>
</div>
</div>
<div id="login1" >
<div id="centerl">
<ul class="flotl" >
<?php
$cata = Catagory::find_all();
foreach($cata as $catag){?>
<li><?php echo $catag->name; ?></li>
<?php }?>
</ul>
</div>
</div>
Product Page:
<?php require_once("includes/head.php"); ?>
<?php
$cata_id = "";
$subcat ="";
if(isset($_GET['catid']))
{
$cata_id = $_GET['catid'];
$product = Product::find_by_cata_id($cata_id);
}
elseif(isset($_GET['subcat']))
{
$subcat =$_GET['subcat'];
$subcat = SubCata::find_by_cata_id(1);
print_r($subcat);
}
?>
<div class="cBoth"></div>
<div id="contentEveryWhere" class="center">
<div id="cata">
<div id="leftNoticeBoard"></div>
<ul id="catagories">
<h1>CLOTHING</h1>
<?php foreach($subcat as $sub){ ?>
<li><?php echo $sub->name; ?></li>
<?php } ?>
</ul>
</div>
<div id="products">
<div id="catatitle">
<ul>
<li>Home ></li><li>Women ></li><li>Coat<li>
</ul>
<h1>Coat</h1>
<p class="floatl">Sort items by Price: High | Low View as: <img src="#" alt="icon png"/> |<img src="#" alt="icon png"/></p>
</div>
<ul id="product">
<?php $product = Product::find_by_cata_id($cata_id);?>
<?php foreach($product as $pro){?>
<?php $image = Image::find_by_product_id( $pro->product_id);?>
<li>
<?php if(isset($image->filename)){ ?>
<img src="/ghaniya.com/img/products/<?php echo $image->filename;?>"/>
<?php } ?>
<h2><?php echo $pro->name;?></h2>
<h3> <?php echo $pro->product_desc;?></h3>
<h4><?php echo $pro->price;?></h4>
</li>
<?php } ?>
</ul><!--end of product list-->
</div> <!--end of products div-->
</div><!--end of contentEveryWhere div-->
<div class="cBoth"></div>
<?php require_once("includes/footer.php"); ?>
Warning: Invalid argument supplied for foreach() in /Users/mughery/Website/ghaniya.com/product.php on line 25
The problem is quite simple:
if(isset($_GET['catid']))
{
$cata_id = $_GET['catid'];
$product = Product::find_by_cata_id($cata_id);
}
elseif(isset($_GET['subcat']))
{
$subcat =$_GET['subcat'];
$subcat = SubCata::find_by_cata_id(1);
}
That means you're only setting $subcat if, and only if $_GET['catid'] isn't set and $_GET['subcat'] is. In all other cases $subcat is an empty string, not an array. Just add a line like:
$subcat = (is_array($subcat) ? $subcat : SubCata::find_by_cata_id(1));
//or:
$subcat = (is_array($subcat) ? $subcat : array());
And you'll be good to go
Also, this:
$subcat =$_GET['subcat'];
$subcat = SubCata::find_by_cata_id(1);
Doesn't really make sense to me, I think you need something like:
elseif(isset($_GET['subcat']))
{
$subcat =SubCata::find_by_cata_id($_GET['subcat']);
}
$subcat = (is_array($subcat) ? $subcat : SubCata::find_by_cata_id(1));
If not, regardless of the subcat parameters actual value, your fetching all data for id 1...
When using a foreach, the first argument has to be a array.
You could change the code to:
<?php
if( is_array( $subcat ) )
foreach($subcat as $sub){
?>
4 line:
<?php
$subcat = array();
?>

Categories