Generating information based on users choice in php - php

I have any information stored in a database which is picked up and displayed with radio buttons. I like to display information from the database based on what radio buttons the user has chosen. For example I have a list of activities a user may have done and based on what they have chosen I would like to display other activities they could do. I can get the system to display random information from the database using RAND(). Can't find any online tutorials for this.

Please give us more information or a concrete example of your problem, all i can tell you is that your SQL request in your second code snippet will probably not give the expected result :
SELECT * FROM activities ORDER BY RAND() LIMIT 1
You probably don't want to ORDER BY RAND() (may be impossible) nor LIMIT 1, you just want to pickup one random row from your mysql results, am i right ?
If i am right just get the full resultset (with no order by / no limit clause), generate a random with php (between 0 and resultset size) the pick the expected row from resultset.

Ok, so i don't know your database structure, but lets say you have a table for activities and table for the activities the user does. For the sake of this example we will call them activities and activities_by_user
The activities table will have columns
activity_id | activity
The activities_by_user will have columns
activity_id | user_id
So your display code will look something like this
$query = "SELECT activities.*, activities_by_user.activity_id AS has_activity FROM activities LEFT JOIN activities_by_user ON activities_by_user.activity_id = activities.activity_id AND user_id = 1 ORDER BY RAND()";
// The user_id in just for example. There should be the id of the logged user
$result = mysqli_query($con, $query) or die('Error');
while($row = mysqli_fetch_object($result)) {
// If the has_activity field is not null, then the user does that activity
$checked = (isset($row->has_activity) && $row->has_activity != null) ? 'checked' : '';
echo '<label><input type="checkbox" name="activities[]" value="' . $row->activity_id . '" ' . $checked . ' />' . $row->activity . '</label>';
}
This will generate checkboxes for all the activities and will check does who are done by the user.

Related

How can I select all id's from a sql table in descending order and then echo them (in php)?

I have several id's in a table called "leaderboards" that belong to different users. They're named as:"id_user" and they're not in order. What I want to do is printing divs in a leaderbord which should contain some info that I get from those id_user's.
The only problem I have about it is that after a research on stackoverflow and other websites, I still couldn't find how to select those id_user's in descending order AND be able to take one by one to get the info from that user and then continue with the next id_user, and so on.
I don't know how to select the specific row of each id_user in descending order to do the other codes that I already know how to do.
I hope it's not a duplicate of any other previosly asked question on this website (I really did a research and I couldn't find any specific answer to this question, for the sql part and the php part all together).
Thank you so so much beforehand.
An INNER JOIN between your tables will achieve what you intend.
SELECT *
FROM users
JOIN leaderboards WHERE users.id = leaderboards.id_user
ORDER BY users.id DESC
In each returned row, you will get the columns from both your users and leaderboards tables, so loop over the result and echo the information from the user you need.
$query = 'SELECT...';
$res = mysqli_query($query);
while ($row = mysqli_fetch_assoc($res)) {
echo '<div>'.$row['id'].' - '.$row['username'].' - '.$row['image'].'</div>';
}
You could do with a good read up on both PHP and MySql but I'll give you a clue.
EDIT
$query = "SELECT * FROM `the_name_of_your_table` ORDER BY `user_id` DESC;";
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
print $row["user_id"] . " - " . $row["username"] . "<BR>";
}
/* free result set */
mysqli_free_result($result);
}

Echo the variable of i in while

i try something like this :
function userrank($userid){
$sql = mysql_query("SELECT * FROM users ORDER BY atacs DESC");
$i = 1;
while ($row = mysql_fetch_assoc($sql)) {
if ($row['username'] == $userid) {
echo 'You are on ' . $i . ' in the general leaderbord';
}
}
}
On the leaderboard it shows me the rank correctly, but i want to show me on another page too , on the "youraccount" page , for this i try to make this function.
what is wrong ?
Basically what you're doing here is counting how many users have an atacs greater than or equal to $userid's atacs. Problems with this:
Terribly inefficient. Note the database retrieves and sends to your
while loop an entry for every user, even those who have an atacs
less than the $userid. All but one of these while loop iterations
does nothing by design. Lots of wasted time sending data from the
database to PHP, which doesn't even use it.
Pulls way more data back
than is necessary. You end up with every row for every user in
your entire users table - but your result is just a scalar number
( how many users with > score ).
Actually gives you wrong results
in the case that your score is tied with others'. In this case some
users with the same score may be counted as "above" the user, others
as "below the users".
Databases are good at iterating over data; it's
all "locally" accessible and the database engine can make many
optimizations if you can describe in SQL what you are trying to
accomplish. So instead of doing it that way, why not just do
everything in the database?
set #user_atacs = ( select atacs from users where id = 12 );
select count(*) +1 from users where atacs > #user_atacs;
I've mocked up the table here: http://sqlfiddle.com/#!2/ff9a86/3
This solution essentially just counts the number of users with a higher atacs than the current user. All users with the same score will get the same rank, and the next rank will be appropriately higher, so it doesn't suffer from any of your method's errors.
As a final note, the most appropriate way to do something like leaderboards is probably to precompute the leaderboard periodically and then use the results to show each user's position in the leaderboards, rather than trying to compute it on the fly for each user. But that's even farther out of scope :)
You have to increment $i. I'm Assuming that the leader board order is represented by the result of your query. So, if true, change your code as follows:
function userrank($userid){
$sql = mysql_query("SELECT * FROM users ORDER BY atacs DESC");
$i =0; // starts out with an unknown rank.
while ($row = mysql_fetch_assoc($sql)) {
$i++; // increment $i here.
if ($row['username'] == $userid) {
echo 'You are on ' . $i . ' in the general leaderbord';
}
}
}
The $i will increment for sure. So, if it is not working still, I'd look to see what the result of your query is. Try echoing $row['username'] and see what the value is and then compare that to the echoed calue of $userid.

sql sort users by the sum of their logged distance

I am working with a table that contains logs for users reported exercise distances. I want to rank users by the sum of their logged distance.
First I find all the User ID's:
select distinct wordpress_user_id from wp_exercise_log
Then I loop through that and get the name and sum(distance) with:
foreach($users as $user) {
// DISTANCE
$user_distance = floor($wpdb->get_var( "select sum(distance) from wp_exercise_log where wordpress_user_id='$user'"));
// FULL NAME
$user_info = get_userdata($user);
$full_name = $user_info-> user_firstname . ' ' . $user_info-> user_lastname;
}
Heres my problem: Unless I append them to a multidimensional array and sort with PHP, I'm not sure how I can rank the users.
Is there a better way to select all this data and sort it with one SQL query?
select
wordpress_user_id,
sum(distance) as user_distance
from
wp_exercise_log
group by
wordpress_user_id
order by
user_distance desc
Please mind ORDER BY GROUP_FUNCTION() is always causing perfomance issues.
You may consider to add some column user_total_distance to your users table and update it every change in wp_exercise_log.

How can i search all tables for a specific node value's parent_id?

There are several other posts like this but none which match my specific parameters/needs.
How do i find the parent_id associated with one of 50 different outputted query results a user could click on?
Like, if the user clicks on "Transportation" I need code that can find the parent_id corresponding to the transportation node.
Problem is, my data is structure over multiple tables, so if they click on a link I don't necessarily know which table to search.
Essentially what I want is SELECT parent_id FROM * WHERE * = communication
But I can't * for parameters such as table name.
So how do I create code to automatically find the parent_id of a specific query once the user selects it?
There must be a better option than listing all my 20 tables in the query parameters?
Should I restructure my data into 1 table?
You have to search each table for the parent_id. If you want shorter codes, you can try this:
<?php
$tables = mysql_query('SHOW TABLES');
while($table = mysql_fetch_row($tables)){
$queries[] = 'SELECT parent_id FROM `' . $table[0] . '` WHERE method=\'Transportation\'';
}
$result = mysql_query(implode(' UNION ', $queries));
?>

Retrieve data from query filled drop down box

I have made a dropdown box that is filled by a query that looks for company names from company name database, these names also have and ID number that I don't want displayed but are looked up in the query. I need the ID number to link to sites of the company so somehow when I hit the submit button on the site page it finds the ID number by looking at the position value and relating that to the position on the query array I just don't know what to do. If it helps this is how I fill the dropbox:
mysql_select_db("DB", $con);
$query = "SELECT Company_Name, ID FROM company_table";
$result = mysql_query($query) or die(mysql_error());
$options ='';
$num = 0;
while ($row=mysql_fetch_array($result)) {
$num = $num+1;
$options.= "<OPTION VALUE=\"$num\">".$row["Company_Name"];
}
<SELECT NAME=thing>
<OPTION VALUE=0>Choose
<?=$options?>
</SELECT>
Any Ideas?
There are two immediate ways this can be done. One is to keep it the way you have it using an index, $num; the other way is to use the actual company id field, ID. If you stick with the index of $num, when the user submits the form (i.e. - selects a company), you will have to re-query the database and re-loop through the results to find the specific company (or you could use a LIMIT/OFFSET; notes at end of answer).
I would recommend using the actual company id in your form:
while (($row = mysql_fetch_assoc($result))) {
$options.= '<option value="' . $row['ID'] . '">' . $row["Company_Name"] . '</option>';
}
This will generate a list of options, like you currently have, except the value of each will be the specific company id. When the user submits the form, let's assume the form is using POST, you can get the ID with:
$companyId = (isset($_POST['thing']) && is_numeric($_POST['thing'])) ? intval($_POST['thing']) : false;
$results = mysql_query('SELECT * FROM company_table WHERE ID=' . $companyId);
.. and then process as you desire.
I use $_POST['thing'] in the above example as that is what your code-example has the select field named. Also, I make the assumption that ID is an integer.
If the actual ID needs to remain hidden, as specified, the index of $num can be used with MySQL's LIMIT/OFFSET as follows:
$selectedCompany = (isset($_POST['thing']) && is_numeric($_POST['thing'])) ? intval($_POST['thing']) : -1;
if ($selectedCompany >= 0) {
$query = "SELECT Company_Name, ID FROM company_table LIMIT " . $selectedCompany . ", 1";
// process as desired
}
An option is to add a "created" field to the company table that is a timestamp, or just a 2nd column that is a random UUID column. Then set the value of the dropdown to this column so you don't show ID but you will still know the record since you are using the "other" id as well.
I actually use this method in one of my programs where it was the same situation as you, the client didn't want the ID to be shown.
If you don't want to go with this method (because you don't want a 2nd column) you could just md5 hash the ID or some other hashing method.
Then you would do
SELECT * FROM company where md5(id) = "$value".
The downside to this method is that it is an expensive query, since you won't be using an index and it has to compute all the md5 hashes for each id.

Categories