SQL - Displaying names instead of ID [duplicate] - php

This question already has answers here:
Select Name instead OF ID in table with ID-Ref Column SQL
(2 answers)
Show Name Instead of ID from Different Table
(2 answers)
Closed 1 year ago.
I have 2 tables
rankID | name
1 | new
2 | learner
3 | experienced
4 | pro
And another with all the user info and passwords and stuff
id | username | rankID
1 | hello | 3
2 | hey | 3
I have come so far so I can display their rank number, but I want to display the rank name. How can I do that? I have tried a lot of things but I'm not so good at sql and the php part of it.
This is the code I use to display the rank number
//Get rankID
$query = "SELECT rankID FROM users WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rankID'];
And to display the rank number:
Rank: <?php echo $rank; ?>

Simple JOIN query :-
"SELECT rank.name as rank_name,users.rankID as rankID from users LEFT JOIN rank ON rank.rankID = users.rankID WHERE id = '$userId'"
And then After:-
$query = "SELECT rank.name as rank_name,users.rankID as rankID from users LEFT JOIN rank ON rank.rankID = users.rankID WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
Do:-
$rank = $row['rankID'];
$rank_name = $row['rank_name'];
Rank: <?php echo $rank; ?>
RankName: <?php echo $rank_name; ?>
Or
$rank_data = $row;
Rank: <?php echo $rank_data['rankID']; ?>
RankName: <?php echo $rank_data['rank_name']; ?>
Not:- lot of other possible ways are there which are listed by other programmers in comment and answer as well.

//Get datas
$query = "SELECT rankID, name FROM users WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rankID'];
$rank = $row['name'];
And to display the datas:
Rank: <?php echo $rank; ?>
Name: <?php echo $name; ?>

Hope so this should make a trick for you.
$query = "SELECT rankID FROM users WHERE id = '".$userId."'";
$result = $conn->query($query);
$count = $result->num_rows;
if($count==0)
{
return false;
}
else
{
$rows=[];
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
}

Please use below code
$query = "SELECT name FROM users as u JOIN rank as r ON r.rankID = u.rankID WHERE u.id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
Name: <?php echo $name; ?>

When you want to get data from two different table.You need join query.
Here is your query which will solve your proble definitely :
$q="select a.name,b.rankID from rankname as a INNER JOIN user as b
ON a.rankID = b.rankID";
For more know about How to join two tables see this:http://www.tutorialspoint.com/sql/sql-using-joins.htm
Hope this will help you better.

Please try this
//Get rankID
$query = "SELECT r.name as rank_name FROM rank as r inner join users as u on r.rankID = u.rankID WHERE u.id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rank_name'];
echo 'Rank: '. $rank;

try this:
//Get rankID
$query = "SELECT rankID, rank.name AS rank_name FROM rank, users WHERE id = '$userId' and users.rankid = rank.rankid";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rank_name'];
echo $rank;

Related

how select from the database where the colum has the highest value in a table in sql

i have this table that has some data, but i want to get the row where a paticular coluom votecount has the highest value:
id
votecount
1
0
2
1
3
1
4
13
i tried this sql statement:
$selectr = "SELECT *, MAX(`votecount`) from `audio`";
$stmt = $conn->prepare($selectr);
$stmt->execute([]);
while($row = $stmt->fetch())
{
$userid = $row["id"];
$votecount = $row["votecount"];
echo $userid;
echo $votecount;
}
but it echos out 10 which means it got the first item in the table and the value is 0, which is wrong, its not getting the highest column
so how do i fix this
Try this:
$selectr = "SELECT * from `audio` where `votecount` = ( SELECT MAX(`votecount`) from `audio`)";
$stmt = $conn->prepare($selectr);
$stmt->execute([]);
while($row = $stmt->fetch())
{
$userid = $row["id"];
$votecount = $row["votecount"];
echo $userid;
echo $votecount;
}
Try correct: $userid = $row["userId"]; to $userid = $row["id"];

How get 1 question and 4 answers from this script?

I am creating a webGL game on Unity but want to get my php correct first.
I have 2 tables questions and answers. Each question has 4 potential answers and need to pull these from my db.
The answer table matches with the question table through questionId.
Questions:
Should I better use a table join or should I separate them?
Should I simply have a select statement just for the question table then a
join table for answers and submit separately?
Should I have created
the answer table with 4 columns for different answers?
Current code:
<?php
$query = ("select questiontable.questionId, questiontable.question, answertable.answerId,answertable.answer, answertable.questionId, questiontable.scoreValue
FROM questiontable
inner join answertable on questiontable.questionId=answertable.questionId ORDER BY RAND () LIMIT 1 ");
$result =mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$row_cnt = mysqli_num_rows($result);
echo $row_cnt;
echo $row ['question'];
echo $row ['answer'] ;
echo $row ['answer'] ;
echo $row ['answer'];
echo $row ['answer'];
}
?>
Here are my tables:
CREATE TABLE `braingain`.`questionTable`
( `questionId` INT NOT NULL AUTO_INCREMENT , `question` VARCHAR(600) NOT NULL , `scoreValue` INT NOT NULL , `subject` VARCHAR(50) NOT NULL , PRIMARY KEY (`questionId`));
CREATE TABLE `braingain`.`answerTable`
( `answerId` INT NOT NULL , `answer` VARCHAR(600) NOT NULL , 'questionId', isCorrect;
The query should pull questions and 4 associated answers into an array.
Desired result
The created array should look like this:
| question | answerA | answerB | answerC | answerD |
| WHICH IS THE CORRECT SPELLING? | APPLE | APEL | APPUL | APPAL |
Run two nested queries,
$output = array();
$answer_array = array('answerA','answerB','answerC','answerD');
$query = ("select * from questiontable ORDER BY RAND () LIMIT 1 ");
$result =mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$row_cnt = mysqli_num_rows($result);
$output['question']=$row['question'];
$query2 = ("select * from answerTable where questionId = ". $row ['questionId'] order by answerId);
$result2 =mysqli_query($conn, $query2) or die(mysqli_error($conn));
$i=0;
while ($row2 = mysqli_fetch_assoc($result2)){
$output[answer_array[$i]]=$row2['answer'];
$i++;
}
}
print_r($output);
?>
Please have a look at indentation, makes code much more plesant :)
<?php
$query = ("
SELECT
questiontable.questionId,
questiontable.question,
answertable.answerId,
answertable.answer,
answertable.questionId,
questiontable.scoreValue
FROM
questiontable
INNER JOIN
answertable on questiontable.questionId = answertable.questionId
ORDER BY RAND()
LIMIT 1
");
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$data = [];
$data[] = null;
$keys = [
'question',
'answerA',
'answerB',
'answerC',
'answerD',
];
$return = [];
while ($row = mysqli_fetch_assoc($result)){
if ($data[0] !== $row['question']) {
$data = [];
$data[] = $row['question'];
}
$data[] = $row['answer'];
if (count($data) === 5) {
$dataAssociative = array_combine($keys, $data);
$return[] = $dataAssociative;
}
}
var_dump($return);
?>
ok, so i have everything working with my php etc. i have it echoing the result as i want heres the code...
<?php
session_start();
include 'dbconnect.php';
$output = array();
$answer_array = array('answerA','answerB','answerC','answerD'); //loads answers into array
$query = ("select * from questiontable ORDER BY RAND () LIMIT 1 ");//sql query to get questions
$result =mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$row_cnt = mysqli_num_rows($result);
$output['question']=$row['question'];
$query2 = ("select * from answerTable where questionId = '". ($row ['questionId'])."' order by rand()");//sql query to get answers for questions by questionId
$result2 =mysqli_query($conn, $query2) or die(mysqli_error($conn));
$i=0;
$question=$row ['question'];
while ($row2 = mysqli_fetch_assoc($result2)){
$output[$answer_array[$i]]=$row2['answer'];
$i++;
$_POST = $output;
}
}
echo "</br> ";
echo $_POST ['question'];
echo "</br> ";
echo $_POST['answerA'];
echo "</br>";
echo $_POST['answerB'];
echo "</br>";
echo $_POST['answerC'];
echo "</br> ";
echo $_POST['answerD'];
?>
now i need to store the results in unity so i can assign them to buttons etc.
i have it pulling the details but unsure how to assign for example $_POST['answerA]; to a variable in c#.
this is my c# code...
public class qNaDisplay : MonoBehaviour {
public Text questionDisplayText, answerAText, answerBText, answerCText, answerDText;
public Text questMessage, answerMessage;
private string question, a, b, c, d;
// Use this for initialization
void Start ()
{
WWW questionURL = new WWW("http://localhost:8080/Project/PHP/questionRequest.php");
question = questionDisplayText.text;
a = answerAText.text;
b = answerBText.text;
c = answerCText.text;
d = answerDText.text;
StartCoroutine(qNaget(questionURL));
}
// Update is called once per frame
void Update () {
}
private IEnumerator qNaget (WWW questionURL)
{
yield return questionURL;
Debug.Log(questionURL.text);
if (questionURL.error != null)
{
print("There was an error getting the question " + questionURL.error);
}
else
{
Debug.Log (questionURL.text); // this is a GUIText that will display the scores in game.
}
}
}

Counting specific records MySQL

I want to show the count of users which have the status 1 (see code) within PHP MySQL.
<?php
// something like this
$result = mysqli_query($mysqli, "SELECT COUNT(*) FROM users WHERE status = '1'");
echo "$result";
?>
Try this:
$query = "SELECT COUNT(*) as countvar FROM users where status = '1'";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$count= $row['countvar '];

While loop showing only one record when i use nested while loop for fetch data from another table

I have case manager table where i have inserted court table id as foreign key. i want to fetch record from both tables. when using nested while loop it shows only one row data.
$id = $_SESSION['id'];
$query1 = "SELECT * from `case_manager` where user_id = '$id' ";
$result1 = mysqli_query($conn, "$query1");
while($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$Status = $row['status'];
$id = $row['id'];
$case_type = $row['case_type'];
$court_id = $row['court_id'];
$query2 = "SELECT * from `case_type` where case_id = '$case_type'";
if($result1 = mysqli_query($conn, "$query2")) {
while($row2 = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
echo $row2['case_name'];
}
}
}
Because you are overwritting you $result1 change inner query result to $result2 then try
$id = $_SESSION['id'];
$query1 ="SELECT * from `case_manager` where user_id = '$id' ";
$result1 = mysqli_query($conn , "$query1");
while ($row = mysqli_fetch_array($result1 ,MYSQLI_ASSOC)) {
$Status=$row['status'];
$id = $row['id'];
$case_type = $row['case_type'];
$court_id = $row['court_id'];
$query2 ="SELECT * from `case_type` where case_id = '$case_type'";
if($result2 = mysqli_query($conn , "$query2")){;
while ($row2 = mysqli_fetch_array($result2 ,MYSQLI_ASSOC)) {
echo $row2['case_name'];
}
}
}
1st : Because you are overwriting the variable $result1 In second query execution.
if($result1 = mysqli_query($conn , "$query2")){;
^^^^^^^^ ^^
Note : And remove that unnecessary semicolon .
2nd : No need multiple query simple use join
SELECT cm.*,c.* from `case_manager` cm
join `case_type` c
on cm.cas_type=c.case_id
where cm.user_id=$id;
You can use below query to fetch your record:
$query = SELECT case_manager.* ,case_type.case_name FROM case_manager Left JOIN case_type ON case_manager.case_type=case_type.case_id where case_manger.user_id = $id;
While($row = mysql_fetch_array()){
echo $row['case_name'];
}

PHP MYSQL Nested While loop skips iterations

Need help to get through this Nested WHILE loop.
The Scenario is
These are the 5 tables in my db
user_info(userid,name,picurl)
user_friends(userid,friend_id)
user_post(userid,post_id,post,time)
user_likes(userid,post_id)
user_comments(userid,post_id)
I want to access user_post table and populate the data in my android application. i can access userid,post_id and time from user_post table and using friend_id of the user from friends table. Now to display a complete post with pic and name i need to access name and picurl of the person who's post it is from user_info table. If i need to display one 1 friends post i can do this simply but when there are couple of friends with more than 1 post i can't get the name and picurl of the user and it displays null in json response.
I'm using Nested While loop for this operation following is my code.
$userid = $_POST['userid'];
$query = "SELECT * FROM user_friend WHERE userid = '$userid'";
$result = mysql_query($query);
$return_arr = array();
$return_arr['newsfeed'] = array();
//Access userid
while($row = mysql_fetch_assoc($result)) {
echo "Friend Name is ".$row['friend_id']. "<br>";
$friend_id = $row['friend_id'];
$friend_id = mysql_real_escape_string($friend_id);
//accessing user_info table to access user info
$picquery = "SELECT * FROM user_info WHERE userid = '$friend_id'";
$picresult = mysql_query($picquery);
$pic = mysql_fetch_assoc($picresult);
$row_array['name'] = $pic['name'];
$row_array['picurl'] = $pic['picurl'];
$query2 = "SELECT * FROM user_post WHERE userid = '$friend_id'";
$result2 = mysql_query($query2);
//Access Posts Against userids
while( $row = mysql_fetch_array($result2) ) {
$post_id = $row['post_id'];
//for number of likes
$likesQuery = "SELECT COUNT(*) as totallikes FROM post_likes WHERE post_id = '$post_id'";
$likesResult = mysql_query($likesQuery);
$likesvalues = mysql_fetch_assoc($likesResult);
$num_of_likes = $likesvalues['totallikes'];
//for number of comments
$commentsQuery = "SELECT COUNT(*) as totalcomments FROM post_comments WHERE post_id = '$post_id'";
$commentsResult = mysql_query($commentsQuery);
$commentsvalues = mysql_fetch_assoc($commentsResult);
$num_of_comments = $commentsvalues['totalcomments'];
$row_array['post_id'] = $row['post_id'];
$row_array['userid'] = $row['userid'];
$row_array['post_text'] = $row['post_text'];
$row_array['post_time'] = $row['post_time'];
$row_array['post_num_likes'] = $num_of_likes;
$row_array['post_num_comments'] = $num_of_comments;
array_push($return_arr['newsfeed'],$row_array);
}
}
date_default_timezone_set('Asia/Karachi');
$date = date(' h:i:s a d/m/Y', time());
echo json_encode($return_arr,JSON_UNESCAPED_SLASHES);
something like this could help. As I don't have any test data I cannot see how it's working. It should display the post_id along with the count of the likes and the comments
SELECT
p.post_id,
COUNT(c.post_id) AS comments_count,
COUNT(l.post_id) AS like_count
FROM user_post p,
user_likes l,
user_comments c
WHERE p.post_id = l.post_id
AND p.post_id = c.post
GROUP BY p.post_id

Categories