Hide/Show button, also when refreshed - php

I am making an application that displays "activities". Each activity has his own button. When you click on that button, you add that specific activity to your "guide". The idea is that you can add one specific activity only once, so the button of that activity must disapear when it's added to the guide. I can use a simple $(this).hide() in my javascript but that obviously doesn't work when I refresh the page. So I guess i should make a check if the activity exists in de guide.
in the database I have 3 tables, 1: activity (with an ActivityID), 2: user (with a UserID) and 3: user_activity (with ActivityID and UserID, a linktable).
So the check must check if the ActivityID exists in the user_activity table, and that the UserID that belongs to that ActivityID in the user_activity table is the sames as the current users' ID.
At this moment, I know how to check the current users UserID:
//userid
$sql = "SELECT * FROM user WHERE Username = '".$_SESSION['Username']."' ";
$stm = $db->prepare($sql);
$result = $stm->execute(array());
while($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$userid = $row['UserID'];
}
But I don't know how to check if the ActivityID already exists, and how I should make this
if else statement.
Ay the moment I use this script to display the activity (incl. the button)
$sql = "SELECT * FROM activity";
$stm = $db->prepare($sql);
$result = $stm->execute(array());
while($row = $stm->fetch(PDO::FETCH_ASSOC))
{
echo '<div id="activity'.$row['ActivityID'].'">';
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['ActivityIMG'] ) . '" >', '<br>';
$instantguide = $row['ActivityID'];
echo '<input type="button" class="addActivity" onclick="MakeRequest(' . $instantguide . ')" value="Activiteit toevoegen" data-activity="' . $row['ActivityID'] . '">';
echo '</div>';
}

You need a LEFT JOIN to see what activities are already on
SELECT a.*, ua.ActivityID as added
FROM activities a LEFT JOIN user_activity ua
ON a.ActivityID=ua.ActivityID AND UserID=:userid
So you'll have an additional added field in the resultset, filled with an id if it is already chosen or empty otherwise

// First you need to get all the activityIDs from the table where you want to search and put them into an array
$sql2 = "SELECT * FROM user_activity";
$stm2 = $db->prepare($sql2);
$result2 = $stm2->execute(array());
$user_activityID = array();
while($row2 = $stm->fetch(PDO::FETCH_ASSOC))
{
// if in the table user_activity the column you are trying to compare has the same name as in activity -- $row2['ActivityID']
array_push($row2['ActivityID'], $user_activityID);
}
// Then you use in_array to compare while you go through the user_activity table
$sql = "SELECT * FROM activity";
$stm = $db->prepare($sql);
$result = $stm->execute(array());
while($row = $stm->fetch(PDO::FETCH_ASSOC))
{
if (in_array($row['ActivityID'], $user_activityID))
{
// yes the current $row['ActivityID'] from the activity table, exists in the user_activity table
// you can choose whether or not to add this to your array
array_push($row['ActivityID'], $activityID);
}
}
I'm sure there's other more efficient ways to do this, using some pdo stuff that I don't know, but this is how I would have done it.

Related

mysql query returning false even when values DO exist in table? Trying to find if not in table?

Ok, so I am building on my first question here https://stackoverflow.com/questions/38102208/php-mysql-how-to-only-echo-links-with-search-bar-post-that-arent-already-echo
trying to only echo only usernames of people whose id is NOT in a mysql table called conversation along with a set id (the person who is signed in).
I echo the people who their id is user_two in a table conversation REGARDLESS if a search bar is posted here:
//$num = mysqli_query($con, "SELECT * FROM `pm_messages` WHERE user_from=".$account['id']."");
$numCon = mysqli_query($con, "SELECT * FROM `conversation` WHERE user_one=".$account['id']."");
$numrows = mysqli_num_rows($numCon);
while ($u = mysqli_fetch_assoc($numCon)) {
//get other users usernames to echo link
$getUserTwo = mysqli_query($con, "SELECT * FROM `accounts` WHERE id=".$u['user_two']."");
$s = mysqli_fetch_assoc($getUserTwo);
//echo $s['username'];
echo "<a href='message.php?id={$s['id']}'><li><img class = 'dmCircle' src = '../images/chatCircle.png'/>{$s['username']} </li></a>";
}
This works well, meaning only individuals who a conversation has been started with (a row exists for this user and the one signed in conversation table) are echoed in a link.
Problem comes here with the search bar because it echoes all individuals even if a conversation has been started, resulting in duplicates:
(notice the 2 khusteds)
This does not make sense because here I select the row in conversation where user_one is the signed in user and user_two is the second user and only echo a link if the result is FALSE (meaning there's no conversation):
if (isset($_POST['searchbarpm'])) {
//$sess->getUsers();
$dbh = mysqli_connect("localhost","username","password","sqlserver");
$query = $_POST['searchbarpm'];
$q = mysqli_query($dbh, "SELECT * FROM sqlserver.accounts WHERE username LIKE '%".$query."%'");
//display all the results
while($row = mysqli_fetch_assoc($q)) {
$checkConvo = mysql_query("SELECT 'id' FROM sqlserver.conversation WHERE user_one=".$user_id." AND user_two=".$row['id']."");
//only output users they dont have convo going with because theyre already printed!!!
if ($checkConvo==false && $row['id']!= $user_id) {
echo "<a href='message.php?id={$row['id']}'><li><img class = 'dmCircle' src = '../images/noChatCircle.png'/> {$row['username']}</li></a>";
}
}
}
But it looks like the query is always false because again, all users are echoed. Why is this happening? How can I only echo users not in conversation table with the signed in user (user_one)?
EDIT:
new code (sorry for screenshot); :
#IanH -
$con = mysqli_connect("localhost","username","password","sqlserver");
//$num = mysqli_query($con, "SELECT * FROM `pm_messages` WHERE user_from=".$account['id']."");
$numCon = mysqli_query($con, "SELECT * FROM `conversation` WHERE user_one=".$account['id']."");
$numrows = mysqli_num_rows($numCon);
while ($u = mysqli_fetch_assoc($numCon))
{
//get other users usernames to echo link
$getUserTwo = mysqli_query($con, "SELECT * FROM `accounts` WHERE id=".$u['user_two']."");
$s = mysqli_fetch_assoc($getUserTwo);
//echo $s['username'];
if(isset($_POST['searchbarpm'])){
//$sess->getUsers();
$dbh = mysqli_connect("localhost","username","password","sqlserver");
$query = $_POST['searchbarpm'];
$q = mysqli_query($dbh, "SELECT * FROM sqlserver.accounts WHERE username LIKE '%".$query."%'");
//display all the results
while($row = mysqli_fetch_assoc($q)){
if($row['id']!= $user_id && $row['id']!=$s['id']) { //only output users they dont have convo going with because theyre already printed!!!
echo "<a href='message.php?id={$row['id']}'><li><img class = 'dmCircle' src = '../images/noChatCircle.png'/> {$row['username']}</li></a>";
}
}
}
else {
echo "<a href='message.php?id={$s['id']}'><li><img class = 'dmCircle' src = '../images/chatCircle.png'/>{$s['username']} </li></a>";
}
}//
First of all, you need change the mysql_query( ... ) on line 9 of your second posted code block to mysqli_query( ... ), for API consistency and compatibility.
Also, you could have duplicate results if you are allowing multiple entries in the conversation table where users A and B can be entered as user1 = A, user2 = B in one conversation, and user1 = B, user2 = A in a different conversation.
Lastly, as Jay Blanchard said, you should use prepared statements to avoid SQL injection.

Displaying link if no row exists in the database, otherwise display text

I have a table called flagged_posts in my database, and it has the following columns:
id
thought_id
flagged_by_id
What I am trying to do is that if the logged in user has already flagged the post, then don't allow them to flag the post again, and I am trying to achieve this by removing the anchor link and replacing it by a message.
Here is a snippet of my code:
<?php
$query = mysqli_query($connect, "SELECT * FROM user_thoughts WHERE added_by='$user' AND shared ='yes' "."ORDER BY id DESC LIMIT {$start}, {$limit}");
while ($row = mysqli_fetch_array($query)) {
$thought_id = $row['id'];
$message_content = $row['message'];
$date_of_msg = $row['post_details'];
$thoughts_by = $row['added_by'];
$attachent = $row['attachment'];
$shared = $row['shared'];
// getting the id of the user who is logged in.
$see_if_flagged_q = mysqli_query($connect, "SELECT id FROM users WHERE username = '$username'");
$getting_deets = mysqli_fetch_assoc ($see_if_flagged_q);
$logged_in_user_id = $getting_deets ['id'];
echo "
<div class='more_options' style='float: right;'>";
$see_if_flagged_q2 = mysqli_query($connect, "SELECT * FROM flagged_posts WHERE flagged_by_id ='$logged_in_user_id' ");
while ($getting_deets2 = mysqli_fetch_assoc ($see_if_flagged_q2)){
$flagged_post_by_id = $getting_deets2 ['flagged_by_id'];
// If the user logged in has not flagged the post, i.e. there is no data in the database ..
// .. which says their user id has flagged this thought_id.. then display the link...
if ($logged_in_user_id == $flagged_post_by_id){
echo "<a href='/inc/flagged_post.php?id=$thought_id'> Flag </a>";
}
// if there is data stating this user has flagged this thought_id, then echo a message
if ($logged_in_user_id != $flagged_post_by_id) {
echo "Flagged";
}
}
echo " </div>";
}
?>
So assume I am logged in as Conor. Conor has an id of 8 (id obtained from users table). Conor flags a post with an id of 209 (thought_id obtained from user_thoughts table). So in my flagged posts table, I will see the following row:
id: 1
thought_id: 209
flagged_by_id: 8
At the moment, neither link nor the message is appearing. If I change my query, i.e. $see_if_flagged_q2 = mysqli_query($connect, "SELECT * FROM flagged_posts "); (removed the WHERE clause) then I get the message Flagged echo'd four times (because there are four rows in the flagged_posts table and they are echo's on every post, even those which have not been flagged by the logged in user.
Update:
Here is the updated code first of all:
$see_if_flagged_q2 = mysqli_query($connect, "SELECT * FROM flagged_posts WHERE flagged_by_id = '$logged_in_user_id'");
$test_num = mysqli_num_rows ($see_if_flagged_q2);
$getting_deets2 = mysqli_fetch_assoc ($see_if_flagged_q2);
$flagged_post_by_id = $getting_deets2['flagged_by_id'];
if ($flagged_post_by_id == $logged_in_user_id){
echo "<a href='/inc/flagged_post.php?id=$thought_id'> Flag </a>";
echo $test_num;
}
if ($flagged_post_by_id != $logged_in_user_id) {
echo "Flagged";
}
With the above, the link appears for all posts now, even if they are flagged. I have echo'd both $flagged_post_by_id and '$logged_in_user_id', which both echo the value of 12 (the id of Conor from users table). The values are correct and the number of rows returned by $test_num is also correct.
Ok, here's a reworking of your original code. I moved the data gathering part up front, so we have a setup section before we run the while loop on the thoughts. I changed a variable name here and there. Basically, we build a list of flagged entries, and then in the while loop the job is simpler. If the current row id is in the flagged_posts array, it's flagged, else present the link.
// get the id of the current user
$user_id_q = mysqli_query($connect, "SELECT id FROM users WHERE username = '$username'");
$getting_deets = mysqli_fetch_assoc($user_id_q);
$logged_in_user_id = $getting_deets['id'];
// build array of posts flagged by current user
$flagged_posts_q = mysqli_query($connect, "SELECT thought_id FROM flagged_posts WHERE flagged_by_id = '$logged_in_user_id'");
$flagged_posts = array();
while ($row = mysqli_fetch_array($flagged_posts_q)) {
$flagged_posts[] = $row['thought_id'];
}
$query = mysqli_query($connect, "SELECT * FROM user_thoughts WHERE added_by='$user' AND shared ='yes' "."ORDER BY id DESC LIMIT {$start}, {$limit}");
while ($row = mysqli_fetch_array($query)) {
//You could just use $row['foo'] down below, and skip all this
/*
$thought_id = $row['id'];
$message_content = $row['message'];
$date_of_msg = $row['post_details'];
$thoughts_by = $row['added_by'];
$attachent = $row['attachment'];
$shared = $row['shared'];
*/
echo "<div class='more_options' style='float: right;'>";
if (in_array($row['id'], $flagged_posts)){
echo "Flagged";
} else {
echo "<a href='/inc/flagged_post.php?id=".$row['id']."'> Flag </a>";
}
echo "</div>";
}

MySQL / PHP - How to match an author id to a user id and display username

another question. I need to display a username and so what I'm doing is getting the author id (which is '1'), and then using a query saying get the username from the users table where the author id is the same as the user id.
My problem is that I'm getting the value of '1' returned as I've said above and the following is my code. Am I missing something here or...?
$users = mysqli_query($sql, "SELECT * FROM users WHERE userid = '$authorid'") or die($users . "<br/>" . mysqli_error($sql));
while($userData = mysqli_fetch_array($users)) {
$postAuthor = $usersData['username'];
}
Edit 1
I said also mention the above information should show the name 'Dan'.
The user 'Dan' has a user id of 1 should the author id should be 1 (which it is) from the post row. This is the only use of anything to do with the user table so it's not being overridden anywhere. I'm so confused.
This should have been an error:
while($userData = mysqli_fetch_array($users)) {
^^ no s
$postAuthor = $usersData['username'];
^^ used different variable name
}
Note: Use prepared statements also in this case, you're using mysqli anyways.
$select = $sql->prepare("SELECT * FROM users WHERE userid = ?");
$select->bind_param('i', $author_id);
$select->execute();
$results = $select->get_result();
while($userData = $results->fetch_assoc()) {
$postAuthor = $userData['username'];
}

PHP displaying info from two seperate tables

I have a web page that has a user database, each user has a unique User ID. Now I have created a login page where it starts a session, and the session includes the user ID.
I also have an "update status" option where the user types in a status and it submits the status and the users Unique ID into a new table. So the table will have the Users ID and the status that the user put in.
Now I want to display the users status on a page, and I want to display the user's Username along with it. So basically the code must take the user ID from the status table and then match it with the user ID from the Users table, and from that it must give me the username from the matching ID in the users table.
*FINAL WORKING CODE*
//Connect to mysql
mysql_connect("localhost","root","");
//connect to database
mysql_select_db("users");
//query the database
$query = "select * \n"
. " from status inner join users \n"
. " on status.user_id = users.id\n ORDER BY users.id DESC";
//fetch results / convert results into an array
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$s_firstname = $row['firstname'];
$s_lastname = $row['lastname'];
$s_status = $row['status']
}
I recommend spending some time learning about joins in sql. You would only need one SQL query, and it would be something like this...
select *
from status inner join users
on status.userid = users.userid
where active = '1' and connect = '1'
Edit: Although using mysql functions is not recommended (see the note at the top of this page - http://uk3.php.net/mysql_query), your lines should be like this..
$query = "select * from status inner join users on status.user_id = users.id where active = '1' and connect = '1'";
$result = mysql_query($query);
WHILE ($row = mysql_fetch_array($result)){
... rest of your code....

Implementing facebook-style "unlike" function

I've recently implemented a custom liking and disliking feature for my comics site. I'd like to give users the ability to "Take back" their selection by "unclicking" the like or dislike button.
My function works by:
1) Passing button value (id = 'like' or id = 'dislike') via Jquery to
php script
2) script will first check if an ip exists in the database against
that given comic id... if not it will insert user's IP and current
comic ID... if it does, it originally said "you've already voted"... but now to implement "unliking", I will just have it run a delete query
3) then it will get total current likes for that comic id and
increment.
The way I think it can be done is if the user presses the button again, I basically run the opposite query... delete that user's vote from the table given that comic id... then decrement total likes for that image in the comics table.
So my questions are,
1) Is doing an insert query if they press a button once, then a delete
query if they "deselect" that same choice the best way to implement
this? Couldn't a user spam and overload the database by continuously
pressing the like button, thereby constantly liking and unliking?
Should I just implement some sort of $_SESSION['count'] for that ID?
2) If I'm storing a certain IP... what happens if several uniques
users happen to use the same computer at... let's say a netcafe... it
will always store that user's IP. Is storing against the IP the best
way to go?
Code if you need a reference:
<?php
include 'dbconnect.php';
$site = $_GET['_site'];
$imgid = intval($_GET['_id']);
$input = $_GET['_choice'];
if ($site == "artwork") {
$table = "artwork";
}
else {
$table = "comics";
}
$check = "SELECT ip, tablename, imgid FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND tablename = '$table' AND imgid = $imgid";
$result = $mysqli->query($check);
if ($result->num_rows == 0) {
//Insert voter's information into votes table
$sql = "INSERT INTO
votes (ip, tablename, imgid)
VALUES
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)
ON DUPLICATE KEY UPDATE
imgid = VALUES(imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
/*while ($row = $result->fetch_assoc()) {
echo "you've inserted: " . $row['ip'] . ", " . $row['tablename'] . ", " . $row['imgid'] . ".";
}*/
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") {
$sql = "UPDATE $table SET like_count = like_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes++;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes++;
}
}
else { //"unlike" their previous like for that given image id
$sql = "DELETE FROM
votes
WHERE (ip, tablename, imgid) =
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") { //remove like
$sql = "UPDATE $table SET like_count = like_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes--;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes--;
}
}
echo "Likes: " . $likes . ", Dislikes: " . $dislikes;
mysqli_close($mysqli);
?>
1) I would say yes, use a count feature to limit the number of attempts they can hit the button in succession. Probably wouldn't have much trouble unless they hit really high numbers, I believe a simple loop would do fine.
2) I would not store just the IP. I would try and use something more than just the IP as an Identifier, like the IP and the session cookie - that way it's unique. However on the look back to the server you would have to parse the entry from the db. Or perhaps the mac address. I'm not sure if you have access to that or not. How can I get the MAC and the IP address of a connected client in PHP?
I'm sure there's another way but conceptually that's how I see it working.

Categories