Display number of user favourites / notifications - php

I am new to php and the mvc structure, however I am developing a library app for personal development. All is working as expected however I would like to implement one more feature - 'favourites'.
A notifications style bar contained within a <div>.
I currently have a favourites table that contains the following;
id book_id user_id
1 2422 22
2 6551 71
3 7716 22
What I am trying to do is simply display to the logged in user (eg user 22 above) "Hello, you have 2 items in your favourites". I know this should be relatively simple and it would normally be, however the mvc format has me slightly confused.
I think I have the bulk of the work done I just need some direction and advice as to where I am going wrong. Is there something else I should be loading or including? How should I display the number of favourites within the <div>?
I have included my code below for reference.
books_controller.php
function checkFav()
{
$checkFav_model = $this->loadModel('Books');
$checkFav_model->wishList();
}
function itemView()
{
$itemView_model = $this->loadModel('Books');
$this->view->books = $itemView_model->itemView();
$this->view->render('books/itemView');
}
books_model.php
public function wishList()
{
$userid=$_SESSION['user_id'];
$sql = "SELECT COUNT(*) FROM favourite WHERE user_id = :user_id";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->execute();
$rows_found = $query->fetchColumn();//numRows doesnt work
if(empty($rows_found)) {
echo $rows_found;
} else {
echo $rows_found;
}
}
header.php
<div class="notifications">
**DISPLAY NUMBER OF FAVS HERE**
</div>

Try this query:
$sql = "SELECT COUNT(book_id) AS book FROM favourite WHERE user_id = :user_id";
Reason : User has many favorite book. And your quote adbove
"Hello, you have 2 items in your favourites"
so i think you want to showing how much book he likes. Not how many times he liked the book. But it can be done to with SUM on user_id.

Hmm maybe this way:
$sql = "SELECT COUNT(id) as count FROM favourite WHERE user_id = :user_id";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->execute();
$rows_found = $query->fetchAll();
$rows_found = $rows_found[0][count];

Related

else if condition while comparing 2 variables in php

I am new to php so far i wrote this referral script:
<?php
ob_start();
include( $_SERVER['DOCUMENT_ROOT'] . '/config.php' );
mysql_connect(DB_HOST,DB_USER,DB_PASS);
mysql_select_db(DB_NAME);
$id = $_REQUEST['id'];
$uid = $_REQUEST['uid'];
$oid = $_REQUEST['oid'];
$new = $_REQUEST['new'];
$total = $_REQUEST['total'];
$sig = $_REQUEST['sig'];
// Secrete Key
$hash = 'myapikey';
// Output results
if ($sig == $hash) {
//Users point update query here (it's working )
$users = mysql_query("SELECT points FROM users WHERE id=".$uid);
$rows = mysql_fetch_array($users);
$user_points = $rows['points'];
$query1 = mysql_query("update users set points=($user_points+$new) where id=".$uid );
//Updating referral coins (it's not working )
$query2 = ("SELECT points, referral_id, level FROM users WHERE referral_id=".$uid );
$user_rows = mysql_query($query2);
$all=mysql_fetch_array($user_rows,MYSQL_BOTH);
if($all['referral_id'] != 0 && $all['level'] == 0){
$lvl0 = $new*(15/100);
$referal_points = $lvl0;
$update_referral_points = ("update users set points = points + $referal_points where referral_id = ".$all['referral_id']);
mysql_query($update_referral_points);
} else if($all['referral_id'] != 0 && $all['level'] == 1){
$lvl1 = $new*(25/100);
$referal_points = $lvl1;
$update_referral_points = ("update users set points = points + $referal_points where referral_id = ".$all['referral_id']);
mysql_query($update_referral_points);
}
print "1\n";
} else {
print "0\n";
}
?>
How Script working:
whenever someone signup using referral code i have insert referral code user id into new user referral_id row, & through $_REQUEST['']; my app sending points ($new) to user...
$query1 is working fine there's problem to execute $query2, in short $query2 needs to be fixed; something getting wrong, that i am not able to figure out if any pro can help me out this i will appreciate it...
DB structure:
users table:
id (AI) name points Referral code Referral id Level
=========== ========== ========== ================== ============== ======
1 user A 0 abcdef123 0 0
2 user B 100 bvsuda897 1 1
3 user C 500 vrtasio65 2 0
In this example above,
1- user C signup using user B Referral code = bvsuda897
2- right now user B level is 1 so whenever user C earn point ($new) my app should give user B 25% coins of user C $new
The Problem
right now when my app sending coins to user C, user B not getting coins, because something wrong in query2
After spending some more time looking over your code, I have tracked down your issue. First, you need to get the referral_id from the $users query.
$users = mysql_query("SELECT points, referral_id FROM users WHERE id=".$uid);
Then $query2 needs to match the id to the user's referral_id, not the other way around.
$query2 = "SELECT id, points, referral_id, level FROM users WHERE id=".$rows['referral_id'];
Your UPDATE queries may need some work after that, but this will get you in to the if else conditions.
Successful code determined by OP
//Updating referral coins
$query2 = "SELECT id, points, referral_id, level FROM users WHERE id=".$rows['referral_id']; $user_rows = mysql_query($query2);
$all=mysql_fetch_array($user_rows,MYSQL_BOTH);
$lvl0 = intval((5/100) * $new);
$lvl1 = intval((10/100) * $new);
$query3 = mysql_query("update users set points = (points + $lvl0) where level = 0 AND referral_id = ".$all['referral_id']);
$query4 = mysql_query("update users set points = (points + $lvl1) where level = 1 AND referral_id = ".$all['referral_id']);
Now I appreciate that you are in the learning stage, but I want to point out a couple things that will cause confusions as you pursue PHP programming in the future.
First off, as Option mentioned, the MySQL functions you are using have been deprecated. They do not exist in the current stable version of PHP, and your code will no longer work if the server is updated. Look in to MySQLi or PDO as alternatives. It's a lot to learn, but some Googling will get you some guidance.
Second is your use of $_REQUEST, which combines the values of $_GET, $_POST and $_COOKIE, allowing easy manipulation by visitors. It may be that you are only using it for the user details while testing your other code, but I just want to make sure you know about PHP sessions, which is the better way to store a relationship between a logged in user and their persistent variables.

Can't get this SQL / PHP query correct, trying to view details according to specific ID

Before I show what I have tried, i'll just explain my scenario. I have three tables. Genre, Games, GameGenre.
Genre = The different game genres (Action, Adventure, Multiplayer)
Games = The different games (example 1, example 2, example 3)
GameGenre = the grid and the gaID and also the ggID (genre, game and gamegenreID)
Currently how this works is, firstly you would create a game genre, then add specific games to that genre. So they both have a geID and a gaID.
Now, what I am trying to do is display these according to genre. So that when I choose a genre, only games which have that genre are listed. Hence I have the ggID.
Code:
mysql_query("SELECT * FROM Genre WHERE gaID == geID = '$ggID'");
while($row = mysql_fetch_array($results)){
$geID = $row['geID'];
$gaID = $row['gaID'];
echo statements here.
}
This does not work though, any help please?
Did you tried this ?
mysql_query("SELECT * FROM Genre WHERE gaID = '$ggID' AND geID = '$ggID'");
Try
mysql_query("SELECT * FROM Genre WHERE gaID = geID AND geID = '$ggID'");
SQL is not C++, and = is not an assignment operator, so A = B = C doesn't make sense. And there is not == in SQL.

Get Referrer ID

Im trying to modify this wordpress plugin of mine to track the name of who reffered the current logged user.
So far I managed to build the code below, but i'm very new with any kind of coding and I would be very thankfull if I get some help.
The idea is to get the "parent_user_id" (the referrer id) from the current user, them use this ID to get the login_ID.
Actualy this code is outputting this: "Referred by: Array"
function wpmlm_display_referrer() {
global $wpdb, $user_ID, $current_user;
if(isset($_GET['current_user_id']) && !empty($_GET['current_user_id'])) {
$current_user_id = $_GET['current_user_id'];
} else {
$current_user_id = $current_user->ID;
}
# Logged in user
if ( is_user_logged_in() == true ) {
$get_id = "SELECT parent_user_id FROM mlm WHERE user_id=%d".$current_user_id;
$get_name = "SELECT login_id FROM mlm WHERE user_id=%d".$get_id;
$ref = $wpdb->get_results($get_name);
return 'Referred by: '.$ref;
}
}
Thank you for any help you can provide in this situation.
please try this:
$get_id = "SELECT parent_user_id FROM mlm WHERE user_id='".$current_user_id ."'";
$get_name = "SELECT login_id FROM mlm WHERE user_id='".$get_id ."'";
I have just edited the query.
Now second thing is that $get_id is the variable containing the query so if you want to write the sub-query write it like below:
you below if parent_user_id from the sub query will return 1 value
$query = "SELECT login_id FROM mlm WHERE user_id=(SELECT parent_user_id FROM mlm WHERE user_id='".$current_user_id ."')";
use below if the sub query will return multiple values:
$query = "SELECT login_id FROM mlm WHERE user_id IN (SELECT parent_user_id FROM mlm WHERE user_id='".$current_user_id ."')";
and Then try print_r($ref);
you would get the value in the array. and once you see the value use the proper index of the array to get the value.

How do i GROUP BY or DISTINCT inside array?

I have searched high and low and cant find a similar issue to what i have.
I am a beginner so please forgive my clunky query structure.
I am trying to ( have attached screen grab below of output ):
Query the photos table to get the id based on category id and also start,limit because of pagination.
Query the photos tagged table based on the photo id i just got from the first query.
But my problem is that i cant group the tags, some photos have the same tag name. And the output just shows all the tags for each photo. I want restaurant to show only once etc...
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT tag_name FROM photoTagged WHERE file_id=".$rowFile['id']." GROUP BY tag_name";
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
while ($rowTagged = mysql_fetch_array($resultTagged)) {
$tagged = $rowTagged['tag_name'];
?>
<li><a href="#"><?php echo $tagged; ?></li>
<?php }} ?>
the above query is producing:
bar,cappucino,coffee,coffee machine,restaurant,bar,cappucino,coffee,coffee machine,restaurant,bar,coffee,restaurant,bar,coffee,coffee machine
restaurant,bar,cappucino,coffee,restaurant
what i need to show is:
bar,cappucino,coffee,coffee machine,restaurant
If anyone could help i would greatly appreciate it.
Thank you in advance.
John
My new code is
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT DISTINCT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'];
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
$rowTagged = mysql_fetch_array($resultTagged);
$tagged = $rowTagged['tag_name'];
?>
<li><a href="#"><?php echo $tagged; ?></li>
<?php } ?>
I now get this: ( So i am close arent i? )
----------
cappucino
restaurant
bar
coffee machine
restaurant
coffee
coffee
restaurant
restaurant
restaurant
coffee
coffee
restaurant
restaurant
coffee machine
restaurant
coffee
I wonder if the spaces are something? i got that from copy and paste...
Any further help would be appreciated :-)
You should first perform a join between your photos and tags table, and THEN select the distinct tags.
I believe this query will let the database do all the work for you:
SELECT DISTINCT tag_name
FROM (SELECT file_id FROM $tableName WHERE cat_id=$fileID LIMIT $start, $limit) t1
LEFT JOIN photoTagged ON t1.id = photoTagged.file_id
You can also sort the tags in the database (ORDER BY tag_name).
Haven't tried it myself, so maybe the syntax is a bit off. But the idea should work.
distinct doesnt work if you are only getting one record at a time, so put the data in a PHP array and then use array_unique, which is PHPs way to do distinct
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'];
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
$rowTagged = mysql_fetch_array($resultTagged)
$tagged[] = $rowTagged['tag_name'];
}
// Let PHP do the work.
$tagged=array_unique($tagged);
while (list(,$val) = each($tagged)) {
echo "<li><a href="#">$val</li>
}
?>
you need to do a sub-query to dodge the pagination problems with the photos. If you wish the selected tags to be a subset of the photos found in your first query, then you will need to do the following.
<?php
$queryTagged = "SELECT TAG.tag_name, count(TAG.tag_name) AS num FROM photoTagged as TAG JOIN (SELECT id FROM $tableName WHERE cat_id=$fileID LIMIT $start, $limit) as PHOTO ON (PHOTO.id = TAG.file_id) GROUP BY TAG.tag_name";
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
while ($tagged = mysql_fetch_assoc($resultTagged)) {
echo "<li id="'.$tagged['TAG.tag_name'].'"><a href="#">".$tagged['TAG.tag_name']." (".$tagged['TAG.num'].")</li>";
}
?>
This way you will have two queries, on for finding the photos, and one for finding the tags for the photos on that page. This technically takes a little longer as MySQL has to load the query into a temporary table, but it should work fine.
SELECT DISTINCT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'] ?

Merging data from two different data sets (Facebook & MySQL)

I'm wondering if this is the best way to tackle this issue. I am merging a Facebook users friends data, (from facebook - returns a multi array) with the votes from the users in that list that voted (from MySQL).
This is how I accomplished this. I'm a junior developer and looking for help on making my code as optimized as possible.
public function getFriendVotes(){
global $facebook;
// Get The users friends that use this app from facebook
$friends = $facebook->api_client->fql_query(
"SELECT uid, first_name, last_name
FROM user
WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=$this->user)"
);
// Create an array of just the ids
foreach($friends as $friend){
$userids[] = $friend['uid'];
}
// Create a string of these ids
$idstring = implode(",", $userids);
// Get the votes from only the users in that list that voted
$result = $this->db->query(
"SELECT vote, userid FROM user_votes WHERE userid IN ($idstring)"
);
// Create a new result set (multi array). Include the data from the first
// Facebook query, but include only those who voted and append their votes
// to the data
$row = $result->fetch_assoc();
foreach($friends as $friend){
if($row['userid'] == $friend['uid']){
$return[$count] = $friend;
$return[$count]['vote'] = $row['vote'];
$row = $result->fetch_assoc();
$count++;
}
}
return $return;
}
I asume that fql_query does support mysql syntax and it would be more efficient to use LEFT JOIN instead creatig extra query, here is my version of your code:
public function getFriendVotes(){
global $facebook;
// Get The users friends that use this app from facebook
$friends = $facebook->api_client->fql_query("
SELECT DISTINCT u.uid,u.first_name,u.last_name
FROM user AS u
LEFT JOIN friend AS f ON uid=uid2
WHERE f.uid1='{$this->user}'
");
$arrayUsers = array();
// Create an array of just the ids
foreach($friends as $v){
$arrayUsers[$friend['uid']] = $v;
}
unset($friends);
// Create a string of these ids
$idstring = implode(",", array_keys($arrayUsers));
// Get the votes from only the users in that list that voted
$result = $this->db->query(
"SELECT vote, userid FROM user_votes WHERE userid IN ({$idstring})"
);
$result = array();
// Create a new result set (multi array). Include the data from the first
// Facebook query, but include only those who voted and append their votes
// to the data
while($v = $result->fetch_assoc())
{
if(isset($arrayUsers[$v['userid']])
{
$arrayUsers[$v['userid']] = $v['vote'];
$result[] = $arrayUsers[$v['userid']];
unset($arrayUsers[$v['userid']], $v);
}
}
return $return;
}
I can't tell you how your code would perform without measuring and testing. I would look for other issues with your code, that would make it a bit more readable/maintanable. For example:
Create smaller methods.
Inside the main method , I see some chunks of code that are well commented. Why not create a method instead of making a huge comment in the main method?
For example:
// Get The users friends that use this app from facebook
$friends = $facebook->api_client->fql_query(
"SELECT uid, first_name, last_name
FROM user
WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=$this->user"
);
return $friends;
Would make an interesting
functin get_users_friends_from_facebook($facebook){
// Get The users friends that use this app from facebook
$friends = $facebook->api_client->fql_query(
"SELECT uid, first_name, last_name
FROM user
WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=$this->user"
);
return $friends;
}
In the same manner,
// Get the votes from only the users in that list that voted
$result = $this->db->query(
"SELECT vote, userid FROM user_votes WHERE userid IN ($idstring)"
);
Is a good candidate to
function get_votes_from_voters(){
// Get the votes from only the users in that list that voted
$votes = $this->db->query(
"SELECT vote, userid FROM user_votes WHERE userid IN ($idstring)"
);
}
Give variables meaningful names to the context.
$return isn't a good name. Why don't you name it $users_votes for example?
Try to keep the naming convention of your plataform.
Check the apis you're using. Are they using camelCase? Are they using underscores? Try to keep with your libraries and plataform conventions. Check this topic for a good reference.
And welcome to SO. Your code is fine. Try to read some OO principles, you could even cut more lines of your code. All the simple advices I wrote here are avaiable in a great book named Code Complete.
I took points from all your comments and rewrote this method as below. Thanks for all the great input.
public function getAppUserFriends(){
global $facebook;
return $facebook->api_client->fql_query(
"SELECT uid, first_name, last_name
FROM user
WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=$this->user)
AND is_app_user;"
);
}
public function getFriendVotes(){
// Get the users friends that use this app
$friends = $this->getAppUserFriends();
// Create an array with the ids as the key
foreach($friends as $v){
$arrayFriends[$v['uid']] = $v;
}
// Create a string of these ids
$idString = implode(",", array_keys($arrayFriends));
// Get the votes from only the users in that list that voted
$result = $this->db->query(
"SELECT vote, userid
FROM user_votes
WHERE pollid=$this->poll
AND userid IN ($idString)"
);
// Pluck out user data from facebook array where the user has voted
// and add the vote to that array
while($row = $result->fetch_assoc()){
$friendsVotes[$row['userid']] = $arrayFriends[$row['userid']];
$friendsVotes[$row['userid']]['vote'] = $row['vote'];
}
return $friendsVotes;
}
Are you having performance troubles in this method? Because unless you are, there's no need to optimize it.
Code first, profile the code, and then optimize where it does the most good.
$friends = $facebook->api_client->fql_query(
"SELECT uid, first_name, last_name
FROM user
WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=$this->user"
);
could probably be shortened to
$userids = $facebook->api_client->fql_query(
"SELECT uid
FROM user
WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=$this->user)"
);
because the uid is the only thing you seem to be using from fb
It was a little hard for me to tell what you are trying to do, but you might consider looking at PHP's array_intersect (and its cousins).
A = {1:'fred', 2:'bob'}
B = {1: 2, 3: 0}
C = array_intersect( array_keys(A), array_keys(B) )
D = {}
foreach (C as c) {
D[c] = (A[c], B[c])
}
The syntax is off there but I hope it leads you in the right direction.

Categories