SELECT userinformation where userid is in the most rows - php

I have a table that contains the same userid multiple times.
I would like to return the picture of 9 users that have the most rows with their userid in it.
How can I select the user with the most rows and the ones following (from most to least)?
It's probably something easy but I can't find an answer.
$sql ="SELECT * FROM beoordelingen,users WHERE beoordelingen.userid=users.userid
GROUP BY beoordelingen.userid LIMIT 9 ";
$result = $conn->query($sql) or die ("The query could not be completed. try again");
$cols=3;
echo "<table width='150' border='0' cellpadding='0'>"; // The container table with $cols columns
do{
echo "<tr>";
for($i=1;$i<=$cols;$i++){ // All the rows will have $cols columns even if
// the records are less than $cols
$row=mysqli_fetch_array($result);
if($row){
echo"<td>
<table width='150' border='0' cellpadding='0'>
";
if ($row["userimage"] == '') {
echo "<a href='user.php? id=" . $row['userid'] . "'</a><img src='Images/users/nopicture.png' alt='nopicture'
class='userimage-tooltip-large' title='".$row['username']."''>";
} else {
echo "<a href='user.php? id=" . $row['userid'] . "'</a><img src='Images/users/".$row['userimage']."'
class='userimage-tooltip-large' title='".$row['username']."''>";
}
echo"</table>
</td>";
} else {
echo "<td> </td>"; //If there are no more records at the end, add a blank column
}
}
} while($row);
echo "</table>";

Add a count of the rows with the userid, order by that descending and then use the limit:-
SELECT users.userimage,
users.userid,
users.username,
COUNT(*) AS userid_count
FROM beoordelingen
INNER JOIN users
ON beoordelingen.userid=users.userid
GROUP BY beoordelingen.userid
ORDER BY userid_count DESC
LIMIT 9
Note that which values you get of the columns other than the userid is not defined. If you want the values from a particular row then this is a bit more complicated and you need to define which one.

Related

mysql get the value of a column in a database as a percentage

I have a table in a database and am currently pulling data using the SELECT statement Where the information from the column Opinion equals either Negative or Positive.
what i want to also do is output the positive data as an overall percentage but Unsure if that would be possible i had a look at multiple overflow questions but couldn't see anything. Any help would be appreciated.
$sql = "select Opinion from survey where Opinion = 'Positive'";
$result = mysqli_query($con, $sql);
if (!$result) {
die(mysqli_error($con));
}
echo "<div style='overflow: auto;'>";
echo "<table width=40% border=1 align=center >
<tr>
<th>Opinion</th>
<th>Date</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr align=center>';
echo "<td>" . $row['Opinion'] . "</td>";
}
} else {
echo "0 results";
}
?>
The query will calculate how many percentage of 'Positive' opinions compared to total rows of the 'survey' table:
select (SUM(IF(Opinion = 'Positive',1,0))/count(*))*100 as percentage_positive
from survey
The query below can determine the percentage of each different opinions at once:
select
Opinion,
count(*) as total,
(count(*) / (select count(*) from survey))*100 as percentage
from survey
group by opinion
Something like this as SQL query?
SELECT COUNT(Opinion) / (SELECT COUNT(Opinion) FROM survey) * 100
FROM survey
WHERE Opinion = 'Negative'
After help from Kevin HR i have fixed my issue with the code below.
$sql = "select Opinion,count(*) as total,(count(*) / (select count(*) from survey))*100 as percentage from survey group by opinion";
$result = mysqli_query($con, $sql);
echo "<div style='overflow: auto;'>";
echo "<table width=40% border=1 align=center >
<tr>
<th>Opinion</th>
<th>Percentage</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr align=center>';
echo "<td>" . $row['Opinion'] . "</td>";
echo "<td>" . $row['percentage'] . "</td>";
}
}
else {
echo "0 results";
}
Working code for getting the value of number of rows from a database
$sql = "SELECT * FROM `survey` WHERE Opinion='Positive'";
$connStatus = $con->query($sql);
$numberOfRows = mysqli_num_rows($connStatus);
echo "There are a total number of $numberOfRows Positive rows in the database";
echo "<br>";
echo "<br>";

sort my display data based on their user role

hi i already can make search. now how i want to put that data based on their role, based on this picture i want to make admin ,admin , user, user,user. need to use sort by ? i dont know.
and this my coding search . where should i put sort by ?
<?php
include 'config1.php';
if(isset($_POST['search'])){
$searchTerm = $_POST['search'];
$query = "SELECT * FROM members WHERE userid LIKE '%$searchTerm%'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
echo "<table height = '30%'border='1'>";
if($count == 0)
{
echo "NO ID REGISTERED!";
}
else
{
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td width='5%'><b>USER ID:</b> {$row['userid']} </td>";
echo "<td width='5%'><b>USER NAME :</b> {$row['username']} </td>";
echo "<td width='5%'><b>USER EMAIL:</b> {$row['useremail']} </td>";
echo "<td width='5%'><b>USER ROLE:</b> {$row['userrole']} </td>";
echo "<td width='5%'><b>USER DIVISION:</b> {$row['userdiv']} </td>";
echo "<td width='5%'><b>USER DEPARTMENT:</b> {$row['userdepartment']} </td>";
echo "</tr>";
}
}
echo"</table>";
}
?>
$query = "SELECT * FROM members WHERE userid LIKE '%$searchTerm%' ORDER BY userrole";
Also can use ASC or DESC for displaying in ascending or descending order after ORDER BY.
eg.
Select * from users WHERE choice = 'PHP' ORDER BY id ASC;
$query = "SELECT * FROM members WHERE userid LIKE '%$searchTerm%' order by fieldWhichYouWant";
OR
$query = "SELECT * FROM members WHERE userid LIKE '%$searchTerm%' ORDER BY userrole ASC";
or add ASC or DESC as Ascending or descending oder to sort.
Replace fieldWhichYouWant with your requirement.

Show all items from a database even without a picture

I'm making a webpage that displays my database. I'm using 2 tables for this.
Table 'artikel' and 'images'
Both tables got a key that link to each other: A_ARTCODE and I_ARTCODE
Both keys are the same.
Now I got the problem my keys were not linked and I saw this was, because I didn't used this:
WHERE artikel.A_ARTCODE = images.I_ARTCODE
So first my page looked like this: click here
and when I used that code I got this: click here
Like you see, now my both ID's are correct.
But I was talking about my tables, in the table 'images' I only got 2 images. Those you see now, but I got like 383 items in my 'artikel' table.
My question now is, how can I display them all? Even the items without a picture?
This is my total php code:
<?php
include('connect-mysql.php');
if (!empty($_GET["page"])) {
$page = $_GET["page"];
} else {
$page=1;
};
$start_from = ($page-1) * 20;
$sqlget = "SELECT *
FROM artikel, images
WHERE artikel.A_ARTCODE = images.I_ARTCODE
LIMIT $start_from, 20
";
$sqldata = mysqli_query($dbcon, $sqlget) or die('error getting');
define('IMAGE_PATH', 'images/');
$sql = "SELECT COUNT(A_ARTCODE) FROM artikel";
$rs_result = mysqli_query($dbcon, $sql) or die ("mysqli query dies");
$row = mysqli_fetch_row($rs_result) or die ("mysqli fetch row dies");
$total_records = $row[0];
$total_pages = ceil($total_records / 20);
echo "<div class='boven'>";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=".$i."'>".$i."</a> ";
};
echo "</div>";
echo "<table>";
echo "<tr><th>A_ARTCODE</th><th>A_NUMMER</th><th>A_OMSCHRN</th><th>A_REFLEV</th><th>A_WINKEL</th><th>I_ARTCODE</th><th>I_FILE</th></tr>";
while($row = mysqli_fetch_array($sqldata)){
echo "<tr><td align='right'>";
echo $row['A_ARTCODE'];
echo "</td><td align='left'>";
echo $row['A_NUMMER'];
echo "</td><td align='left'>";
echo $row['A_OMSCHRN'];
echo "</td><td align='left'>";
echo $row['A_REFLEV'];
echo "</td><td align='right'>";
echo $row['A_WINKEL'];
echo "</td><td align='right'>";
echo $row['I_ARTCODE'];
echo "</td><td align='right'>";
echo "<img src='". IMAGE_PATH . $row['I_PATH']. '/' . $row['I_ID']. '.png' ."' />";
echo "</td></tr>";
}
echo "</table>";
echo "<div class='onder'>";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=".$i."'>".$i."</a> ";
};
echo "</div>";
?>
To achieve this U could use a LEFT JOIN sql.
This will give u all records for the articles, even when no images are defined for it
SELECT *
FROM artikel a
LEFT JOIN images i
ON a.A_ARTCODE = i.I_ARTCODE
LIMIT $start_from, 20
One way is to use a left join.
select *
from artikel
left join images
on artikel.A_ARTCODE = images.I_ARTCODE
LIMIT $start_from, 20;
Break yourself of the habit of writing things like from artikel, images; this isn't 1989. Use ANSI joins.
Another way is to guarantee that every row has an image. Use a default image (and a default value with a "not null" constraint for it in the table). It might be just a gradient with the text "Picture coming soon" on it.

Using MySQL Count function

I want to count all user records and display them in tables, I am trying this code code, It displays the record for one user only, I want to display records from all users.
$u=$_POST['userid'];
$result1 = mysqli_query($con,"SELECT COUNT(user_id) as total FROM table-name where user_id=$u");
echo "<table border='1'>
</tr>
<tr>
<th>User ID</th>
<th>count</th>
</tr>";
while($row = mysqli_fetch_array($result1))
{
echo "<tr>";
echo "<td>" . $u . "</td>";
echo "<td>" . $row['total'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
Try the following SQL Query:
SELECT `user_id`, COUNT(`user_id`) as `total` FROM `table-name` GROUP BY `user_id`;
Refer to the documentation of the GROUP BY clause.
Use below:
$result1 = mysqli_query($con,"SELECT COUNT(user_id) as total FROM table-name");
where clause use for filter the data.
refer http://www.w3schools.com/sql/sql_where.asp

PHP: table structure

I'm developing a website that has some audio courses, each course can have multiple lessons. I want to display each course in its own table with its different lessons.
This is my SQL statement:
Table: courses
id, title
Table: lessons
id, cid (course id), title, date, file
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
Can someone help me with the PHP code?
This is the I code I have written:
mysql_select_db($database_config, $config);
mysql_query("set names utf8");
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<p><span class='heading1'>" . $row['course'] . "</span> </p> ";
echo "<p class='datum'>Posted onder <a href='*'>*</a>, latest update on " . strftime("%A %d %B %Y %H:%M", strtotime($row['date']));
}
echo "</p>";
echo "<class id='text'>";
echo "<p>...</p>";
echo "<table border: none cellpadding='1' cellspacing='1'>";
echo "<tr>";
echo "<th>Nr.</th>";
echo "<th width='450'>Lesso</th>";
echo "<th>Date</th>";
echo "<th>Download</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['nr'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . strftime("%d/%m/%Y", strtotime($row['date'])) . "</td>";
echo "<td><a href='audio/" . rawurlencode($row['file']) . "'>MP3</a></td>";
echo "</tr>";
echo "</table>";
echo "<br>";
}
?>
One thing that comes to mind is you're starting with lessons and pulling the course details over with it. That means you're going to have a new row per lesson with a joined course. You may want to sort by course (so they're grouped) then (in PHP) keep a tally of "current course". When the course changes, switch to new heading paragraph, table, etc.
Pseudo code:
$currentCourse = null; // intitialize the course
$query = your select sorted by course;
while ($row in $query)
{
if ($currentCourse != $row['course'])
{
if (!is_null($currentCourse))
{
// there was a course before it, close the current one
}
// begin setting up heading1, table beginning, etc.
$currentCourse = $row['course']; // set this as the active course
}
// dump the current row as a table entry
}
// close the table (same code as in the second if statement)
You close the while loop on line 8 of your code block. Remove that '}' on line 8.
Also the HTML element doesn't exists!
I think I know what's your problem. You need a while loop that loops al the "courses" and in that loop you execute a second query where you select the lessons where the course_id is equal to the current course id you're looping. A little dummy code for you.
<?php
while($row = mysql_fetch_assoc(mysql_query("SELECT * FROM courses"))) {
//display the course
while($row2 = mysql_fetch_assoc(mysql_query("SELECT * FROM lessons WHERE course_id=" . $row['id']))) {
//display the lessons of that course
}
}
?>

Categories