User Online List PHP - php

I'm trying to make a online user list output all my usernames in a row like this (username, username, username)
The code I'm trying:
$result2 = $db->query("SELECT * FROM `online`");
$fetched2 = $result2->fetch_assoc();
$user_id = $fetched2['user_id'];
$result = $db->query("SELECT * FROM `users` WHERE id = $user_id");
while ($fetched = $result->fetch_assoc())
{
$users_arr[] = array("username"=> $fetched['username']);
}
But it's only returning 1 username from online table and not all in a row, how can i do this?
return json_encode(array("status" => 200, "message" => $users_arr)));
This only outputted 1 username, and also it's outputted in json format which i do not want, i want it outputted like so: User, User, User and not like [{'username': 'vanilla'}]"
Can someone please show me the correct way of using an array or a solution to my problem, thanks!
UPDATE:
Tried this and it worked, but now the dilemma is how do i make the outputted json array to look like User, User instead of ['user1', 'user2']
$users = array();
$result = $db->query('SELECT user_id, ident, u.group_id FROM '.$db->prefix.'online LEFT JOIN '.$db->prefix.'users AS u ON (ident=u.username) WHERE idle=0 ORDER BY ident', true) or error('Unable to fetch online list', __FILE__, __LINE__, $db->error());
while ($user_online = $result->fetch_assoc())
{
$users[] = $user_online["ident"];
}
I tried to use:
$trimmed = trim($users, '[]');
But this threw a warning/error:
PHP Warning: trim() expects parameter 1 to be string
Also tried:
$string = implode('[]', $users);
It does output 2 users, but its formated/outputted like:
user1[]user2

(Moved solution to answer space on behalf of the question author to move it from the question).
Fixed by using:
$string = implode(", ", $users);

Related

Conditionally use fallback value if value in resultset does not match currently logged in user

I have the php script below to get data from a database and return it to a calendar as part of a booking system. The title field, $row["title"], is actually the username of different people for each booking.
Everything works well, but I want to change things so that each user can only see their own username on the calendar, not each other’s. I want them to see 'booked' instead.
I’m pretty new to php, but my guess is that I need to iterate over the created $data array, changing only the title field if it doesn’t match the logged in user. I’m thinking this would come from this in my login script:
$_SESSION["username"] = $username; <=== I think this needs to be incorporated into the script and the php loop.
What I am trying to do is replace the title field with ‘booked’ if it doesn’t match the logged in user.
I also need to allow all users to see public entries too, say, unavailable, holiday -- so those title values should always be shown.
<?php
$connect = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$data = array();
$query = "SELECT * FROM events ORDER BY id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["start_event"],
'end' => $row["end_event"]
);
}
echo json_encode($data);
?>
Let's say Mary is logged in. The data array will look like this:
[
{"id":"365","title":"Kerry","start":"2021-08-19 20:00:00","end":"2021-08-19 20:40:00"},
{"id":"366","title":"John","start":"2021-08-19 19:00:00","end":"2021-08-19 19:40:00"},
{"id":"367","title":"Mary","start":"2021-08-20 10:00:00","end":"2021-08-20 10:40:00"},
{"id":"368","title":"Mary","start":"2021-08-20 12:00:00","end":"2021-08-20 12:40:00"},
{"id":"369","title":"Betty","start":"2021-08-20 15:00:00","end":"2021-08-20 15:40:00"}
]
But I want to change it to this before sending it to the calendar:
[
{"id":"365","title":"booked","start":"2021-08-19 20:00:00","end":"2021-08-19 20:40:00"},
{"id":"366","title":"booked ","start":"2021-08-19 19:00:00","end":"2021-08-19 19:40:00"},
{"id":"367","title":"Mary","start":"2021-08-20 10:00:00","end":"2021-08-20 10:40:00"},
{"id":"368","title":"Mary","start":"2021-08-20 12:00:00","end":"2021-08-20 12:40:00"},
{"id":"369","title":"booked","start":"2021-08-20 15:00:00","end":"2021-08-20 15:40:00"}
]
If you want to access session data you'd first need to start the session. Then you can just use the session variables in the script
<?php
session_start();
$connect = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$data = array();
$query = "SELECT * FROM events ORDER BY id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row) {
$data[] = array(
'id' => $row['id'],
'title' => isset($_SESSION['username']) && $row['title'] == $_SESSION['username'] ? $row['title'] : 'booked',
'start' => $row['start_event'],
'end' => $row['end_event']
);
}
echo json_encode($data);
sidenote, this will only work properly if all the usernames are unique though
If the the username in the SESSION is the same as the row's title, then show the title, otherwise show booked.
Extension: To show the title value when it matches the logged in user's name OR if it matches so communal/public strings, pile them all into an IN() condition.
Recommendation:
$sql = "SELECT id,
IF(title IN (?,'unavailable','holiday'), title, 'booked') AS title,
start_event AS start,
end_event AS end
FROM events
ORDER BY id";
$statement = $connect->prepare($sql);
$statement->execute([$_SESSION['username']]);
echo json_encode($statement->fetchAll(PDO::FETCH_ASSOC));
If you want this to be a dynamic condition, you can prepare your whitelist array in advance:
$allowTitles = [
$_SESSION['username'],
'unavailable',
'holiday',
];
Then you create the necessary number of placeholders and feed the array to execute().
$placeholders = implode(',', array_fill(0, count($allowTitles), '?'));
$sql = "SELECT id,
IF(title IN ($placeholders), title, 'booked') AS title,
start_event AS start,
end_event AS end
FROM events
ORDER BY id";
$statement = $connect->prepare($sql);
$statement->execute($allowTitles);
echo json_encode($statement->fetchAll(PDO::FETCH_ASSOC));
P.S. I share #DarkBee's concern regarding unique names in your db table. Typically you should use ids to avoid any chance of data collisions.

Empty array in PHP with MySql

I am trying to code it so users can type in their -- or others -- usernames which will be converted in their UUID then returns that user's stats from my MySql databse.
The code I attempted this with is
$username = $_POST['searchbox'];
$json = file_get_contents("https://api.mojang.com/users/profiles/minecraft/".$username);
$obj = json_decode($json);
$id = $obj->id;
$rank = Database::query("SELECT * FROM playerdata WHERE uuid=:uuid", array(':uuid'=>"".$id))[0]['rank'];
echo 'Showing results for '.$_POST['searchbox'].' '.$id.' Rank: '.$rank;
Except when I run this code it outputs:
"Showing results for kingbluesapphire 0d8d246d11c54cbbb197c6bc8ba01ee2 Rank:"
I know it's not a problem with the connection to the database because other queries are working
My goal right now is to get the field in the MySql Database thats called rank and I would like to display their rank.
Given the discussion in the comments, either you have to find out what is removing the dashes which I highly recomend to or change your query to:
$rank = Database::query("SELECT *
FROM playerdata
WHERE replace(uuid, '-','')=:uuid",
array(':uuid'=>"".$id))[0]['rank'];
Databases need to be given the exact value you are looking for, any different character in a equals operation will not give you any data.
It's more like:
<?php
if(isset($_POST['searchbox']){
$sb = $_POST['searchbox']);
$json = json_decode(file_get_contents("https://api.mojang.com/users/profiles/minecraft/$sb"));
if($queryRes = $connection->query("SELECT * FROM playerdata WHERE uuid={$json->id}")){
if($queryRes->num_rows){
$o = $queryRes->fetch_object(); // guessing there's only one row or you would put this in a while loop
echo "Showing results for $sb {$o->uuid} Rank:{$o->rank}";
}
}
else{
die($connection->connect_error);
}
}
?>
I'm assuming uuid is a number. Do tell.

PHP Array chunk get's accessed twice and I don't know why

I wrote a function to start a tournament and people got Emails twice instead of once. So I tried to debug stuff. As you can see, I fill an array (part[]) with information from my database, shuffle it for the random enemy thing and then want to email the participants their opponents. I cut the whole email thing and just printed the array. But it gets printed twice. What makes me really sick is, that one of the prints appears above the
echo "<hr>";
which is crazy because there is no output.
function start_pre($t_id) {
global $con;
$participants=array();
$sql = "SELECT u.name, u.btag, u.email FROM participant p, user u WHERE p.tournament_id = ".$t_id." AND p.user_id = u.user_id";
$result = mysqli_query($con, $sql);
if ($result) {
while ($row = mysqli_fetch_array($result)) {
$part[] = array(
"name" => $row['name'],
"btag" => $row['btag'],
"email" => $row['email']
);
}
} else {echo "Problem.";}
shuffle($part);
echo "<hr>";
$paare = array_chunk($part, 2);
foreach ($paare as $paar) {
print_r($paar);
}
$sql = "UPDATE tournament SET enrollable='0' WHERE tournament_id='".$t_id."'";
$result = mysqli_query($con, $sql);
}
I cannot include a screenshot of the actual output because of privacy and stuff but I bet you can imagine how a printed array above and below a horizontal line look. Any help is appreciated!
You must be calling the whole function twice. Also, It would perform better if you just use order by rand() in mysql rather than shuffle.

PHP need help to filter a loggfile

So my problem is this I got a code that loops trough a loggfile then compares them to a treestructure and then gives them a id that correspond to the id in the structure. To not get a lot of bad traffic i sort out all the 302 and above.
The problem is now that i want some specific 302s to count that have a particular pagetype in the structure. This is not a big problem as I can just match the url in the loggfile against the url in the tree structure but some loggfiles does not use friendly url while the structure is in friendly url this creates a problem but I can just match the id in the query parameter with the id in the structure. I then make a string of all the ids that match the special pagetype that I want.
The problem is this I can not get the Mysql statement to work, it looks like this.
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN '$check'";
A example query can look like this "id=4&epslanguage=sv" so I want to check only the id=X part.
It´s a kinda easy question really im just stuck and can not get it to work, any help is appreciated!
I think your Q is: How do I extract id from that part of a line?
".. so I want to check only the id=X part."
Once you have isolated that string then you can use:
$string = "id=4&abclang=sv";
parse_str($string);
echo $id; // 4
EDIT
In light of other responses:
$strings[] = "id=4&abclang=sv";
$strings[] = "id=45&abclang=en";
$vals = array();
foreach( $strings as $string){
parse_str($string);
$vals[] = $id ;
}
$in_clause = join(",", $vals) ;
$sql = "SELECT lid FROM logfile WHERE something IN ($in_clause) ";
echo $sql; // SELECT lid FROM logfile WHERE something IN (4,45)
So you have the IDs already and want to filter the MySQL query to just get these rows?
$check = Array(1, 2, 3, 4);
$check = implode(",", $check);
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN ($check)";

Selecting PHP variables from joined tables

I am still trying to learn PHP and have some issues with this code. I have a field $youtubeurl in ID_Vehicles and I am trying to output some code if that field has data in it how do I select that field with this join to output the value like the sample below?
function getDealerSettings($vid)
{
include('db.php');
$query = "SELECT banner, ebay_htmlcss FROM ebay_dealersettings INNER JOIN ID_vehicles ON ebay_dealersettings.did=ID_vehicles.did WHERE vid='".$vid."'";
$result = #mysql_query($query);
if ($result)
{
$row = mysql_fetch_assoc($result);
return array("banner" => trim($row['banner']), "css" => str_replace(array("\n", "\t"), " ",$row['ebay_htmlcss']));
}
return "";
}
function getTemplate($vid)
{
$code = "";
extract($this->getDealerSettings($vid));
if (!empty($youtubeurl))
$code .= "$youtubeurl";
Seems like you just need to add that field to your select statement:
$query = "SELECT banner, ebay_htmlcss, youtubeurl FROM ebay_dealersettings INNER JOIN ID_vehicles ON ebay_dealersettings.did=ID_vehicles.did WHERE vid='".$vid."'";
You need to add youtubeurl to the SELECT statement as well as ensuring it's in your return array, then it should work.
I wasn't returning the value in the array return array("banner" => trim($row['banner']),"youtubeurl" => trim($row['youtubeurl']),
Not necessarily an answer, supplements my comment to the question, I couldn't find a $youtubeurl mentioned before the empty check. If the db does not return anything or the query fails, the needed error handling is also not present. I have added simple error handling to the script. the return array contains ($return_array[0]) $errflag, which can be read to see if there was an error, $errmsg is an array containing the error msg, the third element contains your return array.
function getDealerSettings($vid)
{
$errflag=false;
$errmsg=array();
$return=array();
include('db.php');
$query = "SELECT banner, ebay_htmlcss FROM ebay_dealersettings INNER JOIN ID_vehicles ON ebay_dealersettings.did=ID_vehicles.did WHERE vid='".$vid."'";
$result = #mysql_query($query);
if (!$result){
$errflag=true;
$errmsg[]="Error with db connection". mysql_error();
}else{
$row = mysql_fetch_assoc($result);
$return = array("banner" => trim($row['banner']), "css" => str_replace(array("\n", "\t"), " ",$row['ebay_htmlcss']));
}
$return_array=array($errflag, $errmsg, $return);
return $return_array;
}

Categories