How to randomly selected column from two tables in database PHP - php

i want to make reading toefl test. i have two tables named 'id_reading' and 'soal_reading'. id_reading table contain id and text. soal_reading contain id, question, option a b c d and answer. so i want to display data from that tables. but i want to display randomly all column in soal_reading tables except id column. i try but it wont random. please help.
<?php
include "conection.php";
$query = mysql_query("
SELECT id_reading.id
, text
, id_reading.text
, soal_reading.pertanyaan
, a
, b
, c
, d
, jawaban
from id_reading
, soal_reading
where id_reading.id = soal_reading.id
");
if ($query) {
while ($row = mysql_fetch_array($query)) {
echo "
<tr>
<td>".$row['id']."</td>
<td>".$row['text']."</td>";
$q = mysql_query("SELECT * from soal_reading order by rand()");
if ($q) {
while ($r = mysql_fetch_array($query)) {
echo "
<td>".$r['pertanyaan']."</td>
<td>".$r['a']."</td>
<td>".$r['b']."</td>
<td>".$r['c']."</td>
<td>".$r['d']."</td>
<td>".$r['jawaban']."</td>
<td>
Edit |
Delete
</td>
</tr>";
}
}
}
}
?>

Your query set in a random way questions but not fields in the question. So if you have 3 questions for example Q1, Q2,Q3 they are ordered in a random way, not the fields.
I suggest you to put your $r['a'] .... $r['d'] into an array and then extract a number from 0 to count($array) to get a possible answer and remove that element from the array. Do that until all possible answers are extracted. (count($array)==0).
In summary, your query provides you random order for your questions and in PHP you give a random order to your fields.
For some code, please comment.
Bye

Related

The sum of the user's points

I am a beginner when it comes to PHP and it is not my specialty, I am rather in the front end and I have a big problem.
I need to edit one of the tables after a guy who doesn't work with our company anymore and it seemed simple to me at first, but I can't find a solution.
I have a table with 4 columns: Date, Full Name, Login, and Points. Records of added points are saved in the database, but each action adding points creates a new record in the database, let's say:
Date
Full Name
Login
Points
04/10/2021
John Kovalsky
koval
10
04/11/2021
John Kovalsky
koval
20
04/12/2021
John Kovalsky
koval
15
The script below works, and I can almost understand the syntax, there is a display limit set here and a table pagination added. The script displays all records in the database.
The problem is that I need exactly the same, but with the sum of the user's points, so that a given user is displayed only once, and in the "Points" column, the sum of all his points is displayed.
I tried with the array_sum () function, but it enumerates all the records in the database for me. The script looks like this:
<?php
$login = $_GET['login'];
$_SESSION["login"] = $login;
include('Pagination.php');
include('config.php');
$limit = 200;
$queryNum = $db->query("SELECT COUNT(*) as ID FROM db_main");
$resultNum = $queryNum->fetch_assoc();
$rowCount = $resultNum['ID'];
$pagConfig = array(
'totalRows' => $rowCount,
'perPage' => $limit,
'link_func' => 'searchFilter'
);
$pagination = new Pagination($pagConfig);
$query = $db->query("SELECT * FROM db_main LIMIT $limit");
echo "<center>";
echo "<table id=\"tabela\" cellpadding=\"2\" border=1>";
echo "<tr>";
echo "<th>".'Date'."</th>";
echo "<th>".'Full Name'."</th>";
echo "<th>".'Login'."</th>";
echo "<th>".'Points'."</th>";
echo "</tr>";
echo "</tr>";
if($query->num_rows > 0){
?>
<?php
while($r = $query->fetch_assoc()){
echo "<tr>";
echo "<td>".$r['Date']."</td>";
echo "<td>".$r['Full_name']."</td>";
echo "<td>".$r['Login']."</td>";
echo "<td>".$r['Points']."</td>";
echo "</tr> </center>";
}
echo $pagination->createLinks();
}
?>
Please help, I have no idea how to do it. I will be very grateful for your help and hints.
You could do it by using a different query.
First, get all unique users.
$db->query("SELECT COUNT(DISTINCT(Full_name)) as ID FROM db_main");
Now get the collected data for each user.
$db->query("SELECT MAX(Date) AS Date, Full_name, Login, SUM(Points) AS Points FROM db_main GROUP BY Full_name LIMIT $limit");
Using the GROUP option will make sure you get one row per user.
The SUM will give you the amount of all the user's points.
The MAX(Day) will return user's the last day field.
There are two assumptions here, that the login is always the same for the user, and that the Points field is numeric and not a string.

How to get specific data from table1, use it in table2

I'm trying to get specific rows in table 1 (stellingen). I want to store these rows to specify the rows im interested in for the second table (stelling). So lets say table 1 has 5 rows where stelling ID matches REGIOID = 5. These IDS from stelling ID I want to use to fetch the data from the second table. see the code to see what I tried. I'm not managing to find a way in order too make this happen.
So maybe too be clearer because people always say im not clear:
There are two tables. they both have a matching column. Im trying to tell the second table I want data but only if it matches the data of the first table. Like a branch of a tree. Then, I want to output some data that's in the second table.
I've tried something like this before:
SELECT
*
FROM
table2
LEFT JOIN
table1 ON
table1.ID = table2.table1_id
I've tried to create a while loop to get the data before(after the first if statement and the last += was for the variable $amountofstellinge):
$amountOfStellinge = 0;
while ($amountOfStellinge<5){
mysqli_data_seek($result, $amountOfStellinge);
Here is the code what it looks like now, its wrong, i've been messing with t a lot, but maybe it shows you what I'm trying to achieve better.
if($result = mysqli_query($con, "SELECT * FROM stellingen WHERE REGIOID=1;")) {
$row = mysqli_fetch_assoc($result);
$stellingid= $row["Stelling_ID"];
//checking.. and the output is obviously not what I want in my next query
printf($stellingid);
//defining the variable
$Timer=0;
$sql1="SELECT * FROM stelling WHERE stelling_iD=$stellingid ORDER BY Timer DESC;";
$records2 = mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records2);
//max 5 data
if ($recordscheck < 5){
while ($stelling = mysqli_fetch_assoc($records2)){
//At the end, i would like to only have the data that is most recent
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}}
$recordscheck+=1; } // this is totally wrong
EDIT:
I've tried this, #noobjs
$Timer=0;
$sql1="SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.ID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer LIMIT 5 DESC ;";
$records2 = mysqli_query($con, $sql1);
printf($records2);
while ($stelling = mysqli_fetch_assoc($records2)){
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}
with this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in
EDIT for more clarification
Here is some sample data
The expected results is:
every page has uses data from a different REGIOID. I expect the page to show data from the table stelling(Table 1). Accordingly to the REGIOID (Table2)
if i understand right:
SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.stellingID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer DESC LIMIT 5 ;

How to find total rows before required row [duplicate]

This question already has answers here:
Rank function in MySQL
(13 answers)
Closed 8 years ago.
I have a text based mafia game and I am selected some GameRecords. The game records are all defined in the "users" table. For this example I am using "totalcrimes". I need to select all the rows from the users table and order it by totalcrimes and then find out which row each specific user is that is viewing the page.
If I was the user that was "ranked" 30th it would echo "30". The code I use to find the top 5 is here however I need to expand on it:
<?php
$i = 0;
$FindCrimes = mysql_query("SELECT * FROM players WHERE status='Alive' AND robot = 0 ORDER BY `totalcrimes` DESC LIMIT 5");
while($Row = mysql_fetch_assoc($FindCrimes)){
$Username = $Row['playername'];
$TotalCrimes = number_format($Row['totalcrimes']);
$i++;
echo "
<tr>
<td bgcolor='#111111' width='5%'>$i</td>
<td bgcolor='#111111' width='50%'><a href='viewplayer?playerid=$Username'>$Username</a></td>
<td bgcolor='#333333' width='45%'>$TotalCrimes</a></td></td>
</tr>
";
}
?>
I am going to assume that you already have a variable set to hold the current users ID number and total crimes, so in this case I will use $user as my variable.
Change yours to fit.
Now, I see 2 instances in which you could mean as your post wasn't very specific, so I will address both.
To show the number at the top of the page, you would use something like;
<?php
$sql = "SELECT * FROM `players` WHERE `totalcrimes` > '{$user['totalcrimes']}'";
$run = mysql_query($sql);
$rank = mysql_num_rows($run) + 1;
echo 'Your rank: ' . $rank;
Other than that, I see it's possibly being used to highlight your row, so something like this would suffice;
<?php
$i = 0;
$FindCrimes = mysql_query("SELECT * FROM players WHERE status='Alive' AND robot = 0 ORDER BY `totalcrimes` DESC LIMIT 5");
while($Row = mysql_fetch_assoc($FindCrimes))
{
$Username = $Row['playername'];
$TotalCrimes = number_format($Row['totalcrimes']);
$i++;
$primary = '#111111';
$secondary = '#333333';
if ($Row['id'] == $user['id'])
{
$primary = '#222222';
$secondary = '#444444';
}
echo "<tr>
<td bgcolor='$primary' width='5%'>$i</td>
<td bgcolor='$primary' width='50%'><a href='viewplayer?playerid=$Username'>$Username</a></td>
<td bgcolor='$secondary' width='45%'>$TotalCrimes</a></td></td>
</tr>";
}
If neither of those give your requirements, please comment and I'll edit to suit.
edit: I've worked on games for a few years - care to share the link to yours?
This can do the trick
SELECT COUNT(*)+1 as rank
FROM users
WHERE totalcrimes > (SELECT totalcrimes
FROM users
WHERE user_id='12345' AND status='Alive' AND robot='0');
So it counts all rows with greater totalcrimes than selected user (in this example I have used user_id column and some id 12345), than adds 1 on that sum and returns as rank value.
Course, modify WHERE clause inside the brackets to make it work for you.
I assumed that table name is users and user's id is integer user_id.
Test preview (Navicat Premium):
What this query does? It returns number of selected rows + 1 as rank column, from the table users where totalcrimes is greater than totalcrimes of some user. That user's totalcrimes is selected by another query (by its user_id). If you have multiple users with same totalcrimes value, this query will return same rank for all of them.

PHP: Left Join 2 table and print all records

I have two table records in my database which look like this:
Table 1 with the column 1:
topic_id name
21 my computer
table 2 with columns as follows:
reply_id topic_id message
1 21 blabla
2 21 blue
In which the topic_id column in the table 2 is the foreign key of the table 1
I wanted to echo all replies in the table 2 along with the topic name (#21) in the table 1. So, I made the query like this
$q="SELECT name, message
FROM table1
LEFT JOIN table2
ON table1.topic_id = table2.topic_id
";
However, the result/ output returns the topic's name and ONLY ONE reply, but not 2 (or all) as expected. Did I miss something?
I used LEFT JOIN because some topics are still waiting for replies. In case that there is not any reply, the topic's name is still printed in browsers.
I also tried adding
GROUP BY table1.topic_id
but still NO LUCK!
Can you help? Thanks
EDIT: To clarify the question I add the php code to fetch records as follows:
As you know, The name needs to be printed only once. So, I code like this:
$tid = FALSE;
if(isset($_GET['qid']) && filter_var($_GET['qid'], FILTER_VALIDATE_INT, array('min_range'=>1) ) ){
// create the shorthand of the question ID:
$tid = $_GET['tid'];
// run query ($q) as shown above
$r = mysqli_query($dbc, $q) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $q");
if (!(mysqli_num_rows($r) > 0) ){
$tid = FALSE; // valid topic id
}
}//isset($_GET['qid']
if ($tid) { //OK
$printtopic = FALSE; // flag variable to print topic once
while($content = mysqli_fetch_array($r, MYSQLI_ASSOC)){
if (!$printtopic) {
echo $content['name'];
$printtopic= TRUE;
}
}
} // end of $tid
// Print the messages if any:
echo $content['message'];
Try this with inner join
$q="SELECT name, message
FROM table1
INNER JOIN table2
ON table1.topic_id = table2.topic_id";
Try:
$q="SELECT table2.reply_id, table1.name, table2.message
FROM table2
LEFT JOIN table1
ON table1.topic_id = table2.topic_id
";
After struggling with this issue, I can find out that the problem is that I had to change the query to INNER JOIN and add the WHERE clause like this:
WHERE table2.reply_id = {the given topic_id}
Then it works well!
Sorry to disturb you all!

php database table select limited

im new on php programming and i've searched the function that i need but didn't found it.
here what exactly i want to do :
i want to select 2 columns from a table
set the order by descending by 1 column that is numeric
and then show in php the first 100 rows that were selected
Here is my code right now php shows all the columns i want it to show the first 100
$result = mysqli_query($con,"SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC");
while($row = mysqli_fetch_array($result))
{
echo $row['pvpkills'] . "&nbsp " . $row['char_name'];
echo "<br>";
}
SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC LIMIT 0,100

Categories