PeterM helped me with this question, but i dont want to create new one, thats why im editing this one.
I got another problem, sorry, im just new with sql.
This is my code that output all the information I need from the database.
What i want:
I created table with name "customers" with columns "id and customername".
Then i created simple script with INSERT INTO "customers", yes, its script like admin page.
The idea is: I want to add new orders from a separate page, for example: admin.php so I don't have to do it from a file.
How to easily do this?
I have admin.php file with: INSERT INTO customers (customername) VALUES (customername) and its working, i can add new order to database, when i fill html form, it doesn't show my new added order.
<?php
$output = "SELECT *, SUM(enddate - startdate) AS time FROM employees GROUP
BY id";
$result = mysqli_query($conn, $output);
WHILE ($row = mysqli_fetch_assoc($result)) {
$EMPLOYEE = $row['employee'];
$CUSTOMER = $row['customername'];
$WORKDATE = $row['workdate'];
$WORKTYPE = $row['worktype'];
$DAYHOURS = $row['startdate'];
$ENDDATE = $row['enddate'];
$TOTAL = $row['time'];
echo "
<tr>
<td>$EMPLOYEE</td>
<td>$CUSTOMER</td>
<td>$WORKDATE</td>
<td>$WORKTYPE</td>
<td>$DAYHOURS</td>
<td>$ENDDATE</td>
<td>$TOTAL</td>
</tr>";
}
?>
My html form:
<div class='row'>
<div class='col-25'>
<label for='customers'>Choose OrderName</label>
</div>
<div class='col-75'>
<select name='customername'>
<?php
$customers = "SELECT customername FROM customers";
$result = mysqli_query($conn, $customers);
WHILE ($row = mysqli_fetch_assoc($result)) {
$customer = $row['customername'];
echo "<option value=''>$customer</option>";
}
?>
</select>
</div>
</div>
You should change your query into something like this:
SELECT *, SUM(`enddate` - `startdate`) AS time FROM `employees` GROUP BY `employee`;
First you need to subtract the startdate from the enddate then get the sum of all the grouped results, hence the SUM part.
This should give you a result somewhat similar to this
Results:
| id | employee | startdate | enddate | time |
|----|----------|-----------|---------|------|
| 8 | David | 8 | 22 | 17 |
The time column is the one you need.
I made a fiddle where you can see and test how it works, http://sqlfiddle.com/#!9/40a959/5
Related
I am a newbie to PHP and I am stuck at a certain point. I tried looking up a solution for it however, I didn't find exactly what I need.
My goal is to create a leaderboard, in which the values are displayed in descending order plus the rank and score are displayed. Furthermore, it should also display whether or not a tie is present.
The database should look like this:
+---------+------+----------------+-------+------+
| user_id | name | email | score | tied |
+---------+------+----------------+-------+------+
| 1 | SB | sb#gmail.com | 1 | 0 |
+---------+------+----------------+-------+------+
| 2 | AS | as#web.de | 2 | 0 |
+---------+------+----------------+-------+------+
| 3 | BR | br#yahoo.com | 5 | 1 |
+---------+------+----------------+-------+------+
| 4 | PJ | pj#gmail.com | 5 | 1 |
+---------+------+----------------+-------+------+
And the outputted table should look something like this:
+------+-------------+-------+------+
| rank | participant | score | tied |
+------+-------------+-------+------+
| 1 | BR | 5 | Yes |
+------+-------------+-------+------+
| 2 | PJ | 5 | Yes |
+------+-------------+-------+------+
| 3 | AS | 2 | No |
+------+-------------+-------+------+
| 4 | SB | 1 | No |
+------+-------------+-------+------+
I managed to display the rank, participant and the score in the right order. However, I can't bring the tied column to work in the way I want it to. It should change the value, whenever two rows (don't) have the same value.
The table is constructed by creating the <table> and the <thead> in usual html but the <tbody> is created by requiring a php file that creates the table content dynamically.
As one can see in the createTable code I tried to solve this problem by comparing the current row to the previous one. However, this approach only ended in me getting a syntax error. My thought on that would be that I cannot use a php variable in a SQL Query, moreover my knowledge doesn't exceed far enough to fix the problem myself. I didn't find a solution for that by researching as well.
My other concern with that approach would be that it doesn't check all values against all values. It only checks one to the previous one, so it doesn't compare the first one with the third one for example.
My question would be how I could accomplish the task with my approach or, if my approach was completely wrong, how I could come to a solution on another route.
index.php
<table class="table table-hover" id="test">
<thead>
<tr>
<th>Rank</th>
<th>Participant</th>
<th>Score</th>
<th>Tied</th>
</tr>
</thead>
<tbody>
<?php
require("./php/createTable.php");
?>
</tbody>
</table>
createTable.php
<?php
// Connection
$conn = new mysqli('localhost', 'root', '', 'ax');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL Query
$sql = "SELECT * FROM names ORDER BY score DESC";
$result = $conn->query("$sql");
// Initalizing of variables
$count = 1;
$previous = '';
while($row = mysqli_fetch_array($result)) {
$current = $row['score'];
$index = $result['user_id']
if ($current == $previous) {
$update = "UPDATE names SET tied=0 WHERE user_id=$index";
$conn->query($update);
}
$previous = $current;
?>
<tr>
<td>
<?php
echo $count;
$count++;
?>
</td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['score'];?></td>
<td>
<?php
if ($row['tied'] == 0) {
echo 'No';
} else{
echo 'Yes';
}
?>
</td>
</tr>
<?php
}
?>
I think the problem is here
$index = $result['user_id'];
it should be
$index = $row['user_id'];
after updating tied you should retrieve it again from database
So I solved my question by myself, by coming up with a different approach.
First of all I deleted this part:
$current = $row['score'];
$index = $result['user_id']
if ($current == $previous) {
$update = "UPDATE names SET tied=0 WHERE user_id=$index";
$conn->query($update);
}
$previous = $current;
and the previous variable.
My new approach saves the whole table in a new array, gets the duplicate values with the array_count_values() method, proceeds to get the keys with the array_keys() method and updates the database via a SQL Query.
This is the code for the changed part:
// SQL Query
$sql = "SELECT * FROM names ORDER BY score DESC";
$result = $conn->query("$sql");
$query = "SELECT * FROM names ORDER BY score DESC";
$sol = $conn->query("$query");
// initalizing of variables
$count = 1;
$data = array();
// inputs table into an array
while($rows = mysqli_fetch_array($sol)) {
$data[$rows['user_id']] = $rows['score'];
}
// -- Tied Column Sort --
// counts duplicates
$cnt_array = array_count_values($data);
// sets true (1) or false (0) in helper-array ($dup)
$dup = array();
foreach($cnt_array as $key=>$val){
if($val == 1){
$dup[$key] = 0;
}
else{
$dup[$key] = 1;
}
}
// gets keys of duplicates (array_keys()) and updates database accordingly ($update query)
foreach($dup as $key => $val){
if ($val == 1) {
$temp = array_keys($data, $key);
foreach($temp as $k => $v){
$update = "UPDATE names SET tied=1 WHERE user_id=$v";
$conn->query($update);
}
} else{
$temp = array_keys($data, $k);
foreach($temp as $k => $v){
$update = "UPDATE names SET tied=0 WHERE user_id=$v";
$conn->query($update);
}
}
}
Thank you all for answering and helping me get to the solution.
instead of the update code you've got use something simular
$query = "select score, count(*) as c from names group by score having c > 1";
then you will have the scores which have a tie, update the records with these scores and your done. Make sure to set tie to 0 at first for all rows and then run this solution
UPDATE for an even faster solution sql based:
First reset the database:
$update = "UPDATE names SET tied=0";
$conn->query($update);
All records have a tied = 0 value now. Next update all the records which have a tie
$update = "update docs set tied = 1 where score IN (
select score from docs
group by score having count(*) > 1)";
$conn->query($update);
All records with a tie now have tied = 1 as we select all scores which have two or more records and update all the records with those scores.
I have two tables and i want to echo the total call count once each user logins:
Login
Firstname | Lastname | Login ID
------------------------------
Tyler | Durden | 3
Call Count
Name | Call Count | Open | GrandTotal
------------------------------
Tyler Durden| 100 | 33 | 133
i tried:
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name=".$_SESSION['firstname']. ' ' .$_SESSION['lastname']." ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>
But its not working, i think i have to join the the two tables to get it to work. What do you think?
Assuming your Call Count table is actually called csvdata, you'll want to format your SQL request string a bit by adding single quotes around the WHERE name = part.
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name='".$_SESSION['firstname']. ' ' .$_SESSION['lastname']."' ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Call Count'].' Call Count';
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>
Good practice would require that you use primary keys to facilitate joins between tables and make sure two users with the same name can be differenciated.
In that case you may want to consider replacing the Name column in your Call Count table for your loginID. This way you could get your name from the Login table (as shown below). Also, as bad as it is to have duplicated data like your user's name in both tables, you do not need your GrandTotal column since you can easily get the sum of CallCount and Open to get the exact same number. In the end, your query should look more like this (assuming your tables are called Login and CallCount).
<?php
$result = mysqli_query($mysqli, "SELECT l.FirstName, l.LastName, cc.CallCount, cc.Open, (cc.CallCount + cc.Open) AS GrandTotal FROM Login AS l JOIN CallCount AS cc ON l.LoginID = cc.LoginID WHERE l.FirstName LIKE \"".$_SESSION['firstname']."\" AND l.LastName LIKE \"".$_SESSION['lastname']."\"");
// ...
?>
i'm just learning PHP, and i have a question
Let just say, i have MySQL table "A"
Name | Job
--------|---------
Jynx | 1
Micah | 4
Nancy | 3
Turah | 1
And another table "B"
JobId | JobName
-------|-----------
1 | Lawyer
2 | Architec
3 | Farmer
4 | Mage
5 | Warrior
So supposedly in php i want to draw table that showed the content of table "A", but instead of displaying number at the "Job" colomn, they each display Job names from Table "B".
What is the most efficient way to do that?
For now, i just thinking of using
$conn = My database connect setting
$sql = "SELECT * FROM tableA ORDER BY Name";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>". $row['Name'] ."</td><td>";
$sql2 = "SELECT * FROM tableB WHERE JobId=$row['Job']";
$result2 = $conn->query($sql2);
while($row2 = mysqli_fetch_assoc($result2)) {
echo "<td>". $row2['JobName'] ."</td></tr>;
}
}
But wouldn't it take a lot of calculating proccess if there is multiple similliar colomn with hundreed of rows?
Is there any more efficient way to do this?
Sorry for my bad english
Thank you for your attention.
A join is definitely the way to go here.
SELECT a.Name, b.JobName
FROM tableA a
JOIN tableB b on (a.Job = b.JobId)
ORDER BY a.Name
Well, it is not easy to learn about JOIN, no time for now, but i will get to learn it latter.
As for now, i just get the idea to just use ARRAY instead
So before i draw the main table, i assign the supportive table (Table B) into associative array
$sql = "SELECT * FROM tableB ORDER BY Id";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
$job[$row['JobId']] = $row['JobName'];
}
And at the main table
$sql = "SELECT * FROM tableA ORDER BY Name";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>". $row['Name'] ."</td><td>". $job[$row['Job']];
}
I would like to show the count value for the mysql result in html table.
For an example "district Name1" is the name of "district name" and "count-value1" shows the total post office count in "district name1".
My output must be like this,
------------------------
District | Post Offices
------------------------
Name1 | Count-Value1
Name2 | Count-Value2
Name3 | Count-Value3
Name4 | Count-Value4
... | ...
------------------------
Anyone can please help me to fix this..
This is my PHP code,
<?php
include('config.php');
$data_content= "";
$qry = "SELECT DISTINCT district_N,state_N FROM pincode_data WHERE state_N ='" . mysql_real_escape_string($_GET['st'])."' ORDER BY district_N ASC";
$result = mysql_query($qry);
while($row = mysql_fetch_array($result))
{
$dist_Value = $row['district_N'];
$state_Value = $row['state_N'];
$data_content.= "<tr><td><a href='pincity.php?dist=".$row['district_N']."'> ".$row['district_N']."</a></td><td>Count Value to be Displayed Here</td></tr>";
}
mysql_close();
?>
This is my HTML code,
<html>
<head>
</head>
<body>
<h1>Pincodes in <?php echo $state_Value; ?></h1>
<div>
<table>
<tr><td>District</td><td>Post Offices</td></tr>
<?php echo $data_content; ?>
</table>
</div>
</body>
</html>
SQL has syntax for counting elements of a group. If you want to count all occurrences of each value for X in a table, the general form is select X, count(X) from <table> GROUP BY X. This will group all equal values of X together, and give you a total count of them. For your particular case, try this:
$qry = "SELECT district_N,state_N, COUNT(district_N) cnt
FROM pincode_data WHERE state_N ='" . mysql_real_escape_string($_GET['st'])."'
GROUP BY district_N ORDER BY district_N ASC";
Also, it is good to see that you are escaping the parameters - but mysql_* is deprecated and will be removed in future versions of PHP. You are best off to use either mysqli_* or PDO. In either case, you should also look into prepared statements and parameter binding. It's good for your health.
I am displaying the complete record of the user in the My profile section, I am fetching all the rows , but the problem is within the rows I've got two fields as arrays, which are 'secondarySubject' and 'secondaryGrade' now I want the display to be something like this
2002-2004 ----------- A Level ------- School Name
Science A
Maths B
I am able to display them but it prints the dates, school name and level name with every subject rather than just once for all the subjects. I am posting my code, can someone pleaseeee help me with it.
$result2 = $db->query('
SELECT *
FROM secondaryEducation
WHERE userID = "'.$graduateID.'"
ORDER BY secondaryFinishDate DESC
');
$totalRows2 = mysql_num_rows($result2);
if($totalRows2 > 0)
{
$html .= '<h2>Secondary Education: '.$option.'</h2>';
while($row = mysql_fetch_assoc($result2))
{
$startYear = formatDate($row['secondaryStartDate'], 'Y');
$finishYear = formatDate($row['secondaryFinishDate'], 'Y');
if (!empty($row['secondaryGrade']))
$secondaryGrade = getSecondaryGradeName($row['secondaryGrade']);
else
$secondaryGrade = $row['secondaryGradeCustom'];
$html .= '
<div class="secondaryListing">
<div><strong>'.$startYear.' - '.$finishYear.' '.stripslashes($row['secondarySchool']).'</strong></div>
<div>'.stripslashes(getSecondaryLevelName($row['secondaryLevel'])).' in '.stripslashes(getSecondarySubjectName($row['secondarySubject'])).' - '.stripSlashes($secondaryGrade).'</div>
</div><!-- End education listing -->
';
}
}
It looks like those are inside the while statement. Every time it loops it will include it. Try moving it outside the while statement.