I'm trying to get this pendingsubmission function to work properly. The way its suppose to work is if a manager logs into his account and has pending timesheets to review i want somekind of notification to the manager that there are pending timesheets.
Here is my code so far although it only works for the first result (first timesheet, does not get manager for all other timesheets submitted) i apologize if this is confusing.
function pendingsubmissions($loggedInUser) {
include("table_names.inc");
global $authenticationManager;
list($qh, $num) = dbQuery("SELECT uid FROM $TIMES_TABLE WHERE submitstatus=1 OR ot_status=1");
while ($data = dbResult($qh)) {
$username = $data['uid'];
list($qh2,$num2) = dbQuery("SELECT manager FROM $USER_TABLE WHERE username='$username'");
while ($data2 = dbResult($qh2)) {
$manager = $data2['manager'];
if ($loggedInUser == $manager || $authenticationManager->hasClearance(CLEARANCE_ADMINISTRATOR))
return 1;
else
return 0;
}
}
}
The first query is to check the database for timesheets that are pending (submit status 1).. if there are any found then the second query is to find out that users manager and then if that users manager is currently logged in, spit out the true value.
The problem is the first query as of now it is showing as follows:
uid
---
user1
user1
user1
user2
user2
user2
and the second query is only checking for user1 manager name.. doesnt check user2.. can someone help fix this so it checks every user for manager-name
thanks
As already mentioned, you can use DISTINCT, or GROUP BY a value such as uid.
This could also be achieved with a single query. Something like:
SELECT manager FROM $USER_TABLE WHERE username IN (SELECT DISTINCT uid FROM $TIMES_TABLE WHERE submitstatus=1 OR ot_status=1)
This saves you sending two requests to the database.
You're also overwriting your values each time, instead of:
while ($data = dbResult($qh)) {
$username = $data['uid'];
You will want to do something like:
$usernames = array();
while ($data = dbResult($qh)) {
$usernames[] = $data['uid'];
You should write a single query with a JOIN between the 2 tables. At present you are only asking the second query to look for one value!
Also, punctuation is as important in English as it is in programming. Please use apostrophes where they are required. It makes reading your question much easier.
Related
Hey I want to create like system in php But I am facing some problem on it ...
How can I create Like system that allow only one like per one user??
This is my code
<?php
if(isset($_POST['like'])){
$q = "SELECT * FROM likes WHERE `username` = '".$_SESSION['recieveruser']."'";
$r = mysqli_query($con, $q);
$count = mysqli_num_rows($r);
if ($count == "0") {
$q1 = "INSERT INTO likes (`username`, `likecount`)VALUES('".$_SESSION['recieveruser']."', '1')";
$result1 = mysqli_query($con, $q1);
} else {
while($row = mysqli_fetch_array($r)) {
$liked = $row['likecount'];
}
$likeus = ++$liked;
$q2 = "UPDATE likes SET likecount='".$likeus."' WHERE username = '".$_SESSION['recieveruser']."'";
$result2 = mysqli_query($con, $q2);
}
}
give me some suggestions
I want only one like per user
In this code every user can give Many likes to another user but I want only one like per one user and I want to display the name of the user who gave like if it's possible
This is only user like code...
I created simliar like system on my website. In my likes table, I had these columns:
Id of comment, that has been liked
Id of user who liked
Id of like (for removal)
When user clicked like, I inserted new row into likes table, with two known values. ID of like was autoincremented.
To show number of likes, I filtered by id of comment and grouped by users id (just to be sure). The number was obtained using count.
select count(*) from likes where comment_id = 666 group by user_id;
Even if you let user insert multiple times, the like counts only as one. But best would be to check, if current user already liked and dont let him do that. For this task, insert on duplicate key update could be used, to spare if exists db request (select).
You should not use the code you posted above. First of all, your code is vulnerable to SQL-Injections and therefore you should use Prepared Statements (https://www.php.net/manual/de/mysqli.quickstart.prepared-statements.php). Second, $_SESSION variables are depricated (https://www.php.net/manual/en/reserved.variables.session.php).
Lets assume you want users only to be able to like a post once. Then, instead of the column likecount you would need a post-id which uniquely identifies the post.
Define the combination post-id and username as a primary key in your database.
Now your code just have to check whether you find the username with the according post-id in the table likes.
In case you do not find the username with the according post-id in the table, you have to INSERT the username and the post-id
Is there a way to check if a value exists in a mysql column? I have table songs, and there are some columns, one of them is called 'agent_ip' where i will put a list/array of all user ip's that will visit the site. I need to check if current user ip is present in column 'agent_ip'. Here is some of my code:
public function voteSong($song_id, $case, $agent_ip) {
$query = $this->link->prepare("SELECT * FROM songs WHERE id = ? LIMIT 1");
$query->bindValue(1, $song_id);
$query->execute();
$rowcount = $query->rowCount();
if ($rowcount != 0)
{
if (!in_array($agent_ip, $r['ip']))
{
if ($case === 'like')
{
while($r = $query->fetch())
{
$vote = $r['votes'] + 1;
}
}
elseif ($case === 'dislike')
{
while ($r = $query->fetch())
{
if ($r['votes'] > 0)
{
$vote = $r['votes'] - 1;
}
else
{
$vote = 0;
}
}
}
$query = $this->link->prepare("UPDATE songs SET datetime = ?, votes = ?, agent_ip = ? WHERE id = ?");
$query->execute(array(date("Y-m-d H:i:s"), $vote, $agent_ip, $song_id));
}
}
}
The line if(!in_array($agent_ip, $r['ip'])) contains the wrong function which won't work, but i need an alternative for mysql. $r['ip'] variable is data from the 'agent_ip' column which look like this 127.0.0.1, 127.0.0.1, 127.0.0.1 (using 127.0.0.1 just for example, every 127.0.0.1 is a different ip)
If you're only checking against a single IP, why don't you just modify your query from:
"SELECT * FROM songs WHERE id = ? LIMIT 1"
To:
"SELECT * FROM songs WHERE id = ? AND agent_ip = ? LIMIT 1"
It seems a bit wasteful to query your whole result set when you are only querying against a specific IP and returning a single row.
EDIT: Your current method would be extremely inefficient, you are passing a unique agent_ip each time you want to query a song to check if the IP exists, that would be fine, but you are creating a new DB connection every time from which you pull back all info which belongs to that song.
Lets say we have 1 song, and 3IP's, currently the application would work like this:
1) Call the method, passing IP_1
2) Query the database getting all songs for ID1
3) Check if IP_1 is in the result set and do process
4) Call the method, passing IP_2
5) Query the database getting all songs for ID1
6) Check if IP_2 is in the result set and do process
7) Call the method, passing IP_3
8) Query the database getting all songs for ID1
9) Check if IP_2 is in the result set and do process
As you can see, there is a lot of repetition here which is going to hinder your apps performance as it scales, you would be so much better modifying your current function to accept a list of results for a song which is pre-queried only once and then recursively call a check function by passing that result array with your unique IP address.
UPDATE You stated I understand that i need to have 2 tables(1 = songs; 2 = votes). But i cannot imagine how i will get songs from database, arranged by votes quantity.
You should read SQL's JOIN documentation, the concept is simple - JOIN allows you to pull back a more detailed set of information based on what you want to query, in your example you may want to find out how many votes a specific song has.
Your tables may look like:
Songs
SONG_ID Primary Key
SONG_TITLE
SONG_DURATION
SONG_TAGS
Votes
VOTE_ID Primary Key
SONG_ID Foreign Key - (references the song_id table)
VOTE_RES Bool (either 0 for no, 1 for yes)
AGENT_IP Who sent the vote
You could then find out how many people said they liked the song by performing a join:
SELECT * FROM songs
JOIN votes
ON songs.song_id = votes.song_id
WHERE songs.song_id = 1
AND votes.vote_res = 1;
This would return all the song with the id of 1 and all of its associated likes. Hope that helps a bit :)
First you need to deserialize/decode the data from the column to the proper php array and then you can use in_array function. In your post edit you stated that you have a comma separated list of IP's, so to convert it to array you need to use an explode function:
$ip_list = explode(', ', $r['ip']);
now you can use the in_array function on the new array:
if(!in_array($agent_ip, $ip_list))
I am building user status app where other can comment. I fetch the json result through ajax and then display it in my ap. however my problem is when i run the query it return only one run for each replies even though there are multiple replies for each status. Honestly i dont know whether the problem is from the PHP loop or it is from the SQL queries it self. I have battling with this since two days now and have search other Stackoverflow question for help but still. I will be glad if anyone can help me. Thank you.
User status are saved in the Status table and all replies on each status is saved in the replies table.
These are my tables
Users Table = gcm_users
id
name
date
Status Table = gcm_status
id
userID
status
Replies Table = gcm_status_replies
id
statusID
userID
replies
This is my sql statement
$sqlSelect = ( 'SELECT gcm_status.status,
gcm_status.id,
gcm_status.userID,
gcm_status_replies.id,
gcm_status_replies.statusID,
gcm_status_replies.userID,
gcm_status_replies.message,
gcm_users.id,
gcm_users.name
FROM gcm_users INNER JOIN gcm_status
ON gcm_users.id = gcm_status.userID
INNER JOIN gcm_status_replies
ON gcm_status.id = gcm_status.id'
array(''), $conn);
PHP Loops is
foreach ($sqlSelect as $row) {
$respohnds = json_encode($row);
echo $respohnds;
}
I really need to help.
You're generating a separate json object for each row, and returning them one by one.
Maybe you should do this instead to return a single json object encoding your whole result set as an array.
$respondhs = array();
foreach ($sqlSelect as $row) {
$respohnds[] = json_encode($row);
}
echo $respohnds;
I have tried upto end everything to the best of my knowledge but all in vain. I'm building a community website and i am stuck at one thing. I want to display a text on my wall when my friends become friends with other users. Just like Facebook displays it. For eg.
"John doe is now friends with max stone"
And
"John doe is now friends with max stone and 5 other people"
I am successfully getting it displayed but not like the one I showed above. I do it using while loop from notifications table. I tried but couldn't get it like facebook shows. so please help me get this thing done.
I am posting my code so that you can get clear idea of my code and my mistakes in my code so you can clear.
$ check_if_friendship_created = mysql_query ("SELECT * FROM `users_notifications`
WHERE `friend_1_username` IN (SELECT `friend_2_username` FROM `users_friends`
WHERE `friend_1_username` = '". $ logged_user ['username']."')
GROUP BY `friend_2_fullname` ORDER BY `notification_time` DESC");
also to let you all know that my friends table is a symmetrical in design...
looking forward to your positive reponse. Thank you....
why don't you have a separate table for friendship notification? Meaning when user1 is friend with user2 you insert the details to the friendship notification table.
table structure
id reqeust_sent_by request_accepted_by friendship_date
So let's assume John sends friend request and then Jack accepts the request, when Jack accepts the request then you insert that detail to the table. You better use mysqli prepared statements or pdo. So here is mysqli prepared statements
$request_sender = 'John';
$logged_user = 'Jack';
$date = date('Y-m-d H:i:s');
$mydabtase = new mysqli('localhost', 'root', '', 'database_name');
$stmt = $mydatabse->prepare("insert into friendship_notification (request_sent_by, request_accepted_by, friendship_date) values (?,?,?)");
$stmt->bind_param('sss' $request_sender, $logged_user, $date);
$stmt->execute();
$stmt->close();
now to select the data you can do
$stmt = $mydatabase->prepare("select * from friendship_notification where request_sent_by ! = ? or requst_accepted_by ! = ? order by id desc");//do your select here. here we are selecting where either rows are different from the logged in user because we don't want to show the logged in user that he has became friends with somebody else, we show this for other users.
$stmt->bind_param('ss', $logged_user, $logged_user);//follow the same procedure when binding the parameters, s means string. if you have 2 ? then you need 2 s along with 2 variables.
$stmt->execute();
$result = $stmt->get_result();//this gets the results
$total = $result->num_rows;//this returns the total number of rows for the above select query
while($row = $result->fetch_assoc()){
//if the total is less than 3 people we do the below
if($total < 3){
echo $row['request_accepted_by']."is now friends with".$row['request_sent_by'].",";
}
elseif($total > 3 ){
$stmt2 = $mydatabase->prepare("select * from friendship_notification where request_sent_by ! = ? or requst_accepted_by ! = ? order by id desc limit 1");//do your select here
$stmt2->bind_param('ss', $logged_user, $logged_user);
$stmt2->execute();
$result2 = $stmt2->get_result();
$row2 = $result2->fetch_array();//we only need one row so no need for while loop.
echo $row['request_accepted_by']."is now friends with".$row2['request_sent_by']."and ".$total-1." others.";
}
}
So this will display something like
John is now friends with Max and magna. and on the second case
John is now friends with Max and 4 others.
if you want the facebook way then you need to use ajax to auto refresh.
I have a system where a PHP script uses MySQL to get info based on a user. Then, based on that information, a certain button will be displayed. The database that is being called has columns:
id
user_one
user_two
This is meant to check if two users are friends. However, my problem is that if a user has more that 1 friend the script only works for the 1st friend.
$select_friends_query = mysql_query("SELECT friend_id FROM friends WHERE user_id = '$user'");
while($friend_row = mysql_fetch_assoc($select_friends_query)) {
$friend = $friend_row['friend_id'];
}
if ($username == $friend) {
$addAsFriend = '<input type="submit" class = "frnd_req" name="removefriend" value="Disassociate">';
}
else
{
$addAsFriend = '<input type = "submit" class = "frnd_req" name = "addfriend" value = "Send Associate Request">';
}
}
}
Then I have echo $addAsFriend later.
I recommend that you change your database design as follows:
User_id, PK
Friend_id, PK
PK = Primary Key. Primary key is the key under which records are stored. It must be unique. The reason we are making it a COMPOUND primary key (two fields make up the PK instead of 1) is because it is impossible for a user to be friends with with the same user Multiple times. Mysql will ensure this does not happen and you won't have to do it on the application level.
Thus, if user "12" and user "25" become friend you should two records:
(12, 25) and (25, 12)
You must have two records because data means literally "user this has friend that." Is it possible for two users to have a one way friendship - not really BUT you may want to one day expand this table to include preferences on the relationship type between the two friends and you would want to distinguish between A -> B and B -> A relationship.
So let's get to the meat of the question. To query mysql to find all friends to a specific user we do the following:
$sql = "SELECT friend_id FROM friends WHERE user_id = 25;";
$query = mysql_query($sql, $connection);
// Loop through all friend records
while ($row = mysql_fetch_assoc($query)) {
$friends[$row['friend']];
}
I don't use procedural code (mysql_query) and instead use mysqli with OP: $mysql->query(). basically, I am not 100% sure if this code will run but it gives you a guide to get started.
At the end of the program, you will have an array "friends" with keys that tell you the friend ids. So "friends" -> 12, 21 could be a potential data set.
You have to look over all results. Like the while loop example in http://www.php.net/manual/en/function.mysql-fetch-assoc.php