I am trying to grab favorite posts from 'posts_fav' where the post id is of the row id. Then i want it to if the userid on the query equals the members id it will show 'yes' otherwise it will show 'No'.
Originial:
foreach ($usersfav as $rowfav) {
if ($rowfav["user_id"] == $member["id"])
{
echo 'yes';
}
else
{
echo 'no';
}
}
One of my attempts:
This changes all to the else function. Skips the check of the if as there needs to be a way I can get $rowfav[""] without needing
foreach ($usersfav as $rowfav) {
$sqlfav = "SELECT * FROM posts_fav WHERE post_id = '".$row["id"]."'";
$stmfav = $dbh->prepare($sqlfav);
$stmfav->execute();
$usersfav = $stmfav->fetchAll();
if ($rowfav["user_id"] == $member["id"])
{
echo 'yes';
}
else
{
echo 'no';
}
}
Update:
So I want the posts where rowfav["user_id"] and member["id"] match up to say 'Yes' and other posts without any rows that can be found to say 'no'
Full code:
$sql = "
SELECT *,
(SELECT profilepic FROM users WHERE users.username = users_profiles_comments.author) AS profilepic
FROM users_profiles_comments WHERE postid = '". $row["username"] ."' ORDER BY `id` DESC";
$stm = $dbh->prepare($sql);
$stm->execute();
$users = $stm->fetchAll();
foreach ($users as $row) {
echo ' <div class="row user-row">
<div class="col-xs-3 col-sm-2 col-md-2 col-lg-2">
<img class="img-thumbnail"
src="'.$row['profilepic'].'" width="150px;"
alt="User Pic">
</div>
<div class="col-xs-10 col-sm-10 col-md-10 col-lg-10">
<div class="panel panel-default">
<div class="panel-heading"><b>'. $row["author"] .'</b> - <small>'. $row["date"] .'</small>
';
if ($row["author"]) {
echo '<p style="float:right;">';
$sqlfav = "SELECT * FROM posts_fav WHERE post_id = '".$row["id"]."'";
$stmfav = $dbh->prepare($sqlfav);
$stmfav->execute();
$usersfav = $stmfav->fetchAll();
foreach ($usersfav as $rowfav) {
if (strcmp($rowfav["user_id"], $member["id"]) == 0)
{
echo '
Yes
';
}
else {
echo 'No';
} }
if (count($usersfav)!=0)
{
foreach ($usersfav as $rowfav)
{
if (strcmp($rowfav["user_id"], $member["id"]) == 0)
{
echo 'Yes';
}
}
}
else
{
echo 'No';
}
If I understood it right, you want to get the favourite posts of a user, and with that, get the information that it's his post or not.
You could, as a suggestion, let the check be done on the query, so your results would come already with the flag you want.
$sql = "SELECT posts_fav.*, posts.*, IF(posts.user_id = ?, 1, 0) as owns_post FROM posts_fav LEFT JOIN posts ON posts_fav.post_id = posts.id WHERE posts_fav.member_id = ?";
$query = $dbh->prepare($sql);
$query->bind_param("posts_member_id", $member["id"]);
$query->bind_param("member_id", $member["id"]);
$query->execute();
$rows = $query->fetchAll();
foreach($rows as $row) {
if($row["owns_post"]) {
echo "User owns the post";
} else {
echo "User does not own the post";
}
}
Not tested, no garantee that it even works. :-)
Related
i have problem, on my code i create chat, but duplicate users name, i try prevent but not success.... some can help?
my code:
$sql = "SELECT * FROM `inbox` WHERE `from`='".$_SESSION['username']."' OR `to`='".$_SESSION['username']."' ORDER by `data` DESC;";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$lastuser = "";
while($row = mysqli_fetch_array($result)) {
$chat_name = "";
if($row['from'] == $_SESSION['username']) {
$chat_name = $row['to'];
} else {
$chat_name = $row['from'];
}
if($lastuser != $chat_name) {
echo "
<a href='?user=".$chat_name."'>
<div class='inbox_users_box'>
<div class='inbox_imagenuser'>
<img class='inbox_image' src='".getAvatarOthers($chat_name)."'></img>
<div style='margin-top: 14px; float: left;'>".$chat_name."</div><span style='margin-top: 17px; margin-left: 5px;' class='".getonline_player($chat_name)."'></span>
<div style='clear:both;'></div>
</div>
<div class='inbox_lastmsgdata'>".$row['data']."</div>
</div>
<div style='clear:both;'></div>
</a>
";
$lastuser = $chat_name;
}
}
my chat : my chat picture
i want dont duplicate users..
You can save the filtered inbox entries in an array with the data to display, but only when the user isn't already in that array. This way it gets added only once. After that you print the array the way you like with a normal foreach() loop.
$users = array();
while ($row = mysqli_fetch_assoc($result);
// retrieve the data from MySQL
$chat_name = "";
if($row['from'] == $_SESSION['username']) {
$chat_name = $row['to'];
} else {
$chat_name = $row['from'];
}
$data = $row['data'];
// look if the user is already in the array
$found = false;
foreach ($users as $user) {
if ($user['name'] == $chat_name) {
$found = true;
break;
}
}
if ($found) {
continue;
}
// its not, so add it
$toAdd = array('name' => $chat_name, 'data' => $data);
$users[] = $toAdd;
}
/* display users */
foreach ($users as $user) {
$username = $user['name'];
$data = $user['data'];
// your HTML code here
}
I am displaying a user's profile image. I have created an if statement to post a default profile image if a user has not updated their own. This is all working, but what I cannot figure out is how to echo or call for each without getting an error for the one not set.
For instance, if they do have a profile picture set, it posts fine, but then I get an error that the other variable is not defined and vise versa.
How should I be calling for this or what changes should I make in my code?
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if ($profilePic === NULL) {
$default_profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$set_profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $default_profile_img;
echo $set_profile_img; ?>
EDIT:
How profilepic gets defined:
$sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY id DESC LIMIT 1
";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param("s", $user_id);
$stmt->execute();
if (!$stmt->errno) {
// Handle error here
}
$stmt->bind_result($id, $user_id, $profilePic);
Just add $default_profile_img = null; and $set_profile_img = null; at the top of php code.
$default_profile_img = null;
$set_profile_img = null;
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if ($profilePic === NULL) {
$default_profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$set_profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $default_profile_img;
echo $set_profile_img; ?>
You just need to initialize the variables before the if..else statements so that it won't be undefined when you try to echo both of them.
$profile_img = "";
$default_profile_img = "";
if (...
Try this code. There is no need to use two different variables. This way, you won't get the warning.
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if (!isset($profilePic) OR $profilePic === NULL) {
$profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $profile_img; ?>
i was looking for a way to return an error if no results were found in a MySql query, at first i declared a variable value false, and if the fetch() function is true it will set the value of that boolean to true, then i check if it is true or false, but then i searched for that in internet cause i didn't like my solution that much, so I found the function IFNULL(query, 'error message');
I tried it but I had an error, can you tell me what's wrong in my code?
if(isset($_POST['tosearchfor']))
{
$query = $db->query('SELECT IFNULL( (SELECT * FROM searchfor WHERE title LIKE \'%'.$_POST['tosearchfor'].'%) , \'Sorry, no resluts found for : <strong>'.$_POST['tosearchfor'].'strong');
while($result = $query->fetch())
{
echo '<div class="result"><a class="title" href="#">'.$result['title'].'</a><span class="link"><span style="font-size:15px;position:relative;top:0.8px;padding-right:2px;">‣</span>https://www.qsoft.com/'.$result['link'].'</span><span class="details">'.$result['details'].'</span></div>';
}
}
else
{
echo 'Error : empty search';
}
Thank you.
Hey i used a different method not in youre query but with $query->rowCount().
Let's use the IF outside of the query :)
And the $db->prepare protect youre query, because never put a $_POST directly inside a query without protection.
if(isset($_POST['tosearchfor'])){
//We prepare the query
$query = $db->prepare("SELECT * FROM searchfor WHERE title LIKE '%:tosearch%'");
//We had parameters
$query->bindParam(':tosearch',$_POST['tosearchfor'], PDO::PARAM_STR);
//We execute the query
$query->execute();
//We retrieve the results in array of objects
$results = $query->fetchAll(PDO::FETCH_OBJ);
if (count($results) > 0) {
foreach ($results as $result){
echo '<div class="result">
<a class="title" href="#">'.$result->title.'</a>
<span class="link">
<span style="font-size:15px;position:relative;top:0.8px;padding-right:2px;">‣</span>
https://www.qsoft.com/'.$result->link.'
</span>
<span class="details">'.$result->details.'</span>
</div>';
}
} else {
echo 'Sorry, no resluts found for : <strong>'.$_POST['tosearchfor'].'</strong>';
}
}else{
echo 'Error : empty search';
}
The default result value of IFNULL(expr1,expr2) is the more “general”
of the two expressions, in the order STRING, REAL, or INTEGER.
You cannot evaluate a group of records with IFNULL. Something like below
Also instead of using direct substitution values, you could use below methods to avoid sql injection.
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array(':name' => $name));
if(empty($stmt)){
return false;
}
foreach ($stmt as $row) {
// do something with $row
}
return result;
If this method return false then there is no search result.
Finally, this is my code, i also added max number of results 20.
$db = new PDO('mysql:host=localhost;dbname=search','root','');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['tosearchfor']))
{
$query = $db->query('SELECT * FROM searchfor WHERE title LIKE \'%'.$_POST['tosearchfor'].'%\'');
for($i=0; $i<20; $i++)
{
if($result = $query->fetch())
{
echo '<div class="result">
<a class="title" href="#">'.$result['title'].'</a>
<span class="link">
<span style="font-size:15px;position:relative;top:0.8px;padding-right:2px;">‣</span>
https://www.qsoft.com/'.$result['link'].'
</span>
<span class="details">'.$result['details'].'</span>
</div>';
}
else
{
if($i==0)
{
echo 'Sorry, no resluts found for : <strong>'.$_POST['tosearchfor'].'</strong>';
}
}
}
}
else
{
echo 'Error : empty search';
}
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 !
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; }
} ?>