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; }
} ?>
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>;
}
I have a column called favid. I am trying to pull and compare the data in that column to an existing value:
<?php $query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid=$favid");
while ($row = mysql_fetch_assoc($query)) {
echo $row['favid']; };?>
I also have an existing value:
$x
But when I do something like this it doesn't work:
<?php if($row['favid'] == $x){?>
Do this...
<?php } else { ?>
Do nothing...
<?php}?>
I realize the data in the column somehow isn't pulled out. What should be done for this to work?
Try this, I assume you already connected to DB.
<?php
$x = 1;
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid='$favid'") or die(mysql_error());
if (mysql_num_rows($query) > 0)
{
while ($row = mysql_fetch_assoc($query))
{
if ($row["existing_column_name"] == $x)
{
echo "Yes";
} else
{
echo "No";
}
}
} else
{
echo "Nothing was found";
}
?>
<?php
$x = 100500; // integer for example
$CID = mysql_connect("host","user","pass") or die(mysql_error());
mysql_select_db("db_name");
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid='{$favid}'", $CID);
while ($row = mysql_fetch_assoc($query)) {
if (intval($row["some_existing_column_name"])==$x){
print "Is equals!";
} else {
print "Is different!";
}
}
?>
Please be informed that mysql_connect and other functions with the prefix of mysql_ is deprecated and can be removed in the next versions of PHP.
I have the following code to check if a row exists in MySQL:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT 1 FROM files WHERE id='$code' LIMIT 1");
if (mysql_fetch_row($result)) {
echo 'Exists';
} else {
echo 'Does not exist';
}
}
?>
This works fine. But I need to change it a bit. I have the following fields:
id, title, url, type. When someone uses the code above ^ to check if a row exists, I need a variable to get the url from the same row, so I can redirect the user to there.
Do you have any idea how I can do that?
Thanks in advance! :)
Try this:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT * FROM files WHERE id=" . $code . " LIMIT 1");
if (mysql_num_rows($result) > 0) {
while($rows = mysql_fetch_array($result)) {
echo 'Exists';
$url = $rows['url'];
}
} else {
echo 'Does not exist';
}
}
?>
It is quite simple. I think you don't show any effort to find the solution by yourself.
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT url FROM files WHERE id='$code' LIMIT 1");
if ($result) {
$url = mysql_fetch_row($resultado);
} else {
echo 'Does not exist';
}
}
<?php
$sql_query = "SELECT * FROM test WHERE userid ='$userid'";
$result1 =mysql_query($sql_query);
if(mysql_num_rows($result1)>0){
while($post = mysql_fetch_array($result1))
{
$url = $post['url'];
}
}
?>
If mysql_num_rows($result1)>0 it means row is existed fir the given user id
I highly appreciate that you try to help me.
My problem is this script:
<?php include("inc/incfiles/header.inc.php"); ?>
<?php
$list_user_info = $_GET['q'];
if ($list_user_info != "") {
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
$user_list = $get_user_list['username'];
$user_profile = "profile.php?user=".$user_list;
$profilepic_info = $get_user_list['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/avatar.png";
}
else {
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
if ($user_list != "") {
?>
<br>
<h2>Search</h2>
<hr color="#FF8000"></hr>
<div class="SearchList">
<br><br>
<div style="float: left;">
<img src="<?php echo $profilepic_info; ?>" height="50" width="50">
</div>
<?php echo "<h1>".$user_list."</h1>"; ?>
</div>
<?php
}
else {
echo "<br><h3>User was not found</h3>";
}
}
else {
echo "<br><h3>You must specify a search query</h3>";
}
?>
I am creating a search script that takes the mysql databse information and shows the result associated to the search query. My script is the above, but keep in mind the sql connection is established in an extern scipt.
The problem is that i want the script to first check if the user is found with the search query in the username row, and then get the entre information from that user and display it. If the user is not found with the username query, it should try and compare the search query with the name row, and then with the last name row. If no result is displayed it should then return an else statement with an error, e.g. "No user wsas found"
Yours sincerely,
Victor Achton
Do the query as Muhammet Arslan ... but just counting the rows would be faster ...
if(mysql_num_rows($get_user_info)){
//not found
}
you should add a "Limit 1" at the end if you are just interested in one result (or none).
But read about prepared statements
pdo.prepared-statements.php
This is how it should be done in 2013!
Something like this but you don't need 3 queries for this. you can always use OR in mysql statements
$handle1 = mysql_query("SELECT * FROM users WHERE username = $username"); // Username
if (($row = mysql_fetch_assoc($handle1) !== false) {
// username is found
} else {
$handle2 = mysql_query("SELECT * FROM users WHERE name = $name"); // name
if (($row = mysql_fetch_assoc($handle2) !== false) {
// name is found
} else {
$handle3 = mysql_query("SELECT * FROM users WHERE lastname = $lastname"); // Last name
if (($row = mysql_fetch_assoc($handle3) !== false) {
// last name is found
} else {
// nothing found
}
}
}
Already you did ,but you can improve it by using "AND" or "OR" on ur sql statement.
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info' or name = '$list_user_info' or last_name = '$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
if(empty($get_user_list))
{
echo "No User was found";
}
and you should control $list_user_info or u can hacked.
Here some adapted copy pasting from php.net
Connect
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
fetch data
$stmt = $dbh->prepare("SELECT * FROM users where name LIKE '%?%'");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
the rest is your programing ...
And do some reading it's very dangerous to use copied code without understanding !
Code:
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table`
WHERE `Username` = '$Username'
ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) { ?>
<?php if(!isset($db['article'] && $db['subject'])) {
echo "Your articles";
} else {
echo "You have no articles added!";
} ?>
<?php } ?>
So I want the rows for example(db['article'] and $db['subject']) from a specific username (see: $Username = $_SESSION['VALID_USER_ID'];) to echo the information if is not empty else if is empty to echo for example "You have no articles added!"
If is some information in the rows the code works, echo the information BUT if the rows is empty don't echo nothing, the code should echo "You have no articles added!" but this line don't appear, where is the mistake?
I tried for if !isset, !empty, !is_null but don't work.
I think what you're trying to achieve is:
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
if(mysql_num_rows($q) > 0)
{
echo "Your articles:\n";
while($db = mysql_fetch_array($q)) {
echo $db['subject']." ".$db['article']."\n";
}
}
else
{
echo "You have no articles added!";
}
?>
I don't understand. Do you have article rows with username, but without article, i.e.:
| id | user | article |
-------------------------------------
| 1 | X | NULL |
If so, you can test with:
if($db['article'] == NULL) { .... } else { .... }
Otherwise, if you don't have a row with user=x, when there are no record, mysql will return an empty result.
So, basicly, if no rows are found on selection: SELECT * FROM article_table WHERE Username = 'X';, you can test
if(mysql_num_rows($q) > 0) { .... } else { .... }
However, mysql_ functions are not recommended anymore. Look at prepared statements.
You have a logic error in your if statement -- what you want is to check if both the article and subject are set.
With your current code, you compare $db['article'] with $db['subject'], and check if the result is set. You need to change it a bit :
Instead of :
if(!isset($db['article'] && $db['subject'])) {
Try:
if(isset($db['article']) && isset($db['subject'])) ...
I would do something like this:
$articles='';
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) {
if(isset($db['article']) && isset($db['subject'])) {
$articles .= $db['article']."<br/>";
}
}
if($articles != ''){
echo $articles;
}
else{
echo "No articles";
}
?>
fastest way to achieve what you want is by adding a variable that will verify if the query returned any rows:
<?php $Username = $_SESSION['VALID_USER_ID'];
$i = 0;
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) {
$i = 1;
if(!isset($db['article'] && $db['subject'])) { echo "Your articles"; } ?>
<?php }
if ($i == 0) echo "You have no articles";
?>
You tried to echo "no articles" in the while loop, you get there only if the query returns information, that is why if it returns 1 or more rows, $i will become 1 else it will remain 0.
In your case:
$numArticles = mysql_num_rows($q);
if($numArticles > 0)
echo 'Your articles';
else
echo 'No articles :((((';
I recommend tough moving on to PDO to communicate with DB.