display php forum topics list in Android - php

I have android app. with a php forum. for the time being I have a single user table to store the user details
but I did so coz I need to allow users to post and comments from the android interface to the forum.
I need to bring the list of topics from my forum and when user choose one of them it displays the content and he can click comment button to go to comment layout to write and send his/comments to the forum.
now I have made this php code to list the topics
<?php
//This page let display the list of topics of a category
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
if(isset($_GET['parent']))
{
$id = intval($_GET['id']);
}
$dn = mysql_query('select t.title, u.username as author, from topics as t left join topics left join user as u where t.parent="'.$id.'" and t.id2=1 group by t.id order by t.timestamp2 desc');
if(mysql_num_rows($dn)>0)
{
$dn = mysql_query("SELECT * FROM topics WHERE id = $parent");
// return user details
$posts = array();
if(mysql_num_rows($dn)) {
while($post = mysql_fetch_assoc($dn)) {
$posts[] = array('post'=>$post);
}
}
} else {
// return false;
}
?>
but I'm sure is correct or not also in my Android side should I create an array to hold this values to display..
I need to know if my concept is correct otherwise I'll be wasting my time...
thanks a lot in advance

What you need to do is to print your information in a format you can parse from Android. I suggest JSON as it's simple and the preferred way to do it.
So, to summarize:
Print your forum's information in JSON
Perform an HTTP request from Android and get the response body
Parse it with a JSON Library
Optional but recommended: Transform it into a object to represent each element (each forum)

Related

Get MySQL data and store it to a PHP array based on the data array returned by another MySQL select operation

I am creating an iOS application and I am facing a difficulty with the web service portion, which is written in PHP. What I am trying to achieve is, sending push notification to the devices. I have completed that part. However, I need a mechanism to differentiate between notifications that has been delivered successfully to the phone and that haven't. I use a feedback web-service for this purpose and It is also working. have a MySQL table with the following structure. Based on the status bit of each notification, I collect all the notifications corresponding to each device token, and make it into an array and send it to the device. Here is where I am facing difficulty.
I have two tables.
This table stores the notification ID, device token and status of the notification. By looking at this table, my script can determine whether the notification has been delivered to the particular device or not. My script collects all the notification IDs that has been undelivered to a particular device ID and uses the following apps_notif table to fetch the undelivered notifications. The table structure is as below.
My PHP/MySQL script is as follows.
$fecthnotif=mysqli_query($mysqli,"SELECT notif_id FROM notif_status WHERE notif_status=0 AND dev_token='$device_token'") or die(mysqli_error($mysqli));
$d2=array();
while($row = mysqli_fetch_assoc($fecthnotif)) {
$d2[]=$row;
$json = json_encode($d2);
$arr = json_decode( $json,true);
By this time, I get an array of undelivered notifications as JSON. The result is as follows.
[{"notif_id":"124"},{"notif_id":"129"}]
Now, I loop though the results as follows.
foreach($arr as $item) { //foreach element in $arr
$uses= $item['notif_id']; }
What I am trying to achieve is to take each notif_id from the above result, fetch allthe notification data from the apss-Notif table, make it a single JSON object and return that payload to the app.So that JSON should have all the notification data of all the notifications that were undelivered at the first place.
Inside the foreach loop, I wrote a query loop to store all the pending notifications to array, but it isnt working.
$d=array();
foreach($arr as $item) { //foreach element in $arr
$uses= $item['notif_id']; //etc
//echo $uses;
$sendnotif=mysqli_query($mysqli,"SELECT * FROM apps_notif WHERE notif_id='$uses'") or die(mysqli_error($mysqli));
while($row = mysqli_fetch_assoc($sendnotif)) {
$d[]=$row;
$i++;
}
}
Edit: Basically, what I am trying to achieve is to return rows from the apps_notif table that match the criteria, notif_status=0 (from table notif_status) and dev_token="qwerty" (from apps_notif table)
I can see that two rows are eligible.
Hope it helps
SELECT b.*
FROM notif_status a
INNER JOIN apps_notif b ON a.notif_id = b.notif_id
WHERE notif_status = 0
AND dev_token = '$device_token';
using sub queries,
SELECT *
FROM app_notify
WHERE notify_id IN (SELECT notif_id
FROM notif_status
WHERE notif_status = 0
AND dev_token = '$device_token') ;
See in your table. In table 1 you have notify_id but in table 2 you have date having kind of similar values. Hence if u match table1 notifyId and table2 notifyId you will not get the desired output. First check the proper criteria how the table should be designed.
You can try below PHP code to get the details from 2 table and make JSON object. Not tested query as i don't have respective DB tables.
$query = "SELECT a.* from apps_notif a JOIN notif_status b ON b.notif_id = a.notif_id WHERE b.notif_status=0 AND b.dev_token='$device_token'";
$res = mysqli_query($mysqli,$query);
$d = array();
while ($row = mysqli_fetch_assoc($res)) {
$d[] = $row;
}
$json = json_encode($d);
Hope this helps you.

Multiple MYSQL: PHP loops not working

I've been writing some code that essentially collects information based on schools and the user search input. Once the information is pulled up, I also query a database containing users to show how many are signed up at each school, and then another database containing files showing how many files have been uploaded from each school.
I imagine this would require a three tiered loop? If I query the school database and then the student database in succession it works great (Every school will have the appropriate number of students signed up displayed). However the problem is with the files. If I add in the file query, it will only show the first two results of the schools.
This leads me to believe that the file database query isn't correct and after testing a two tiered loop (this time will files instead of students) it appears to be the case. So, what am I doing wrong with the file database code? I copied it directly from the student database code so I haven't a clue why this one won't work. Here is the code that works:
mysql_select_db($database_geographic, $geographic);
$query_school = "SELECT * FROM geographic.school WHERE countryid='$countryid' AND stateid='$stateid' ORDER BY school_name ASC";
$school = mysql_query($query_school, $geographic) or die(mysql_error());
$totalRows_schools = mysql_num_rows($schools);
while ($row_school = mysql_fetch_assoc($school)) {
echo $row_school['school_name'];
echo $row_school['city_name'];
echo $row_school['state_name'];
echo $row_school['schoolid'];
$schoolid = $row_school['schoolid'];
mysql_select_db($database_user_information, $user_information);
$query_users = "SELECT COUNT(*) AS studentcount FROM users WHERE school_name= '$schoolid'";
$users = mysql_query($query_users, $user_information) or die(mysql_error());
while ($row_users = mysql_fetch_assoc($users)) {
echo $row_users['studentcount']; }
But if I throw in this third files loop statement it will not work.
mysql_select_db($database_files, $files);
$query_files = "SELECT COUNT(*) AS filecount FROM file_data WHERE school_id= '$schoolid'";
$files = mysql_query($query_files, $files) or die(mysql_error());
while ($row_files = mysql_fetch_assoc($files)) {
echo $row_files['filecount']; }
}
If I use the file query in place of the student query it will not work either. The problem must be with the file query but I can't figure it out. Any help would be awesome! Thanks!

PHP check if variable exists in all rows returned

i want to do a check if a user id exists in all of the table rows i search for.
edit sorry i was missleading i think.
I want to check if the user has read all of the articles in a category, i have a forum front end displaying the categories and within the categories are the articles.
On the categories screen i want to display an image ALL ARTICLES READ or NOT ALL ARTICLES READ, so some how i need to loop through all of the articles per category which is what the example query below is doing and check if user id exists in ALL returned rows if yes then then all articles have been read if there are some rows missing the users id then some articles have not been read
This is my sql query
$colname_readposts = "-1";
if (isset($_GET['Thread_Category_Article_id'])) {
$colname_readposts = $_GET['Thread_Category_Article_id'];
}
mysql_select_db($database_test, $test);
$query_readposts = sprintf("SELECT Thread_Article_User_Read FROM Thread_Articles WHERE Thread_Category_Article_id = %s", GetSQLValueString($colname_readposts, "int"));
$readposts = mysql_query($query_readposts, $cutthroats) or die(mysql_error());
$row_readposts = mysql_fetch_assoc($readposts);
$totalRows_readposts = mysql_num_rows($readposts);
How can i check if all of the rows returned contain the users id?
The idea is to check to see if user has read all the articles if yes show READ if no show UNREAD.
The results per row are like so 0,15,20,37 these are id's entered when a user views a post.
i have managed to get this check for a single article to show if the user has read a specific article but unsure how i would check multiple:
here is my single article check:
<?php
$userid = $_SESSION['loggedin_id'];
$userreadlist = $row_readposts['Thread_Article_User_Read'];
$myarray = (explode(',',$userreadlist));
if (in_array($userid,$myarray )){
?>
html image READ
<?php } else { ?>
html image UNREAD
<?php } ?>
Any help would be appreciated.
Carl
First up, forget the mysql_* functions; ext/mysql is a deprecated API as of PHP 5.5 - so it's a really good idea to use mysqli or PDO.
From what I gather you're actually trying to see if any of those results contain a specific user's id? If so, do this in the SQL query:
SELECT Thread_Article_User_Read FROM Thread_Articles WHERE
Thread_Category_Article_id = %s AND UserID = %s
And supply this the User's ID as a second argument. (Syntax may not be 100% correct, but it should prove a point)
If you mean you want to check there there is any user's ID - then once again; do this in SQL:
SELECT Thread_Article_User_Read FROM Thread_Articles WHERE
Thread_Category_Article_id = %s AND UserID IS NOT NULL
This will ensure there is a valid value for 'UserID'.
Naturally replace 'UserID' with your column name if you base your solution on one of these examples.
However, if you're dumping out ALL the results from a table - and you need to see if your user's ID is present in a certain column (like you do!); then you can actually just adapt the logic that you're using on your single article page. Which should give you something like this...
$userid = $_SESSION['loggedin_id'];
$colname_readposts = "-1";
if (isset($_GET['Thread_Category_Article_id'])) {
$colname_readposts = $_GET['Thread_Category_Article_id'];
}
/* connect to db and run query; CHANGE ME TO SOMETHING NOT DEPRECATED */
mysql_select_db($database_test, $test);
$query_readposts =
sprintf("SELECT Thread_Article_User_Read FROM Thread_Articles WHERE
Thread_Category_Article_id = %s", GetSQLValueString($colname_readposts, "int"));
$readposts = mysql_query($query_readposts, $cutthroats) or die(mysql_error());
/* loop through all returned items */
while($row = mysql_fetch_assoc($readposts)) {
/* repeat the check you used on an individual
row on the single article page. i.e: */
$userreadlist = $row['Thread_Article_User_Read'];
$myarray = (explode(',',$userreadlist));
if (in_array($userid,$myarray )){
/* user has read */
} else {
/* user hasn't read */
}
}
If that code you worked for a single page then it should work in the above; as for every iteration of the loop you're working on a single row - just as you were on the single page. If the data is coming from the same table then the column names etc match up and it will work.
Or, if you just want to know if there are any unread posts at all, replace the loop with this one...
/* loop through all returned items */
$read = true;
while($row = mysql_fetch_assoc($readposts)) {
/* repeat the check you used on an individual
row on the single article page. i.e: */
$userreadlist = $row['Thread_Article_User_Read'];
$myarray = (explode(',',$userreadlist));
if (! in_array($userid,$myarray )){
$read = false;
break;
}
}
if( $read ){
/* all pages are read */
} else {
/* there are unread pages */
}

comment like facebook script

I already have an script where it will allow a user whom is logged in to comment on other users. One field for the usercommenting "men_id" and another field for the user being commented on commented_men_id. Well I save it in a comment table and to pull it I make a while I make a select to get the comment of men_id while getting the comment I do another while loop inside the while loop to get the user name and id to return it in the comment. Now the next step is to let other user to comment on top of the comment that is already there. I was wondering if I have to make another table or just create another table to get the comments on another comments. I was also wondering in terms of the php script will I have to create another while loop inside the second while loop to pull the subcomments?
So far I have the next structure
$sql1 = "SELECT id, mem_id, commented_id, comment
FROM comments
WHERE commented_id = '$id'";
while($row=msql_fetch_array($sql)) {
$id_coment = $row['id'];
$mem_id = $row['mem_id'];
$comment = $row['comment'];
$sql_member_data = msql_query("SELECT id, member_name FROM users WHERE id ='$id_coment'");
while($row2=msql_fetchj_array($sql_member_data)) {
$user_id =$row2['id'];
$user_name =$row2['member_name'];
echo '<div>'.$user_name.'</div>';
echo '<div>'.$comment.'</div>';
}
}
I advise might not be the best code but it is posting the comment, Now how can I get a comment within the comment generated by this script.
Thank you guys.
If you truly want a something like Facebook's commenting system, you are going to have to do a lot more than that. I made my own little system and it's nicely styled with some really awesome jQuery effects.
Here's what you are going to need
Section to get all your comments (which you have -- check for syntax errors)
Form and script to post your comments
And you will probally need to use jQuery and AJAX for the commenting and some more jQuery to auto-refresh like facebook does.
That's my take on it. No one else hate on me for this, just trying to give some input on it.
<?php
// Connect to database here
// Search and start loop to get all comments
$sql_comments = mysql_query("SELECT * FROM comments WHERE type='main'");
while($rows_comment=mysql_fetch_array($sql_comments)){
// Get comment information
$main_comment_id = "".$rows_comment['id']."";
$main_comment_mem_id = "".$rows_comment['mem_id']."";
$main_commented_id = "".$rows_comment['commented_id']."";
$main_comment = "".$rows_comment['comment']."";
// Get user information
$sql_member_data = msql_query("SELECT * FROM users WHERE id ='$main_comment_mem_id'");
while($row2=msql_fetchj_array($sql_member_data)) {
$user_id = "".$row2['id']."";
$user_name = "".$row2['member_name']."";
}
// Display comment
echo "<b>$user_name</b><br>$main_comment";
// Search for any sub-comments
$sql_subcomments = "SELECT * FROM comments WHERE sub_commented_id='$main_comment_id' AND type='sub'";
while($row_subcomment=msql_fetchj_array($sql_subcomments)) {
// Get sub comment information
$subcomment_id = "".$row_subcomment['id']."";
$sucomment_mem_id = "".$row_subcomment['mem_id']."";
$subcomment_comment = "".$row_subcomment['comment']."";
// Get sub commenter information
$sql_member_data_sub = msql_query("SELECT * FROM users WHERE id ='$subcomment_mem_id'");
while($row2_sub=msql_fetchj_array($sql_member_data_sub)) {
$user_id_sub = "".$row2_sub['id']."";
$user_name_sub = "".$row2_sub['member_name']."";
}
// Echo sub comment
echo "<div style='margin-left: 20px;'><b>$user_name_sub</b><br>$subcomment_comment</div>";
}
}
?>

Variable out of scope when entering a while loop in php

I have a problem when trying to populate an array in php. It seems that once I enter a while loop with a mysql_fetch_assoc method I cannot populate my array. I've included the code below.
$params = $_REQUEST['params'];
$arr["status"]="ok";
$projects=array();
$files=array();
$titles=array();
$query = 'SELECT p.id as pid, f.fname as name, f.title FROM proj p INNER JOIN pic f ON f.projid=p.id WHERE p.catid=\'' . $params['category'] . '\' ORDER BY p.ordr, f.ordr';
require("../php/connect.php");
//select all projects from chosen category and pics from selected projects
$proj_result = mysql_query($query) or die ("Select failed");
//populate from rows
while($row = mysql_fetch_assoc($proj_result)){
$projects[]=$row["pid"];
$files[]=$row["name"];
$titles[]=$row["title"];
}
$arr["projects"]=$projects;
$arr["files"]=$files;
$arr["titles"]=$titles;
echo json_encode($arr);
The result: {"status":"ok","projects":[],"files":[],"titles":[]}
Thank You.
A while loop doesn't create a new scope, as you can see here: http://codepad.org/H1U3wXZD
About the code itself, here's a few suggestions:
0) I would consider having a database abstraction layer (PDO would be good enough).
1) Learn how to use JOIN's. It looks like you could fetch all the necessary information with a single query, something like:
SELECT p.id, p.proj, c.id, c.fname, c.title
FROM proj p
INNER JOIN pic c ON c.projid=p.id
WHERE catid='<your category>'
ORDER BY p.ordr, c.ordr
2) You should separate the code that gets data from the db from the code that constructs the HTML (?). Perhaps you could put that in another method. Something like:
if ($cmd == 'catSelect') {
$data = getData($params['category']);
foreach ($data as $value) {
// process data here
}
}
3) I take it you are using the generated JSON to send it via AJAX to a client. In that case, I would totally cut the fat (eg: generated markup) and send only essentials (picture id, title, fname and whatever else is essential) and generate the code on the client side. This will make your page load faster and save you and your visitors bandwidth.
my jquery/ajax client side script was not sending in category properly and therefore was no selecting any rows.
The above code will work.
Within the loop try something like this :
while($row = mysql_fetch_assoc($proj_result)){
$projects[]=$row["pid"];
$files[]=$row["name"];
$titles[]=$row["title"];
echo $row["pid"]." -- ".$row["name"]." -- ".$row["title"]."\n";
}
Do you get anything? Once you have tried it we will take it from there. My guess is that you aren't getting any data from MySQL.

Categories