Multiple MySQL Inputs - php

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);
}

Related

Data inserting blank into database

I am inserting data into the addresses of the customers in magento, I am able to add all the fields except the street field, would anyone know why?
The data is not entered, does not show any error, the other fields are all text or select, so they will normally, this field has only one label, I get the database label, I give a var_dump and it returns me the addresses, but does not add, I think I'm wrong on setStreet1, setStreet2, setStreet3, setStreet4.
Would I have to enter these values ​​in any different way? How do I set this data in the database? Would I have set them differently? I put the data in the bank normally by its name, first_name = Firstname, and here I am trying to do the same thing, but in street it is different is like [street] [0], street. Other data are like [first_name], [last_name]. Because he opened another [] would I have to add it in another way?
The way I pull this information is this way
'rua'=>$usuario_loaded->getStreet1(), 'numero'=>$usuario_loaded->getStreet2(), 'complemento'=>$usuario_loaded->getStreet3(), 'bairro'=>$usuario_loaded->getStreet4()
$i = 1;
$link = mysqli_connect('localhost','root','','x');
$link->set_charset("utf8");
$query = "SELECT * from endereços";
$select = mysqli_query($link, $query);
foreach ($select as $key => $selects) {
$link = mysqli_connect('localhost','root','','x');
$link->set_charset("utf8");
$query = "SELECT * from endereços";
$select = mysqli_query($link, $query);
while($row = mysqli_fetch_array($select)){
$teste = array(
$endereço_id = $row['endereço_id'],
$nome = $row['nome'],
$assinatura = $row['assinatura'],
$sobrenome = $row['sobrenome'],
$rua = $row['rua'],
$numero = $row['numero'],
$complemento = $row['complemento'],
$bairro = $row['bairro'],
$cidade = $row['cidade'],
$país = $row['país'],
$estado = $row['estado'],
$cep = $row['cep'],
$telefone = $row['telefone'],
);
var_dump($teste);
$customer = Mage::getModel("customer/address");
$customer ->setId($endereço_id)
->setFirstname($nome)
->setMiddlename($assinatura)
->setLastname($sobrenome)
->setStreet1($rua)
->setStreet2($numero)
->setStreet3($complemento)
->setStreet4($bairro)
->setCity($cidade)
->setCountryId($país)
->setRegionId($estado)
->setPostcode($cep)
->setTelephone($telefone)
try{
$customer->save();
}
catch (Exception $e) {
Zend_Debug::dump($e->getMessage());
}
}
}
Image
I did, I simply had to add the data with an array. Changing only this line
-> setStreet (array ($rua, $numero, $complemento, $bairro))

Msqli query array

So I have my code
function GetApi($connection,$UserId){
global $Apicall;
$Apicall = array();
$Apiidquery = mysqli_query($connection, "SELECT ID FROM ` Characterapi` WHERE UserId = '$UserId'");
while($results = mysqli_fetch_assoc($Apiidquery)){
$Apicall[] = $results['ID'];
}
}
The output of this function if I call
$Apicall[0] = 3
$Apicall[1] = 11
and this is the information I want. But now I want to use a function like
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$Keyidquery = array();
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ID = '$Apicall'");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
This code does run if i set $Apicall ="3"; The issue im having is that I want the first function to get All the IDs associated with $userId in my data base then for each Id run the second function to to get the two specific pieces of information from that query.
In response to the comment below, this is the solution which I would use. However you should be wary of using this method as it does not parameterize the values, and as such not sanitized.
<?php
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$string = "ID IN('";
$string.= implode("','", $Apicall);
$string.="')";
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ".$string.";");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
?>

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]";

Get all favorites for current user

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.

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