Get all favorites for current user - php

I've got a table in the database called "favorites" with 3 columns (user_id, bookmarked_song_id, bookmark_tag) and I want to get all the Bookmarked_song_id for the current user.
$username = $this->session->userdata('username');
$uidq = mysql_query('SELECT user_id FROM users WHERE username="' . $username . '"');
$rq = mysql_fetch_assoc($uidq);
$user_id = $rq['user_id'];
$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id");
$favsr = mysql_fetch_array($getfavq); //contains all the information from the favorites database where user_id is the user_of the currently logged-in user
And I don't know what to use next... I want to have something like:
foreach($favsr['bookmarked_song_id'] as $song_id) {
$getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id");
$getsongr = mysql_fetch_assoc($getsongq);
$singer = $getsongr['singer'];
$song_name = $getsongr['song_name'];}
Obviously the method is wrong because I get: "Invalid argument supplied for foreach()". Can anyone help me with getting the songs? Thanks in advance.

It should be this:
$favsr = mysql_fetch_array($getfavq, MYSQL_ASSOC);
foreach($favsr as $row) {
$songid = $row['bookmarked_song_id'];
...
}

mysql_fetch_array only loads one row,
it should be like that
$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id");
while $favsr = mysql_fetch_array($getfavq);
{$songid=$favsr['bookmarked_song_id'];
$getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id");
$getsongr = mysql_fetch_array($getsongq);
$singer = $getsongr['singer'];
$song_name = $getsongr['song_name'];}

You have this tagged with codeigniter. If you've building a CodeIgniter application, you should probably use CI's database library:
$username = $this->session->userdata('username');
//Select your user
$this->db->select('user_id');
$this->db->where('username', $username);
$this->db->limit(1);
$user_query = $this->db->get('users');
if($user_query->num_rows() > 0)
{
// We found a user
$user = $user_query->row(); // select a single row
// Grab this user's favorites
$this->db->where('user_id', $user->id);
$favorites_query = $this->db->get('favorites');
$songs = $favorites_query->result();
if($songs)
{
foreach($songs as $song)
{
$song_id = $song->bookmarked_song_id;
$tag = $song->bookmark_tag;
// Do stuff with data.
}
}
else
{
// No songs/favorites found, catch error
}
}
else
{
// No such user found, catch error
}
Of course, the best practice is to have your user data and your favorites data in separate models, but this should work for now.

Related

Multiple Result Data in json Response

I am new in PHP and trying to build one API which provide me json response of required data. There one table called user and I need email, username and user_type from it. I have coded like below for do it
$result = array();
$users = getOnlineUsers($conn);
$userinfo['email'] = $users['email'];
$userinfo['username'] = $users['username'];
$userinfo['user_type'] = $users['user_type'];
$result['status'] ="success";
$result['userData'] = $userinfo;
And function is like below
function getOnlineUsers($conn)
{
$q = $conn->prepare("SELECT * FROM table_users WHERE online_status = 1");
// $q->bind_param("s", $email);
$q->execute();
$result = $q->store_result();
$metaResults = $q->result_metadata();
$fields = $metaResults->fetch_fields();
$statementParams='';
foreach($fields as $field){
if(empty($statementParams)){
$statementParams.="\$column['".$field->name."']";
}else{
$statementParams.=", \$column['".$field->name."']";
}
}
$statment="\$q->bind_result($statementParams);";
eval($statment);
$q->fetch();
return $column;
}
Its working fine but giving me only one row in response. I want get all row instead of one. I am getting response like this
{"status":"success","userData":{"email":"abc#gmail.com","username":"rajrathodbvn","user_type":0}}
Let me know if someone can help me for solve my issue.
Thanks
That's a lot of code for something so simple. Select the columns you want:
function getOnlineUsers($conn) {
$q = $conn->prepare("SELECT email, username, user_type
FROM table_users
WHERE online_status = 1");
$q->execute();
return $q->fetchAll(PDO::FETCH_ASSOC);
}
Then assign:
$result['status'] = 'success';
$result['userData'] = getOnlineUsers($conn);
Or:
$result = ['status' => 'success', 'userData' => getOnlineUsers($conn)];

Multiple MySQL Inputs

I have a script which looks like this which retrieves song information that people are scrobbling on LastFM:
class NowPlaying{
private $url;
private $noTrackPlayingMessage;
function __construct($user, $api_key){
// construct URL
$this->url = 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&limit=1';
$this->url .= '&user=' . $user . '&api_key=' . $api_key;
// default message
$this->noTrackPlayingMessage = 'Nothing is playing right now!';
}
// return the artist and track currently playing
public function getNowPlaying(){
// create an XML object
$xml = simplexml_load_file($this->url);
// get the latest track
$track = $xml->recenttracks->track;
// check if the track is actually playing
$nowplaying = $track->attributes()->nowplaying;
// return the track and artist if music is playing, otherwise show message
if($nowplaying){
$artist = $track->artist;
$songname = $track->name;
return $artist . ' - ' . $songname;
}
else{
return $this->noTrackPlayingMessage;
}
}
// set the message to be shown when no music is playing
public function setNoTrackPlayingMessage($messageIn){
$this->noTrackPlayingMessage = $messageIn;
}
} // end class
$nowPlaying = new NowPlaying($id, 'APIGOESHERE');
$nowPlaying->setNoTrackPlayingMessage($id); // optional
$currentplaying = $nowPlaying->getNowPlaying();
While this is useful for just an individual LastFM account however I want to run several accounts through this script which the details are stored in a MySQL database. My table has two columns, lastfmusername and currentsong. I want to find get all the songs those lastfm user's are listening to and then store them in their currentsong field.
I've tried adding the following to the top:
$sql = "SELECT lastfmusername FROM data";
$id = $db->query($sql);
Then the following to the bottom:
$sql2 = "UPDATE lastfmtable SET currentsong = '$currentplaying' WHERE lastfmusername = '$id'";
$cursong = $db->query($sql2);
But that failed so I'm not sure how to approach this. Any help would be appreciated.
$sql = "SELECT lastfmusername FROM data";
will return an array containing ALL values of lastfmusername, not just one.
Try this instead:
$sql = "SELECT lastfmusername FROM data";
$users = $db->query($sql);
$id = $users[0]['lastfmusername'];
meaning: $id will now store the first result.
You'll need to loop through the result of users and run the update query for each user. So what you are trying to do should look like this:
foreach($users as $r){
$id= $r['lastfmusername'];
$nowPlaying = new NowPlaying($id, 'APIGOESHERE');
$nowPlaying->setNoTrackPlayingMessage($id); // optional
$currentplaying = $nowPlaying->getNowPlaying();
$sql2 = "UPDATE lastfmtable SET currentsong = '$currentplaying' WHERE lastfmusername = '$id'";
$cursong = $db->query($sql2);
}

Returning array from simple function is empty

I have the following function:
function getUser($user_id){
$mysqli = dbConnect();
$gu = "select * from users where user_id = '$user_id'";
$ru = $mysqli->query($gu);
$user = $ru->fetch_array();
return $user;
}
Which is called eg:
$user_id = $_SESSION[user_id];
getUser($user_id);
Then I want to simply echo fields i want, e.g. name. But, when I try the following, it returns empty
echo "users name is $user['name']"; // returns: users name is
Is there a better way to do this?
UPDATE Also tried the following but still empty:
function getUser($user_id){
$mysqli = dbConnect();
$gu = "select * from users where user_id = '$user_id'";
$ru = $mysqli->query($gu);
$user = array();
while($row = $ru->fetch_array()) {
$user[] = $row;
}
return $user;
}
your line:
getUser($user_id);
should be:
$user=getUser($user_id);
This way you'll be setting $user to the array the getUser returns, then you can use it.
Remove the single quotes when printing an array, you echo may needed to be like:
echo "users name is $user[name]";

select-from-where query not working in codeigniter model

I am trying to select the details of the users from a table in mysql database but it is not working. This is the code in my model :-
public function getuserdetails()
{
$user_email = $this->input->post('email');
$query_userdetails = $this->db->query("SELECT *
FROM users WHERE email = '$user_email' ");
return $query_userdetails->result_array();
}
This is not working. But if I put the actual email id in the query instead of $user_email it works but not properly i.e if I use :-
$query_userdetails = $this->db->query("SELECT * FROM users WHERE
email = 'myemail#gmail.com' ");
In this case it returns a result. My controller code to accept the result is :-
$data['details'] = $this->model_userdetails->getuserdetails();
But the problem is that when I access $details in view :-
echo $details['name']."<br />";
it does not recognize 'name'. name is the field in the database where the name of the users are stored. But if I try to retrieve it in a foreach loop it is working :-
foreach($details as $udetails)
{
echo $udetails['name']."<br />";
}
Run queries as per codeigniter suggestion
$query_userdetails = $this->db->query("SELECT * FROM users WHERE email = ?", array($user_email));
http://ellislab.com/codeigniter/user-guide/database/queries.html search for Query Bindings
I would try:
$query_userdetails = $this->db->query("SELECT * FROM users WHERE email = '". $user_email ."'");
I have solved the part where only foreach loop would work.
If we use row_array instead of returning result_array() the foreach constraint to diplay goes away.
Now I want to select the name from the database where email is $user_email
You have to write like this
public function getuserdetails()
{
$user_email = $this->input->post('email');
$this->db->where('email', $user_email)
->get('users')
->result_array();
}
After this, in view, you must to write like this
foreach($details as $udetails)
{
echo $udetails['name']."<br />";
}
You can try like This:
[CONTROLLER]
$data = array();
$data['udetails'] = $this->UserModel->getuserdetails();
$this->load->view('welcome_message',$data);
[MODEL]
public function getuserdetails() {
$user_email = 'webmaster';
$userdetails = $this->db->query("SELECT * FROM users WHERE umail = '$user_email' ");
return $userdetails->result();
}
[VIEW]
<?php
foreach($udetails as $row)
{
echo($row->uname.'<br/>');
echo($row->uname);
}
?>
Try this please it will help you.
Model
public function getuserdetails()
{
$user_email = $this->input->post('email');
$this->db->select("*");
$this->db->from('users');
$this->db->where('email',$user_email);
$query = $this->db->get();
$result= $query->result();
}
Controller
$data['details'] = $this->model_userdetails->getuserdetails();
view
foreach($details as $detail)
{
echo $detail->name;
echo $detail->email;
}

Need Help With Implementing Simple Stuff with PHP and MYSQL

Here is my code -
<?php
$u = $_SESSION['username'];
while($fetchy = mysqli_fetch_array($allusers))
{
mysqli_select_db($connect,"button");
$select = "select * from button where sessionusername='$u' AND response = 'approve'";
$query = mysqli_query($connect,$select) or die('Oops, Could not connect');
$result= mysqli_fetch_array($query);
$email = mysqli_real_escape_string($connect,trim($result['onuser']));
echo $email;
if($email){
mysqli_select_db($connect,"users");
$select_name = "select name, icon from profile where email = '$email'";
$query_2 = mysqli_query($connect,$select_name) or die('Oops, Could not connect. Sorry.');
$results= mysqli_fetch_array($query_2);
$name = mysqli_real_escape_string($connect,trim($results['name']));
$icon = mysqli_real_escape_string($connect,trim($results['icon']));
echo $name;
}
}
NOw, there are two reponses in db. So, two names are getting echoed, but they both are SAME. Why so? Eg
DB - NAMEs - Apple and Orange.
Displayed - Apple Apple.
Database example -
SESSIONUSERNAME OnUSer
s#s.com apple
s#s.com orange
EDITED
Using #endophage's method -
AppleOrange and AppleOrange.
As your loop stands now, $u will always be the same, so $select will always have the same value, and so will $email, and so will $select_name, so it is no surprise that the same record keeps coming back.
Edit
If the $select_name query returns multiple results, then you need to loop through the results with a while loop like the other queries.
Try this, you had your while loop in the wrong place:
<?php
$u = $_SESSION['username'];
mysqli_select_db($connect,"button");
$select = "select * from button where sessionusername='$u' AND response = 'approve'";
$query = mysqli_query($connect,$select) or die('Oops, Could not connect');
while($result = mysqli_fetch_array($query))
{
$email = mysqli_real_escape_string($connect,trim($result['onuser']));
echo $email;
if($email){
mysqli_select_db($connect,"users");
$select_name = "select name, icon from profile where email = '$email'";
$query_2 = mysqli_query($connect,$select_name) or die('Oops, Could not connect. Sorry.');
$results= mysqli_fetch_array($query_2);
$name = mysqli_real_escape_string($connect,trim($results['name']));
$icon = mysqli_real_escape_string($connect,trim($results['icon']));
echo $name;
}
}

Categories