hello I have a problem with my PHP code I have a function to get a comment for each post on my website the function in working but the data is in a wrong place
as you can see in the picture the comments are in the wrong place and I need to move them to the place in the picture
<?php
class posts{
static function getposts(){
$query = database::query("select * from posts join frinds on frinds.user1_id = posts.user_id or
frinds.user2_id= posts.user_id where frinds.user1_id = ? or frinds.user2_id =
?",array($_COOKIE['uid'],$_COOKIE['uid']));
if($query->rowCount() > 0){
$rows=$query->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$id = $row['user_id'];
// if($id != $_COOKIE['uid']){
if($id != $_COOKIE['uid']){
$post_text = $row['text'];
$id= $row['id'];
echo posts::postbody($id,$post_text);
}
}
if($id == $_COOKIE['uid']){
$query = database::query("select * from posts where user_id = ?",array($_COOKIE['uid']));
if($query->rowCount() > 0){
$rows=$query->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$post_text = $row['text'];
echo posts::postbody($row['id'],$post_text);
}
}
}
}
}
static function postbody($id,$post_text){
$body =" <div class='post'>
<div class='post_texts' ><p class='post_text'>$post_text</p>
</div>
<div class='comments'>
" .posts::comments($id)."
</div>
<form method='post'>
<input type='text' name='comment'>
<input type='submit' name='addcoment'>
</form>
</div> ";
return $body;
}
static function creatpost(){
$query = database::query("INSERT INTO `posts` (`user_id`, `text`) VALUES (?,
?);",array($_COOKIE['uid'],$_POST['text']));
}
static function comments($id){
$query = database::query("select * from comments join posts on comments.post_id = posts.id where
posts.id = ?",array($id));
if($query->rowCount() > 0){
$rows=$query->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$comment = $row['comment'];
echo"<p>$comment</p>";
}
}
}
}
?>
as you can see
is where i have the post and <div class'comment'>
where I should have the comments
The issue is that your static method call posts::comments($id) already uses echo to output the comments. While the post body is stored in the variable $body which is echoed only later on.
You need to change you code such that the comments are not immediately echoed when they are collected from the database. But that they are either placed in an output buffer or returned to the calling scope. So that they can become part of the actual post body you try to create.
In other words: when calling posts::comments($id) you expect to get something back which you try to concatenate to your $body variable. But your method never returns something. It only creates output that is send to the client immediately. So it never gets part of that variable where you try to collect the post body.
UPDATE:
How can you "collect" the comments to return them all together?
static function comments($id){
$query = database::query("select * from comments join posts on comments.post_id = posts.id where
posts.id = ?",array($id));
if($query->rowCount() > 0) {
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
$comment = [];
foreach ($rows as $row) {
$comments[] = $row['comment'];
}
return implode("\n", $comments);
}
return "<p>No comments so far...</p>;
}
Related
I am working on a small forum and I am currently trying to display the forum topics in a separate file. For whatever reason when I open the file it is displaying these errors:
Notice: Undefined index: cid in C:\xampp\htdocs(A)Book 2.0\Bootstrap\topics.php on line 19
Notice: Undefined index: scid in C:\xampp\htdocs(A)Book
2.0\Bootstrap\topics.php on line 20
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result,
boolean given in C:\xampp\htdocs(A)Book
2.0\Bootstrap\content_function.php on line 41
I've tried to use an isset function for the variables, but it hasn't worked. I'm calling the variables from a separate functions file.
Here's the code displaying the topics:
<?php
session_start();
require_once ('../db.php');
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
exit; //<--- add this
}else {
// Makes it easier to read
$first_name = $_SESSION['first_name'];
$last_name = $_SESSION['last_name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
}
include ('content_function.php');
$cid2 = $_GET['cid'];
$scid2 = $_GET['scid'];
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Topics</title>
<link href="main.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class = "content">
<?php
/*
$select = mysqli_query($mysqli, "SELECT * FROM categories");
while($row = mysqli_fetch_assoc($select)){
echo "<h1>", $row['category_title']."</h1>" ;
}*/
disptopics($cid2, $scid2, $mysqli);
/*if (isset($_GET['cid'], $GET['scid'])){
disptopics();
}*/
?>
</div>
</body>
</html>
Also, here is the code for the functions:
<?php
require '../db.php';
function dispcategories($mysqli){
$select = mysqli_query($mysqli, "SELECT * FROM categories");
while($row = mysqli_fetch_assoc($select)){
echo "<table class = 'category-table'";
echo "<tr><td class= 'main-category'colspan='2'>".$row['category_title']."</tr></td>";
dispsubcategories($row['cat_id'], $mysqli);
echo "</table>";
}
}
function dispsubcategories($parent_id, $mysqli){
$select = mysqli_query($mysqli, "SELECT cat_id, subcat_id, subcategory_title, subcategory_descr FROM categories, subcategories
WHERE ($parent_id = categories.cat_id) AND ($parent_id = subcategories.parent_id)");
echo "<tr><th width='90%'>Categories</th><th width='10%'>Topics</th></tr>";
while($row = mysqli_fetch_assoc($select)){
echo "<tr><td class='category_title'><a href='topics.php/".$row['cat_id']."/".$row['subcat_id']."'>
".$row['subcategory_title']."<br/>";
echo $row['subcategory_descr']."</a></td>";
echo "<td class='num-topics'>".getnumtopics($parent_id, $row['subcat_id'], $mysqli)."</td></tr>";
}
}
//Displays categories
function getnumtopics($cat_id, $subcat_id, $mysqli){
$select = mysqli_query($mysqli, "SELECT category_id, subcategory_id FROM topics WHERE ".$cat_id." = category_id
AND ".$subcat_id." = subcategory_id");
$get = mysqli_num_rows($select);
return $get;
}
//Displays Topics Within categories
function disptopics($cid, $scid, $mysqli){
$select = mysqli_query($mysqli, "SELECT topic_id, author, title, date_posted, views, replies FROM categories, subcategories, topics
WHERE ($cid = topics.category_id) AND ($scid = topics.subcategory_id) AND ($cid = categories.cat_id)
AND ($scid = subcategories.subcat_id) ORDER BY topic_id DESC");
if(mysqli_num_rows($select) != 0) {
echo "<table class='topic-table'>";
echo "<tr><th>Title</th><th>Posted By</th><th>Date Posted</th><th>Views</th><th>Replies</th></tr>";
while($row = mysqli_fetch_assoc($select)){
echo "<tr><td><a href='readtopic.php/".$cid."/".$scid."/".$row['topic_id']."'>
".$row['title']."</a></td><td>".$row['author']."</td><td>".$row['date-posted'].".</td><td>".$row['views']."</td>
<td>".$row['replies']."</td></tr>";
}
echo "</table>";
} else {
echo "<p>This category has no topics yet! <a href='newtopic.php/".$cid."/".$scid."'> Add a new one!</a></p>";
}
}
?>
I've looked over each file multiple times and used a code checker that says I have no syntax errors.
$_GET is an array, and if the user haven't defined a scid=something in the query string, then $_GET['scid'] is undefined. There, you got an undefined index Notice.
You should test if isset($_GET['scid']) before trying to read it's value.
from where this $_GET['cid'] and $_GET['scid'] is getting data please check echo $_GET['cid'] or you also do var_dump($_GET);
<?php
session_start();
$conn =new mysqli("localhost","root","","registration");
$userid=isset($_POST['userid'])?$_POST['userid']:'';
//$re['success']=false;
$sql="call regtask2('$userid')";
$res=mysqli_query($conn,$sql);
$array = array();
if($res) {
while($row = mysqli_fetch_assoc($res))
{
$array[]=$row ;
$re['success']=true;
$re['userObj']['firstname'] = $row['firstname'];
}
}
else {
$re['success']=false;
}
if(isset($_SESSION['username']))
{
$sem=isset($_POST['sem'])?$_POST['sem']:'';
$fname=isset($_POST['fname'])?$_POST['fname']:'';
$year=isset($_POST['date'])?$_POST['date']:'';
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
$re = array();
while ($row = mysqli_fetch_assoc($query))
{
print_r($row);
//$options['userObj'][]=$row;
}
}
echo json_encode ($re);
return;
?>
This is my full PHP code in this I need two json responses,
1> when I refresh the page
$sql="call regtask2('$userid')";
This query has to work and pass the response to the ajax, then I am using click button. When I use click button this query has to work and pass the response
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
I this is poosible?
3 options:
Just split your php code. On refresh, load script1.php and for your other ajax call, load script2.php.
You will need to set identifiers for your calls. In your ajax, add an "is_submit=true" to the query. In your php, check that value.
Assign your return value to $return and return that.
It's simple just add second query result to your previous json !, also consider adding some validation into user input to prevent sql injection
getting userid from $_POST is really bad idea
<?php
session_start();
$conn =new mysqli("localhost","root","","registration");
$userid=isset($_POST['userid'])?$_POST['userid']:'';
//$re['success']=false;
$sql="call regtask2('$userid')";
$res=mysqli_query($conn,$sql);
$array = array();
$re = array();
if($res) {
$re['success']=true;
while($row = mysqli_fetch_assoc($res))
{
$array[]=$row ;
$re['userObj']['firstname'] = $row['firstname'];
}
}
else {
$re['success']=false;
}
if(isset($_SESSION['username']))
{
$sem=isset($_POST['sem'])?$_POST['sem']:'';
$fname=isset($_POST['fname'])?$_POST['fname']:'';
$year=isset($_POST['date'])?$_POST['date']:'';
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
while ($row = mysqli_fetch_assoc($query))
{
$re['userObj'][]=$row;
//$options['userObj'][]=$row;
}
}
echo json_encode ($re);
return;
?>
i have the following information displayed
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0)
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
?>
as you can see i have created a game_details page which will display that specific Game_id when the image is clicked
im having trouble understanding how to pull the data out from that game_id in sql on the other page.
here is my attempt on the game_details page
<?php
if (!isset($_GET['$game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id={$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['$game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
This attempt is giving me the "invalid category ID" error
Would appreciate help
There are a few issues with your code.
Let's start from the top.
['$game_id'] you need to remove the dollar sign from it in $_GET['$game_id']
Then, $row['$game_id'] same thing; remove the dollar sign.
Then, game_id={$game_id}' will throw a syntax error.
In your first body of code; you should also use proper bracing for all your conditional statements.
This one has none if (mysqli_num_rows($result) > 0) and will cause potential havoc.
Rewrites:
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0){
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
}
?>
Sidenote for WHERE game_id='{$game_id}' in below. If that doesn't work, remove the quotes from it.
WHERE game_id={$game_id}
2nd body:
<?php
if (!isset($_GET['game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id='{$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
Use error checking tools at your disposal during testing:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
You want to be using $_GET['gameid'] as that's the parameter you passed.
You are calling for game_id when the link to go to game_details.php has the variable gameid. Either change the parameter in the link to game_id or call for gameid in your $_GET['$game_id'].
Also, as Fred -ii- said, take out the dollar sign in $_GET['$game_id']
I used the following code to to get list of users facebook friends and ccheck it against users in an app database. This code would return the users of the app, who are Facebook friends of the user.
$friends_set = '(';
foreach($friends["data"] as $value) {
$friends_set .= $value['id'].',';
}
$new_set = preg_replace('/,$/',')',$friends_set);
$res = mysql_query("SELECT * from user AS u, upload AS up WHERE u.fb_id IN $new_set AND u.fb_id=up.user_id") or die(mysql_error());
while($row = mysql_fetch_array($res)) {
echo $row['fb_id']. "". $row['first_name'];
echo "<br>";
}
$data['top_friends']=$res;
$this->load->view('myview');
This code works. It is in a controller of my codeigniter application and it successfully echos the correct data onto the page.
However now I need to print the result of the query in a for each statement in my view like this:
<?php foreach ($top_friends as $me) : ?>
<div >
<p><?php echo $me['first_name']; ?></p>
<?php endforeach; ?>
However when I try getting the query results in the view using the for each it doesn't work.
How do i fix this?
You could try it the codeignitor way, Create a model function say get_top_friends and i assume that you are passing a comma separated string as argument like $fb_id = '45,65,78,89'. Say facebook_model is the name of the model then :
class Facebook_model extends CI_Model{
//other functions and constrcutor here
//function to get the top friends
function get_top_friends($fb_id){
$fbId = explode(",",$fb_id)
$this->db->select('*');
$this->db->where_in('fb_id',$fbId);
$this->db->order_by('points','desc');
$this->db->limit(10);
$query = $this->db->get('user');
if ($query->num_rows() < 1) return FALSE;
return $query->result_array();
}
}
And make change in your code as below:
$friends_set = '';
foreach($friends["data"] as $value) {
$friends_set .= $value['id'].',';
}
$new_set = preg_replace('/,$/',')',$friends_set);
$res = $this->facebook_model->get_top_friends($new_set);
$data['top_friends']=$res;
$this->load->view('myview',$data);
And now in view you can try
foreach ($top_friends as $me){
echo $me['first_name'];
}
[Updated for user ]
If you want to do it as in your question : then try,
$result = array();
while($row = mysql_fetch_array($res)) {
$result[] = $row;
}
$data['top_friends']=$result;
$this->load->view('myview',$data);//pass data to view
Basically I have two files, group.php and class.Groups.php
I am trying to print out the 20 last messages posted to the group, however I cannot figure it out as I am pretty new to this! Any help welcomed.
The problem I am having is that the function I am calling is inside a class. Just dont know how to do the while loop and printing.
Would also welcome suggestions and feedback on my code structure & layout.
Thanks.
class.Groups.php
<?php include("config.php");
// Get Group Details
class Group {
var $groupID;
var $groupName;
var $groupDescription;
var $groupMessage;
function group_details($ID) {
$group_details = mysql_query("SELECT * FROM Groups WHERE GroupID = '".$ID."' LIMIT 1");
if (mysql_num_rows($group_details) == 1) {
$group_details_row = mysql_fetch_assoc($group_details);
$this->groupID = $group_details_row ['GroupID'];
$this->groupName = $group_details_row ['Name'];
$this->groupDescription = $group_details_row ['Description'];
}
}
function group_member($ID) {
$group_member = mysql_query("SELECT * FROM GroupMembers WHERE GroupID = '".$ID."' AND UserID = '".$_SESSION['UserID']."' LIMIT 1");
if (mysql_num_rows($group_member) == 1) {
return 1;
}
else {
return null;
}
}
function group_messages($ID) {
$group_messages = mysql_query("SELECT * FROM GroupMessages INNER JOIN Users ON Users.UserID = GroupMessages.UserID WHERE GroupID = '".$ID."' LIMIT 20");
while ($group_messages_row = mysql_fetch_assoc($group_messages)) {
$this->groupMessage = $group_messages_row['Message'];
}
}
}
?>
group.php
<?php include("includes/class.Groups.php");
$group = new Group;
$group->group_details($_GET['ID']);
if ($_SESSION['LoggedIn'] == 1) {
if ($group->group_member($_GET['ID'])) {
include("includes/header.php"); ?>
<div id="container">
<div id="menu"><?php include("includes/sidebar.php"); ?></div>
<div id="main">
<h2><?php echo $group->groupName; ?></h2>
<p><?php echo $group->groupDescription; ?></p>
<h3>Messages</h3>
<?php
while ($group->group_messages($_GET['ID'])) {
echo $group->groupMessage;
}
?>
</div>
</div>
<?php
}
else {
echo "You are not member of this group.";
}
}
?>
You cannot use $group->group_messages() inside a while, because:
It doesn't return anything (return evaluates to false)
It goes through all the rows in one call, while you are expecting it to return one row at a time
You can rewrite your class code to collect all rows in a variable, return it and the iterate on it using foreach loop
// class.Groups.php
function group_messages($ID) {
$group_messages = array();
$group_messages = mysql_query("SELECT * FROM GroupMessages INNER JOIN Users ON Users.UserID = GroupMessages.UserID WHERE GroupID = '".$ID."' LIMIT 20");
while ($group_messages_row = mysql_fetch_assoc($group_messages)) {
$group_messages[] = $group_messages_row['Message'];
}
return $group_messages;
}
// groups.php
<h3>Messages</h3>
<?php
foreach ($group->group_messages($_GET['ID']) as $group_message) {
echo $group_message;
}
?>
You seem to have an extra curly brace in this chuck of code:
<?php
while ($group->group_messages($_GET['ID'])) {
echo $group->groupMessage; }
} ?>