I've small blog users can add new post and others can comment on this post ( Post is working perfectly, comments is working too )
all posts is showing and all comment is showing but each Separated , how can I display it related.
function getPostInfoo(){
if($this->num_members < 0){
$q = "SELECT * FROM ".TBL_POSTS;
$result = mysqli_query($this->connection, $q);
$fields = array();
while($fetch=mysqli_fetch_array($result)){
echo "
<h3>".$fetch['post']."</h3>
<p>".$fetch['username']."</p>";
}
$this->num_members = mysqli_fetch_array($result);
}
//return
return $fields;
}
function getComment(){
$q = "SELECT ".TBL_POSTS.".*, ".TBL_COMMENTS.".*
FROM ".TBL_POSTS."
INNER JOIN ".TBL_COMMENTS." ON ".TBL_COMMENTS.".postid=".TBL_POSTS.".postid";
$result = mysqli_query($this->connection, $q);
/* Error occurred, return given name by default */
if(!$result || (mysqli_num_rows($result) < 1)){
return NULL;
}
$fields = array();
while($fetch=mysqli_fetch_array($result)){
$fields[] = "<p><a href='#'>".$fetch['username'].": </a>".$fetch['comment']."<br>
<small class='text-muted'>".$fetch['cmntdate']."</small>
</p>
";
}
/* Return result array */
return $fields;
}
test.php
echo "<div>";
$myList2 = $database->getPostInfoo();
if (is_array($myList2) || is_object($myList2)){
foreach($myList2 as $arrayItem2){
echo $arrayItem2;
}
}else {
echo "No Posts yet.";
}
echo "</div>
<div>";
$myList = $database->getComment();
if (is_array($myList) || is_object($myList)){
foreach($myList as $arrayItem){
echo $arrayItem;
}
}else {
echo "No comments yet.";
}
<form method='post' action='functions.php' method='POST'>
<div class='form-group' >
<textarea class='form-control' name = 'comment' placeholder='Write Comment'></textarea>
<input type='hidden' name='postid' value='1'>
<input type='hidden' name='comment_sub' value='1'>
<input type='submit' value='Add Comment!'>
</div>
</form>
</div>";
what I need to do is to display each comments on its own post & show comment textarea on each post
Please see the image https://i.stack.imgur.com/A4D55.jpg
You need to be getting one post at a time and then fetch its comments.
So your test.php should look this test.php?id=post_id
Where post_id is the unique identifier of your post based on your db structure
Could be e.g is 1 or 2 or if you are using auto-increment id
Then you can add the following code to at the beginning of your test.php to get the post id
$post_id = isset($_GET['id']) ? $_GET['id'] : '';
The fetch the post and it's comment from your table using the value of $post_id
Hope it helps
Try this function:
function getPostsInfo(){
$q = "SELECT ".TBL_POSTS.".`id`,".TBL_POSTS.".`post`, ".TBL_POSTS.".`username`, ".TBL_COMMENTS.".`username` as comment_username, ".TBL_COMMENTS.".`comment`, ".TBL_COMMENTS.".`cmntdate`
FROM ".TBL_POSTS."
LEFT JOIN ".TBL_COMMENTS." ON ".TBL_COMMENTS.".postid=".TBL_POSTS.".postid";
$result = mysqli_query($this->connection, $q);
$posts = [];
while($fetch=mysqli_fetch_array($result)){
if(isset($posts[$fetch["id"]])){
$posts[$fetch["id"]]["comments"][] = [
"username" => $fetch["comment_username"],
"comment" => $fetch["comment"],
"cmntdate" => $fetch["cmntdate"]
];
}else{
$posts[$fetch["id"]] = [
"post" => $fetch["post"],
"username" => $fetch["username"],
"comments" => [[
"username" => $fetch["comment_username"],
"comment" => $fetch["comment"],
"cmntdate" => $fetch["cmntdate"]
]]
];
}
}
return $posts;
}
Related
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>;
}
So i've got this input where i can put a username in and it'll use $_POST to get what i put in the input box however i'm struggling on how to get all the information from my database relating to this username and displaying it?
<form action="ProcessPlayerSearch.php" method="POST">
<div class="input-group input-group-sm">
<input type="text" name="SearchUser" id="SearchUser" class="form-control">
<span class="input-group-btn">
<button type="submit" class="btn btn-info btn-flat" type="button">Search</button>
</span>
</div>
</h4>
</form>
This is my ProcessPlayerSearch.php
function GetPlayerSearch(){
global $database;
$user = $_POST['Searchuser'];
$q = "SELECT * FROM NEWPlayerInfo WHERE player=$user";
$result = $database->query($q);
/* Error occurred, return given name by default */
$num_rows = mysqli_num_rows($result);
if(!$result || ($num_rows < 0)){
echo "User not found";
return;
}
if($num_rows == 0){
echo "User not found";
return;
}
for($i=0; $i<$num_rows; $i++){
mysqli_data_seek($result, $i);
$row=mysqli_fetch_row($result);
$uuid = $row[0]; //UUID
$player = $row[1]; //player
$kicks = $row[2]; //kicks
$bans = $row[3]; //bans
echo "$uuid<br>";
echo "$player<br>";
echo "$kicks<br>";
echo "$bans<br>";
}
}
and the error i get is
mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in
however i don't get why it would return a boolean? as i've entered a string into the input? Any help thanks.
Since you are displaying a single user data, Using for loop would be a little overhead. Now we return the array containing the user info from your function:
function GetPlayerSearch($user){
global $database;
$user = $_POST['Searchuser'];
$q = "SELECT * FROM `NEWPlayerInfo` WHERE player='$user'";
$result = $database->query($q);
/* Error occurred, return given name by default */
$num_rows = mysqli_num_rows($result);
$res =mysqli_fetch_assoc($result);
$userinfo =array();
if($num_rows>1){
$userinfo[] = $res;
}else{
$userinfo[] = array();
}
return $userinfo;
}
Now search the user:
if(isset($_POST['SearchUser'])){
$user = isset($_POST['SearchUser'])? $_POST['SearchUser']:'';
$player = GetPlayerSearch($user);
}
Display a single player data:
if(!empty($player)){ //you can also use array_filter()
echo $player['UUID'].'<br>';
echo $player['player'].'<br>';
echo $player['kicks'].'<br>';
}else{
echo 'No user';
}
I have a search function on my website with 4 checkboxes. These are then pasted to the next page where I want to find all products which match the criteria of the check boxes.
As I have 4 check boxes I want to use 4 'ands' but I believe 3 is the max (?)
How can I get around this so it searches to see if all products are matched?
HTML Form
<div id = "search">
<form name = search action = "search.php" method = "POST">
<p class = "big"> Refine Menu </p>
<hr>
<input type = "text" name = "search" placeholder = "Search for an item" size = "12">
<input type = "submit" value = "Go">
<br><br>
<input type = "checkbox" name = "vegetarian"> Vegetarian
<br><input type = "checkbox" name = "vegan"> Vegan
<br><input type = "checkbox" name = "coeliac"> Coeliac
<br><input type = "checkbox" name = "nutFree"> Nut free
</form>
</div>
PHP
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = NULL;
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = NULL;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = NULL;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = NULL;
}
$sql = "SELECT * FROM products WHERE vegan = '$vegan' and nutFree = '$nutFree' and vegetarian = '$vegetarian' and coeliac = '$coeliac'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
I've tried a number of different thing but I don't know the correct syntax for the sql.
NOTE: In my database whether it meets the requierment on it is saved as either a 1 or 0 that is why I changed it from 'on' or 'off'
Rather than a large, unmaintainable chain of if statements, you might consider something similar to the following, which will dynamically build up your query depending on which of your required fields have been checked in your form:
<?php
$search_fields = array( 'vegetarian', 'vegan', 'nutFree', 'coeliac', ...);
$ands = array( '1' => '1');
foreach($search_fields as $req)
{
if(isset($_POST[$req]) && $_POST[$req] != '')
{
$ands[$req] = "$req = '1'";
}
}
$and_part = implode(" AND ", $ands);
$query = "select .... from ... WHERE $and_part ... ";
?>
I managed to solve my problem. I was mistaken when I posted the question because the reason I thought my sql statement wasn't working was because there were too many ands and I didn't see that rather my sql didn't do what I thought it should.
Here is what I changed it to or it has set values or the check boxes ticked but always the ones which aren't to be either or.
Thanks for everyone's help!
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = " ";
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = " " ;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = " " ;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = " ";
}
$sql = "SELECT * FROM products WHERE (vegan = '$vegan' or vegan = 1 xor 0) and (nutFree = '$nutFree' or nutFree = 1 xor 0) and (vegetarian = '$vegetarian' or vegetarian = 1 xor 0) and (coeliac = '$coeliac' or coeliac = 1 xor 0)";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
PHP's NULL have no significance when converted to a string (the SQL query), they will evaluate to empty and your query will look like nutFree = '' and vegetarian = '' and coeliac = ''.
If those fields are 0 in the database, you must set the variables to 0 then.
On a second case, if they are NULL in the database, you must change both your query and the way you define NULL here.
First, those string wrappers should go away. You don't need them for numbers anyway, those are supposed to wrap strings only:
$sql = "SELECT * FROM products WHERE vegan = $vegan and nutFree = $nutFree and vegetarian = $vegetarian and coeliac = $coeliac";
And then instead of setting the variables to NULL, you will set them to the string "NULL".
$nutFree = "NULL";
This will make NULL show on the SQL query as its expected to.
i want to update the fields below but my form is not working. it is not storing data what should i do. i used jquery accordion fo r the fields so it will click the item he wants to edit then update the fields then submit. but it is not working.
VIEW
foreach($people as $row){
echo "<h3>".$row->service."</h3>";
echo "<form action='".base_url()."some_controller/updateCI' method='post'> <div>Service ID: <input type=text name=id value='".$row->id."' size=27px/><br>Service Name: <input type=text name=name value='".$row->service."'><input type='button' class='classname' value='Save'/></form></div>";
}
?>
CONTROLLER
public function updateCI(){
$this->load->model('some_model');
$id = $this->input->post('id');
$servName = $this->input->post('name');
$success = $this->some_model->updateCI($id,$servName);
if($success == TRUE)
$this->editCI_page(TRUE);
else $this->editCI_page(FALSE);
}
MODEL
public function updateCI($id,$servName){
//$name = $this->db->escape_str($name);
$appID = $this->db->escape_str($id);
$ciName = $this->db->escape_str($servName);
$queryStr = "UPDATE appwarehouse.service SET id='$appID',service='$ciName' WHERE id = '$appID';";
$query = $this->db->query($queryStr);
return $query;
}
You can do something like this in your model:
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
I would recommend you to use the active record which are available for codeigniter. For more information visit the below link:
http://ellislab.com/codeigniter/user-guide/database/active_record.html
I am trying to build admin side of small website which consists of 2 pages: index.php and update php. On index.php I run query, that per-fills html form with data from database, which works fine.
Then I send data via $_POST to update.php page, where I try to get those values into variables and then make an update query. Which fails. I suspect something is wrong with $_POST array - some values are messed up or empty, but I don't understand why.
Here is the code for index.php:
<?php
if (!isset($page_id)) {
echo " <p>Please select page to be edited:</p>";
$query = mysql_query("SELECT page_id, title FROM pages");
$res = mysql_fetch_array($query);
do {
printf("<p><a href='index.php?page_id=%s'>%s</a></p>", $res['page_id'], $res['title']);
} while ($res = mysql_fetch_array($query));
} else { $query = mysql_query("SELECT * FROM pages WHERE page_id = '$page_id'");
$res = mysql_fetch_array($query);
require_once 'parts/form.php';}
?>
This is code for update.php:
<?php
//Here I try to get POST values and assign them to variables for update
//Ths is validation that those values are not empty,
require_once 'parts/guard.php';
if (isset($_POST['page_id'])) {
$page_id = $_POST['page_id'];
}
if (isset($_POST['title'])) {
$title = $_POST['title'];
}
if ($title == '') {
unset($title);
}
if (isset($_POST['description'])) {
$description = $_POST['description'];
}
if ($description == '') {
unset($description);
}
if (isset($_POST['keywords'])) {
$keywords = $_POST['keywords'];
}
if ($keywords == '') {
unset($keywords);
}
if (isset($_POST['text'])) {
$text = $_POST['text'];
}
if ($text == '') {
unset($text);
}
//variables are set
require_once 'parts/meta.php';
?>
<?php
//Here is all the values exist, the query is executed.
//Obviousely this query works in phpmyadmin, but not here - some fields come empty or messed up????
if (isset($title) && isset($keywords) && isset($description) && isset($text) && isset($page_id)) {
$query = mysql_query("UPDATE pages SET title = '$title', description = '$description', keywords = '$keywords', text = '$text' WHERE page_id = '$page_id' ");
if ($query == TRUE) {
echo "<p>Page Updated</p>";
echo "<p><a href = 'http://localhost:8888/travel.ru/admin/index.php'>
Edit Another Page</a></p>";
} else {
echo "<p>Page Is Not Updataed</p>";
}
} else {
echo "<p>You Left Some Fields Empty. Page Will Not Be Updated.</p>";
}
?>
And this is the form I use:
<form name="update" action = "update.php" method= "post">
<p> Page Name<br>
<input value = "<?php echo $res['title']; ?>" type = "text" name = "title"></p>
<p> Page Description<br>
<input value = "<?php echo $res['description']; ?>" type = "text" name = "title"></p>
<p> Page Keywords<br>
<input value = "<?php echo $res['keywords']; ?>" type = "text" name = "title"></p>
<p> Page Content<br>
<textarea type = "text" name ="text" cols = "68" rows = "15"><?php echo $res['text']; ?>
</textarea></p>
<input type = "hidden" name="page_id" value =$res[page_id]>
<p><input type = "submit" name ="submit" value ="Save Changes" id="submit"</p>
</form>
Any help will be most appreciated as I dont have a clue why I have this problem?
Most of your form fields are named title. Thus you don't actually have a field called description or page_id or keywords.
Mate also raises a valid point.
Try added php tag to your input value
<input type = "hidden" name="page_id" value ="<?php echo $res['page_id']; ?>" />
As mentioned Amadan , also check the names for all controls in your form.