I have a website in which logged in members are stored under a table called ‘users’
‘users’ table
users_sales_guild_id | users_first_name | users_surname
555 | Jane | Smith
333 | John | Smith
111 | Mike | Myers
The users have sales data in a 'sales_points' field which is in a separate table called ‘sales_list’.
‘sales_list’ table
sales_id | users_sales_guild_id | sales_points | sales_entry_date
1 | 555 | 50 | 2013-02-31 00:00:00
2 | 333 | 30 | 2013-02-31 00:00:00
3 | 111 | 10 | 2013-02-31 00:00:00
4 | 555 | 50 | 2013-03-31 00:00:00
5 | 333 | 30 | 2013-03-31 00:00:00
6 | 111 | 10 | 2013-03-31 00:00:00
Essentially what I am trying to do is a query which:
A. Calculates the total amount of 'sales_points' for each user from 'sales_list'
B. Lists 100 users with the user having the most points at the top, then ranking the next highest below and so on...
C. Im not after a ranking number, just the order itself.
With the code below I am getting 100 users printing ok, however I am getting a ‘Resource id #9’ message in the ’Total Points’ column when it prints. Can anyone help?
What I am trying to print
Jane Smith | 100
John Smith | 60
Mike Myers | 20
Code:
<?php
require_once ('config.inc.php');
$page_title = '';
include ('header.html');
if (!isset($_SESSION['users_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= 'login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}?>
<h1>Rankings</h1>
<?php require_once ('database.php'); // Connect to the database.
$total = mysql_query("SELECT SUM(sales_points) FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
$query = "SELECT us.users_id, us.dealership_id, us.users_sales_guild_id, us.users_first_name, us.users_surname, us.users_type,
de.dealership_id, de.users_dealer_name, de.class , de.region, de.state, de.users_dealer_code_id, de.users_dealer_code_new_id, de.users_model, de.pma
FROM users AS us, dealerships AS de
WHERE us.dealership_id = de.dealership_id
ORDER BY ’$total’ DESC
LIMIT 100";
$result = #mysql_query ($query);
// Table header.
echo '<table width="680"cellpadding="5" cellspacing="1" style="font-size:12px;">
<tr class="orangehead">
<td align="center"><b>Member</b></td>
<td align="center"><b>Title</b></td>
<td align="center"><b>Dealer</b></td>
<td align="center"><b>Category</a></b></td>
<td align="center"><b>Dealer Code</a></b></td>
<td align="center"><b>Total Points</a></b></td>
</tr>';
// Fetch and print all the records. echo '<td align="left"><strong>' . $row['sp_invoice_no'] . '</strong></td> ';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced'); // Switch the background color. New: ' . $row['users_sales_guild_new_id'] . '
// $entries = floor($row['sp_entry_amount']/200);
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left"><strong>' . $row['users_first_name'] . ' ' . $row['users_surname'] . '</strong></td> ';
echo '<td align="center">' . $row['users_type'] . ' </td>';
echo '<td align="center"> ' . $row['users_dealer_name'] . ' </td>';
echo '<td align="center"> ' . $row['class'] . ' </td>';
echo '<td align="center"> ' . $row['users_sales_guild_id'] . ' </td>';
echo '<td align="center"> ' . $total . '</td>';
echo '</tr>
';
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
include ('footer.html'); // Include the HTML footer.
?>
You don't fetch you first result. Fetch it as an array (mysql_fetch_array()) for example.
// Execute query
$total_query = mysql_query("SELECT SUM(sales_points)
FROM sales_list, users
WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'");
// Fetch result
$total = mysql_fetch_array($total_query);
You echo this:
$total = mysql_query("SELECT SUM(sales_points) FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
The variable $total contains the result of the query, which is a Resource. You should use mysql_fetch_assoc or a similar function to extract the result itself. It's best to give the SUM(sales_points) an alias, i.e. AS total_sales_points so you can fetch is easily.
By the way, the mysql_*-extension is soon-to-be deprecated. Good alternatives include MySQLi and PDO.
$query = mysql_query("SELECT SUM(sales_points) as points FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
$row = mysql_fetch_object($query);
$total = $row->points;
You are echoing the mysql resource, you first need to fetch the results, then you can echo them.
Related
So I am currently using PHP to pull the bodies from emails, parse the data, and insert the data into a user-created DB. I want to display an overview of the data (that is inside the DB) using PHP. Here is an example of what I want to achieve:
This is my table:
Table Name: bldgSensors
sensor_code | temp_limit | current_temp
---------------------------------------
0102260100A | 55 | 45
0102260100B | 55 | 50
0102260100A | 55 | 48
Desired output using PHP:
Sensors Count
0102260100A 2
0102260100B 1
So far, I can find distinct values but cannot output the total count:
$result1 = mysqli_query($DBconn,"SELECT DISTINCT sensor_code FROM bldgSensors");
echo "<table border='1'>
<tr>
<th>Distinct sensor codes</th>
<th>Count</th>
</tr>";
while($row1 = mysqli_fetch_array($result1))
{
echo "<tr>";
echo "<td>" . $row1['sensor_code'] ."</td>";
}
echo "</table>";
mysqli_close($DBconn);
Thanks so much in advance! This will help tremendously!
You can do that by modifying your query. Use the COUNT and GROUP BY sql functions:
Try this:
$query = "SELECT
sensor_code,
COUNT(sensor_code) AS sensorCount
FROM bldgSensors
GROUP BY sensor_code
ORDER BY sensorCount DESC";
$result1 = mysqli_query($DBconn, $query);
echo
'<table border="1">
<tr>
<th>Distinct sensor codes</th>
<th>Count</th>
</tr>';
while($row1 = mysqli_fetch_array($result1)){
echo
'<tr>' .
'<td>' . $row1['sensor_code'] . '</td>' .
'<td>' . $row1['sensorCount'] . '</td>' .
'</tr>';
}
echo
'</table>';
mysqli_close($DBconn);
I've got two tables in mySQL.
Table: Player
-----------------------------------------------------------
| name | T1 | T2 | T3 | T4 | T5 | id | weeknumber |
|--------|----|-----|-----|-----|-----|-----|-------------|
| | | | | | | | |
| | | | | | | | |
-----------------------------------------------------------
Table: Teams
-------------------------------------------------------------------------
| id | team1name | team2name | team1score | team2score | weeknumber |
|------|-----------|-----------|-------------|------------|-------------|
| | | | | | |
| | | | | | |
-------------------------------------------------------------------------
The idea is, that table "Teams" is getting populated through another page that already works for me.
Every week there will be 13 new teams.
Table "Player" has to get populated from another page where the user gets the following options:
Name: Text-field
13 Checkboxes (those checkboxes need to store the value ID from table Teams)
The user is supposed to check 5 out of 13 teams (free choice) and the values of those checkboxes (the ID of the Teams ID) should be stored as T1, T2, T3, T4, T5 along with Name from text-field.
<form method="post" action="created.php" class="form-style-7">
<h2>Tilmeld en spiller </h2>
<ul>
<li>
<label for="name">Navn</label>
<input type="text" name="navn" value="<?php echo $navn;?>">
<span>Indtast spillerens navn</span>
</li>
<li>
<?php
$count = $rows = 0;
$sql = "SELECT * FROM Teams WHERE weeknumber='$WeekNumber' ORDER BY id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '
<table class=""><tr><th colspan="3">Igangværende - Uge ' . $WeekNumber . '</th></tr>
<tr class="underhead"><td>#</td><td>Kamp</td><td>Mål</td></tr>
';
// Output af data
while($row = $result->fetch_assoc()) {
if ($rows % 1 == 0) {
$count++;
}
$rows++;
echo '<tr>';
echo '<td>';
echo '';
echo '<input type="hidden" name="ID" value="' . $row['id'] . '" >';
echo '<input class="btn" type="checkbox" name="" > ';
echo ' </form>';
echo '</td>';
echo '<td>' . $count . '</td>';
echo '<td>' . $row["team1name"]. ' - ' . $row["team2name"] . '</td>
</form>';
}
echo '</table>';
}
mysqli_close($conn);
?>
</li>
<li id="buttontilmeld">
<input type="submit" name="submit" value="Tilmeld" >
</li>
</ul>
</form>
Edit:
My created.php contains the following:
if (isset($_POST['navn']) && $_POST['navn'] != "") {
if (isset($_POST['navn'])) {
if ($_POST['name'] == "" || $_POST['T1'] == "" || $_POST['T2'] == "" || $_POST['T3'] == "" || $_POST['T4'] == "" || $_POST['T5'] == "") {
echo 'XX';
}
} else {
require 'config.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['navn']);
$match1 = $conn->real_escape_string($_POST['kamp1']);
$match2 = $conn->real_escape_string($_POST['kamp2']);
$match3 = $conn->real_escape_string($_POST['kamp3']);
$match4 = $conn->real_escape_string($_POST['kamp4']);
$match5 = $conn->real_escape_string($_POST['kamp5']);
$WeekNumber = date('W');
$query = "INSERT into Spillere (navn,kamp1,kamp2,kamp3,kamp4,kamp5,ugenummer) VALUES('" . $name . "','" . $match1 . "','" . $match2 . "','" . $match3 . "','" . $match4 . "','" . $match5 . "','" . $WeekNumber . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
echo "Thanks";
}
}
}
Where I need $_POST['TX']=="" to populate table Player T1 to T5.
The name attribute of the checkboxes are not set. PHP can't get any info about the checked checkboxes (unless you should use Jquery en do some other stuff). It's important to know that only checked checkboxes will be visible in the POST data.
Give your checkboxes a name, for example:
echo '<input class="btn" type="checkbox" name="team_checkbox_'.$row['id'].'"> ';
Then in the script created.php were your data is posted to you can catch these values by running the same SQL-query and trying
if(isset($_POST['team_checkbox_'.$row['id']])){
// $row['id'] is checked
}
Or just check all POST data:
$t = array();
foreach($_POST as $post_param_name => $value){
if(substr($post_param_name, 0, 14) == 'team_checkbox_'){
// substr($post_param_name, 14) is the ID of one of the checked groups
$t[] = substr($post_param_name, 14);
}
}
Now $t is an array containing the team ID's of the checkboxes. So you can save in your SQL: T1 = $t[1], ...
This answer should be reviewed, but the solution is in another answer here:
https://stackoverflow.com/a/47162431/1589379
Follow good coding standards
There's a lot of little problems with the code you posted. Ultimately, you should always be very careful to keep everything properly indented, and always use brackets {}, even if they're not needed.
Your original code:
while (...) {
if ($rows % 1 == 0)
$count++;
Should be:
while (...) {
if ($rows % 1 == 0) {
$count++;
}
Those adjustments would have made it much more clear that your code had two closing </form> tags, and no opening tags, within your while loop.
I am trying write code in PHP with a Mysql database, and the problem is I want to show all rows with a same column value. for example like this:
id | Name | age | Location | type
----+----------+-----+----------+------
1 | Ane | 22 | SG | 1
2 | Angi | 19 | IND | 2
3 | Bobby | 23 | PH | 1
4 | Denis | 26 | IND | 1
5 | Jerry | 21 | SG | 1
6 | Mikha | 25 | JP | 2
I want only show the rows with value in column type = 1 or value in column Location and showing as table in html view.
The result what I want is like this:
id | Name | age | Location | type
---+----------+-----+----------+------
1 | Ane | 22 | SG | 1
3 | Bobby | 23 | PH | 1
4 | Denis | 26 | IND | 1
5 | Jerry | 21 | SG | 1
This is my code:
<?php
$con = mysqli_connect("localhost","root","","testuser");
$query = mysqli_query("SELECT * FROM `usersdata` WHERE `type`='1'");
$result = mysqli_query($con,$query);
echo "<table class='tmaintable' border='0' cellpadding='3' width='99%' align='center' cellspacing='1'>
<tr class='theader'>
<td>ID</td>
<td>Name</td>
<td>Age</td>
<td>Location</td>
<td>Type</td>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr class='todd'>";
echo "<td style='text-align:center;' >" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
But I got errors like this:
Warning: mysqli_query() expects at least 2 parameters, 1 given in www.myweb.com\users_list\type.php on line 94 << this point "$query" line
Warning: mysqli_query(): Empty query in www.myweb.com\users_list\type.php on line 95 << this point "$result" line
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in www.myweb.com\users_list\type.php on line 109 << this point "while ($row=" line
I was trying understand and still i don't get it, anyone can help me please?! thanks.
Change
$query = mysqli_query("SELECT * FROM usersdata WHERE type='1'");
to
$query = "SELECT * FROM usersdata WHERE type='1'";
EDIT
Just for explanation:
mysqli_query takes 2 arguments: connection and query. I assumed that you wanted to just create query string in this line where this error arouse since it is used one line furter as a query string.
Issue is in bolow lines.
$query = mysqli_query("SELECT * FROM usersdata WHERE type='1'");
$result = mysqli_query($con,$query);
You have 2 ways to resolve this.
1. $query = "SELECT * FROM `usersdata` WHERE `type`='1'";
$result = mysqli_query($con,$query);
2. $query = mysqli_query($con,"SELECT * FROM `usersdata` WHERE `type`='1'");
Try this one. It should be working fine
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `usersdata` WHERE `type`='1'";
$result = mysqli_query($conn, $sql);
echo "<table class='tmaintable' border='0' cellpadding='3' width='99%' align='center' cellspacing='1'>
<tr class='theader'>
<td>ID</td>
<td>Name</td>
<td>Age</td>
<td>Location</td>
<td>Type</td>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr class='todd'>";
echo "<td style='text-align:center;' >" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
I am trying to assigned each student with a company from a drop down list and have it updated in the database under the correct student.
So basically, this is how my website looks like.
___________________________________________________________________
| Student ID | Admin No | Student Name | Company List |
| 1 | 1234 | ABC | <drop down list> |
| 2 | 2345 | BCD | <drop down list> |
| 3 | 3456 | CDE | <drop down list> |
| 4 | 4567 | DEF | <drop down list> |
And this is the codes for the table above.
<form name="IT" action="getIT_now.php" method="post">
<table cellspacing="0">
<tr>
<th>Student ID</th>
<th>Admin Number</th>
<th>Student Name</th>
<th>GPA</th>
<th>Gender</th>
<th>Company List</th>
</tr>
<?php
$con=mysqli_connect("....","....","....",".....");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create the query
$result = mysqli_query($con,"SELECT student_id, admin_no, name, GPA, gender FROM student_details WHERE jobscope1= 'Information Technology' ORDER BY `GPA` DESC; ");
$result2 = mysqli_query($con,"SELECT job_title FROM job_details WHERE jobscope='Information Technology' ORDER BY `job_title` ASC;");
/*options sections start*/
$options= '';
while ($row2 = mysqli_fetch_assoc($result2))
{
$options .='<option value="'. $row2['job_title'] .'"> '. $row2['job_title'] .'</option>';
}
/*options sections end*/
//return the array and loop through each row
while($row = mysqli_fetch_assoc($result))
{
$studentid = $row['student_id'];
$adminno = $row['admin_no'];
$name = $row['name'];
$gpa = $row['GPA'];
$gender = $row['gender'];
echo "<tr>";
echo "<td>" . $studentid . "</td>";
echo "<td>" . $adminno . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $gpa . "</td>";
echo "<td>" . $gender . "</td>";
echo "<td><select name='ddl' onclick='if(this.value != '') { myform.submit(); }'>".$options."</select></td>";
}
echo "</tr>";
?>
</table>
<input type='submit' value='Submit Pick' />
</form>
Now this form will actually go to another page since I have include a form action.
So the codes in this getIT_now.php page is
<?
$con=mysqli_connect("...","....","....","....");
if (!$con)
{
die('Could not connect: ' . mysqli_errno());
}
$ddlvalues = $_POST['ddl'];
$studentid = $_POST['student_id'];
$query = mysqli_query($con, "INSERT INTO student_details(company) VALUES('" . $ddlvalues . "');");
?>
However, when I check the database, only the first option in the drop down list is reflected in a new row. I have tried to use the UPDATE query statement, but it is wrong.
This is the query for the UPDATE statement.
UPDATE student_details SET company = '" . $ddlvalues . "' WHERE student_id = '" . $studentid . "';
The problem I'm having right now is actually:
How do I make Student ID on the website and in the database to match so that it can update correctly?
Why is it that only the first option in the drop down list is reflected when I use the INSERT query?
I am quite new to PHP so I am really struggling with this.
You don't have an input that holds the student_id, i.e $_POST['student_id'] is not set, also you would have to validate the user inputs before you pass them to query, You can use prepared statements,
Try with a hidden field like
echo '<input type="hidden" name="student_id" value="'.$studentid.'"/>';
I am trying to create reports based on data from a log in the database that looks like:
id | student | type | marks
1 23494 CAT1 50
2 23495 CAT1 20
3 23494 CAT2 35
4 23495 MIDTERM 40
My select statement so far looks like this:
$res = #mysqli_query ($dbc, "SELECT id, student, type, GROUP_CONCAT(marks) AS mark, GROUP_CONCAT(type) AS types FROM log WHERE class = '1' AND term = '2' GROUP BY student DESC");
// Fetch and print all the records....<br>
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
echo '<tr>
<td align="left">'. $row['student'] .'</td>';
//$exams = split(",", $row['exams']); // 4,3,1,2
$marks = split(",", $row['mark']); // 10,20,40,50
foreach( $marks as $mark ) {
echo '
<td align="left">' . $mark . '</td>
';
}
echo '</tr>';
} //End LOOP
//Then i end table
So far the data displays like so:
STUDENT | CAT1 | CAT2 | MIDTERM
23494 50 35
23495 20 40
The problem is that the code is not arranging 'marks' according to 'type' (look at MIDTERM output for id 4 and corresponding display).
Question:
How do i display the results by student, followed by marks in the appropriate cell/group like so:?
STUDENT | CAT1 | CAT2 | MIDTERM
23494 50 35
23495 20 40
Thanks in Advance Guys.
First, try to keep logic away from layout. It's generally good practice to first gather the data you need, and then display it.
Using GROUP_CONCAT can make things more complicated, since you do not know how many results you will get for each student, nor will you be able to easily identify which marks are of what type.
With that in mind I've created a solution. You'll still need to extend the query of course.
$query = 'SELECT student, type, marks FROM log';
$res = mysqli_query($query);
$studentMarks = array();
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC))
{
$studentMarks[$row['student']][$row['type']] = $row['marks'];
}
// Now $studentMarks should look like:
// $studentMarks = array(
// 23494 => array('CAT1' => 50, 'CAT2' => 35)
// , 23495 => array('CAT1' => 20, 'MIDTERM' => 40)
// );
echo '<table><thead><tr>';
echo '<td>Student</td><td>CAT1</td><td>CAT2</td><td>MIDTERM</td>';
echo '</tr></thead><tbody>';
foreach($studentMarks as $studentId => $marks)
{
echo '<tr>';
echo '<td>', $studentId, '</td>';
echo '<td>', (isset($marks['CAT1']) ? $marks['CAT1'] : ' '), '</td>';
echo '<td>', (isset($marks['CAT2']) ? $marks['CAT2'] : ' '), '</td>';
echo '<td>', (isset($marks['MIDTERM']) ? $marks['MIDTERM'] : ' '), '</td>';
echo '</tr>';
}
echo '</tbody></table>';