Echoing out most recent database records? - php

I have a section of my website that reads out data to the user.
My current code reads out data in the same order, even when new records are added; they are added at the end of the data that is being echoed out.
I want to read out the most recent data as I am creating a message board.
CODE:
session_start();
$sess = $_GET['id'];
$profile_query = "SELECT * from forum WHERE postee = $sess";
$profile_queried = mysql_query($profile_query);
while($row = mysql_fetch_array($profile_queried))
{
echo '<div class="each_post"><p>'.$row['content'].'</p></div>';
}
Question: How can I echo data from a database in order of recency? Must I add another field to do this?

Your query should be:
$profile_query = "SELECT * from forum WHERE postee = $sess ORDER BY id DESC"

Related

how to explode array with certain key in php

I'm developing an app about books and I had a table for contents. before, I made a mistake and I split content in myself and insert them in database. after inserting 90 books I had 1000 records and I found out that it was wrong. Now, I create a table of content and I insert all content of every books(every book has a record), so I want to split content with character(*).
but it doesn't work.
It is my Previous code:
$sql2 = "SELECT tblcontent.content
from tblcontent,tblstory
where tblcontent.storyid=tblstory.storyid
and tblcontent.storyid='$storyid'";
$r2 = #mysqli_query($dbLink,$sql2);
$result2 = array();
while($res2 = #mysqli_fetch_assoc($r2))
{
$result2[] = $res2;
}
and I've added this code:
$result2=explode("*",$result2);
and
if(isset($result2)){
echo json_encode(array("result2"=>$result2));
}
But it doesn't work.Thanks in advance

socialmedia status comment system

I am trying to create a post-comment system, with simple php-mysqli, as simple as it is, it does not seem to give me the result in the fashion I want i.e:
---POST MESSAGE----
-----comments-----
Here is the code I used:
<?php
session_start();
include_once('php_includes/db_conx.php');
$user=$_SESSION['user'];
$o =mysqli_query($db_conx, "SELECT post.id,post.post,post.date,post_comments.poster,post_comments.comment,post_comments.date FROM post LEFT JOIN post_comments ON post.id=post_comments.post_id AND post.username='$user' ORDER BY post.date");
while($r=mysqli_fetch_array($o,MYSQLI_ASSOC)){
$status= $r['post'];
$date=$r['date'];
$com=$r['comment'];
$pid=$r['id'];
$poster=$r['poster'];
if(count($pid) > 1){
}
echo $status.'|'.$pid.'|'.$date.'<br>'.$poster.':'.$com.'<hr>';
}
?>
It seems to duplicate the post for each comment for same post.
Not sure am making sense, but i will appreciate an answer.
First, add post id to your query's ORDER BY. That will ensure that your post and all its comments appear together, and only once. (I'd recommend adding post_comments.date as well so your comments will appear in order, but that won't be necessary to get the grouping working.)
... ORDER BY post.date, post.id, post_comments.date
Then keep track of the post id as you go. Echo the post information only when the post id changes.
$id = null; // initialize to null
while ($r = mysqli_fetch_array($o, MYSQLI_ASSOC)) {
$pid = $r['id'];
$status = $r['post'];
$date = $r['date'];
$com = $r['comment'];
$poster = $r['poster'];
if ($pid !== $id) {
echo $status.'|'.$pid.'|'.$date.'<br>'; // new post, so echo post info here
$id = $pid; // $id becomes new post id
}
if ($com) {
echo $poster.':'.$com.'<br>'; // echo comment if present
}
}
One other thing that will probably cause some trouble is that you have selected both post.date and post_comments.date in your query, so I'm not sure which one will be in $r['date']. It would be a good idea to alias at least one of those columns to disambiguate them.

How Can I make a variable global to be accessed on every page in php

I have these two block of codes on one page in different parts of the page any time I try to use $product_id variable on the other segment of the code it is not recongnised. Take a look.
<?php
$cart_table = mysql_query("select * from order_details where memberID='$ses_id' and status='Delivered' and addon_status=''") or die(mysql_error());
$cart_count = mysql_num_rows($cart_table);
while ($cart_row = mysql_fetch_array($cart_table)) {
$order_id = $cart_row['orderid'];
$status = $cart_row['status'];
$product_id = $cart_row['productID'];
$orderdate = $cart_row['ordertime'];
//Query Product table
$product_query = mysql_query("select * from tb_products where productID='$product_id'") or die(mysql_error());
$product_row = mysql_fetch_array($product_query);
//Query treat_period table
}
?>
I want to use $product_id variable on the next php block of code but but it is not recongnised at all. Somebody please help me.
<?php
require_once'session.php';
$query=mysql_query("SELECT * FROM product_addon WHERE memberid='$ses_id' && productID='$product_id'");
while($row=mysql_fetch_array($query))
{
$sta=$row['treat_kind'];
}
?>
PHP lets you use variables throughout the whole file. The reason product_id is not defined is probably because either your query doesn't return any results or product_id is null or blank.
Try this: var_dump($cart_row) right before your query and see if product ID exists and is not empty

PHP MYSQL $_GET['ID'] from table on dynamically generated page

I have a few products stored in a table with auto-incremented ID entitled "product_id".
I have managed to create a page that displays a list of the products names as selected from the db and dynamically created links for each one. Let's say I have product apple. When I click on apple it takes me to view_product_details.php?id=9
But when I click apple, the view_product_details.php page tells me
"Notice: Undefined index: product_id in C:\xampp\htdocs\working\product-website-exercise\view_product_details.php on line 16"
<?php
//$result = mysql_query("SELECT * FROM temaproduct.products WHERE ID = '".mysql_real_escape_string($_GET['product_id'])."'");
$id = $_GET['product_id']; //This is line 16
$result = mysqli_query($conn,"SELECT * FROM products WHERE ID = $id");
echo $result['product_description'];
echo "<br>";
var_dump($result);
?>
I have tried with different queries but can't figure it out, please help me establish the connection properly so I can read the other fields from the table on the view_product_details page, based on product_id.
EDIT: Thank you guys, with your help, here is the code that works now, if everybody needs this snippet:
<?php
$id = intval($_GET['id']);
$sql = mysqli_query($conn,"SELECT * FROM products WHERE product_id = ".$id);
if(mysqli_num_rows($sql)){
$product_data = mysqli_fetch_array($sql);
echo "<h2><center>".$product_data['title']."</h2></center>";
}
?>
You are using id as a query string in this URL as:
view_product_details.php?id=9
So, you need to get id as:
$id = $_GET['id']; //This is line 16
Second issue in your code is that, you can not get result from database without using mysqli_fetch_* function.
echo $result['product_description']; // this will return nothing
Your Modified Code:
<?
$id = intval($_GET['id']);
$sql = mysqli_query($conn,"SELECT * FROM products WHERE ID = ".$id);
if(mysqli_num_rows($sql)){
$result = mysqli_fetch_array($sql);
echo $result['product_description'];
}
else{
echo "No record found";
}
?>
Suggestion:
You need to do one more thing, please use intval() function if any one pass string or anything else in the query string than your query will not return an error only return 0 record like:
Example:
view_product_details.php?id=abcdJUNK
Than convert it into 0 as:
$id = intval($_GET['id']);
For Future Visitors:
After debugging, found this error "Unknown Column ID"
so correct query was this as OP mentioned (column name was product_id):
SELECT * FROM hangouts WHERE product_id = 9
You are actually passing id in view_product_details.php?id=9 query params not product_id in the url.
To use product_id you can change the url like view_product_details.php?product_id=9 or you can use $_GET['id']
& replace this line
$id = $_GET['product_id'];
with this
$id = $_GET['id'];
You can use get_defined_vars(http://php.net/manual/en/function.get-defined-vars.php) to check which variables are
available.
Also I suggest you suppress your errors for production & show all errors in developement.
To hide errors in production
ini_set("display_errors", 0);
ini_set("log_errors", 1);
To show errors in developement
error_reporting(E_ALL);
ini_set('display_errors', 1);
According to your code and URL that you provide you are passing value in variable id not in product_id. This is your URL view_product_details.php?id=9 here value is in variable id i.e id=9.
$id = $_GET['id']; //This is line 16
two problems here first your name attribute in html form is different then what you are using in php i changed the php code for that issue and second problem is you are missing to convert the result in to assosiative array and directly calling the product description just read the comments in modified version of code down below.
this is your current code
$id = $_GET['product_id']; //This is line 16
$result = mysqli_query($conn,"SELECT * FROM products WHERE ID = $id");
echo $result['product_description'];
this is how it should be
// this is the solution for first issue
$id = $_GET['id']; //This is line 16
$result = mysqli_query($conn,"SELECT * FROM products WHERE ID = $id");
// this is the solution for second issue
// covert it to associative array
$resultData = mysqli_fetch_assoc($result);
echo $resultData['product_description'];

ajax returns success but mysql db not updated

I have a javascript for loop that sends an array to an ajax page to update the mysql database.
I echo the result back to the original page and it echos as a success but when I check the db nothing has changed
my javascript for loop that sends the array
for(var m=0; m<array.length; m++){
$.post("update_page_positions.php",{page_ref:array[m][0], ref:array[m][12], menu_pos:array[m][1], sub_menu_pos:array[m][2], top_menu:array[m][3], pagelink:array[m][4], indexpage:array[m][5], hidden:array[m][6], page_title:array[m][7], page_desc:array[m][8], page_keywords:array[m][9], page_name:array[m][10], deletedpage:array[m][11]},
function(data,status){
alert("data="+data+" status="+status);
});
here is the php ajax page the updates the db
<?
include("connect.php");
$ref = $_POST['ref'];
$page_ref = $_POST['page_ref'];
$menu_pos = $_POST['menu_pos'];
$sub_menu_pos = $_POST['sub_menu_pos'];
$top_menu = $_POST['top_menu'];
$indexpage = $_POST['indexpage'];
$page_name = $_POST['page_name'];
$page_title = $_POST['page_title'];
$page_desc = $_POST['page_desc'];
$page_keywords = $_POST['page_keywords'];
$hidden = $_POST['hidden'];
$pagelink = $_POST['pagelink'];
$deletedpage = $_POST['deletedpage'];
$query = mysql_query("SELECT * FROM pages WHERE ref='$ref' AND page_ref='$page_ref'");
if(mysql_num_rows($query)==0){
mysql_query("INSERT INTO pages(page_ref, ref, page_name, menu_pos, sub_menu_pos, top_menu, link, indexpage) VALUES('$page_ref','$ref','$page_name','$menu_pos','$sub_menu_pos','$top_menu','$pagelink','$indexpage')");
}
if($deletedpage=="1"){
mysql_query("DELETE FROM pages WHERE ref='$ref' AND page_ref='$page_ref'");
mysql_query("DELETE FROM site_content WHERE ref='$ref' AND page_ref='$page_ref'");
}
else{
if(mysql_query("UPDATE pages SET menu_pos='$menu_pos', sub_menu_pos='$sub_menu_pos', top_menu='$top_menu', indexpage='$indexpage', page_name='$page_name', page_title='$page_title', desc1='$page_desc', keywords_list='$page_keywords', hidden='$hidden', link='$pagelink' WHERE ref='$ref' AND page_ref='$page_ref'")){
echo "updated!";
} else{
echo "error";
}
}
?>
the INSERT and DELETE functions are fine but the UPDATE returns a success statement but does not update the db.
Can anyone see what the problem is?
Posted as an answer because the comment was too hard to read:
Rather than echoing "updated", try echoing
"UPDATE pages SET menu_pos='$menu_pos', sub_menu_pos='$sub_menu_pos', top_menu='$top_menu', indexpage='$indexpage', page_name='$page_name', page_title='$page_title', desc1='$page_desc', keywords_list='$page_keywords', hidden='$hidden', link='$pagelink' WHERE ref='$ref' AND page_ref='$page_ref'"
(ie. the query you're trying to run).
See if that gives you some clues.
UPDATE reports success, but does nothing in case when its WHERE clause rejects all rows in updated table.
Maybe $page_ref identifier is correct (so DELETE works), but full $page_ref and $ref combination is not?

Categories