Multiply a databasevalue with a result of a loop - php

Ive currently got this code where I have two loops: one which displays all my ToDos and one which counts the amount of hours ive worked on a certain ToDo.
What I want to do is to multiply the ['pris'] (cost pr hour) with the amount of hours ['timer'] from the loop.
echo "<div id='innhold'>";
$db = kobleTil();
$sql = "SELECT * FROM oppdrag";
$resultat = $db->query($sql);
while($nesteRad = $resultat->fetch_assoc()) {
echo "<hr />";
echo "<table id='resultat'>";
echo "<tr><th colspan='7'>" . $nesteRad['navn'] . "</th></tr>";
echo "<tr><td><b>Type</b></td><td><b>Startdato</b></td><td><b>Sluttdato</b></td><td><b>Pris pr. time</b></td><td><b>Aktiv</b></td></tr>";
echo "<tr>";
echo "<td>" . $nesteRad['type'] . "</td>";
echo "<td>" . $nesteRad['startDato'] . "</td>";
echo "<td>" . $nesteRad['sluttDato'] . "</td>";
echo "<td>" . $nesteRad['pris'] . "</td>";
echo "<td>" . $nesteRad['aktiv'] . "</td>";
echo '<td>Se på</td>';
echo '<td>Legg til timer</td>';
echo '<td>Slett</td>';
echo "</tr></table>";
echo "<hr />";
$prisx = $nesteRad['pris'];
}
echo "<a href='lioppdrag.php'><h5>Legg inn nytt oppdrag</h5></a>";
echo "<br />";
echo "<h3>Statistikk - Oppgaver arbeidet mest med<br /></h3>";
$statistikk = "SELECT oppdrag.*, (SELECT SUM(timer) FROM timeregistrering WHERE timeregistrering.oppdrID = oppdrag.oppdrID) AS Timer FROM oppdrag ORDER BY Timer DESC";
$print = $db->query($statistikk);
while($rad = $print->fetch_assoc()) {
$timer = $rad['Timer'] . '00px';
echo "<b>Oppdrag: " . $rad['navn'] ." Antal timer: " . $rad['Timer'] . " </b><br/>";
echo "<img src='firkant.png' id='firkant' width='"; echo $timer; echo "'></img><br/><br/>";
$timerx = $rad['Timer'];
}
echo "</div>";
} else {
echo "<div id='innhold'>";
echo "<a href='index.php'>Logg inn for å se innholdet</a>";
echo "</div>";
}
?>

I'll try to set you in the right direction but without the exact tables I can't give you the exact answer. first I'd do this in SQL before you ever get to PHOP and loops. Think in terms of set's not loops, so group your todo's and sum(timer) for each group. Then you can do another column with the sum(timer)*pris calling it Total. Psuedocode would be something like
select ToDo.Name, sum(working.timer), sum(timer)*ToDo.Pris as Total
from ToDo join working on todo.id = working.todo_id
group by ToDo.Name
(and a where clause to restrict the dates worked probably unless you just want everything)
edit: sorry I'm not sure why the code didn't show up when I first looked at the question and I only saw it after I answered but I still think this might help so take a look and let me know

Related

PHP script stops // looping through table

I have a very simple script looping through a MySQL-Table (3500 records) and returning the result in an HTML-Table.
The scripts ends suddenly (after 500) without error and without reaching the end of the table.
Any ideas whats wrong? Many thanks for comments.
Cheers
Tim
echo "<h1>This is PHP version " . phpversion() . "</h1>"; // returns 7.1.10
error_reporting(E_ALL);
ini_set('display_errors', 'on');
echo "<h3>Script Runtime: ". ini_get('max_execution_time') ." Sec.</h3>"; // returns 300
echo "<h3>Memory Limit: ". ini_get('memory_limit') ."</h3>"; // retuns 100M
$i = 0;
$sql = "SELECT * FROM tblClients ORDER BY lastname, firstname";
if (! $recClients = mysqli_query($GLOBALS['conn'], $sql)) {die("<p><b>SQL:</b><br>".$sql."</p>");}
echo "<table>";
echo "<tr>";
echo "<th>Nr.</th>";
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "</tr>";
while ($rowClients = mysqli_fetch_assoc($recClients)) {
echo "<tr>";
echo "<td>" . $i++ . "</td>";
echo "<td>" . $rowClients['firstname'] . "</td>";
echo "<td>" . $rowClients['lastname'] . "</td>";
echo "</tr>";
}
echo "</table>";

displaying the year of module without duplicates? [duplicate]

I'm creating a display for a student module webpage that displays in this format
2001/02
Computer Science
Biology
Lorem Ipsum
2002/03
Subject
Subject
Subject
In that style
The data base I'm using contains information such as
year(2001/02)
credit(10)
mods.mid(CS500)
mtitle(module title - software engineering, biology, chemistry...etc)
the PHP code I have displays every module title, so literally I giant list of modules whereas I want to split it out like up there described, Years displayed THEN every module for that year. Any one people help me? Code down below:
<?php
echo "<table cellspacing='40'>";
$query2 ="SELECT mods.mid, ayr, mtitle, credits FROM stud, smod, mods WHERE stud.sid = '".$_POST['stuNo']."' and stud.sid = smod.sid and smod.mid = mods.mid order by ayr ASC";
$result = mysql_query($query2) or die(mysql_error());
echo "Enrolment and progress";
echo "<table width='150' border='1'>";
echo "<th> Module Selection</th>";
echo"<td>".$row["ayr"]."</td>";
while ($row = mysql_fetch_array($result))
{
$temp_year=$row["ayr"];
echo "<tr>";
if ($temp_year!=$row["ayr"]){
echo "<td>" . $row["ayr"] . "</td>";
}
echo "<td>" . $row["mid"] . "</td>";
echo "<td>" . $row["mtitle"] . "</td>";
echo "<td>" . $row["credits"] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
I wouldn't know how to seperate it by year, any help is great. thank you.
I would probably code it like this, probably not the only way but should work based on what I believe you are trying to achieve. Please make sure to add the "order by" to your SQL query as well.
echo "<table cellspacing='40'>";
$query2 = "SELECT mods.mid, ayr, mtitle, credits FROM stud, smod, mods WHERE stud.sid = '".$_POST['stuNo']."' and stud.sid = smod.sid and smod.mid = mods.mid ORDER BY ayr DESC";
$result = mysql_query($query2) or die(mysql_error());
echo "Enrollment and Progress";
echo "<table width='150' border='1'>";
echo "<tr><td colspan="3"><b>Module Selection</b></td></tr>";
$year = "";
while ($row = mysql_fetch_array($result)) {
if ($year != $row["ayr"]) {
echo "<tr><td colspan="3"><b>" . $row["ayr"] . "</b></td></tr>";
$year = $row["ayr"];
}
echo "<tr>";
echo "<td>" . $row["mid"] . "</td>";
echo "<td>" . $row["mtitle"] . "</td>";
echo "<td>" . $row["credits"] . "</td>";
echo "<tr>";
}
echo "</table>";

Select 2 tables in one php select statement

I have two tables in mysql
practice_sheets and parent_pin
And I want to use one select statement and get data from both tables.
I have tried
$result = mysqli_query($con,"SELECT * FROM practice_sheets AND parent_pin
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
and also:
$result = mysqli_query($con,"SELECT * FROM practice_sheets, parent_pin
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
I've never tried to do this before and the previous solutions are what I found searching.
Update
I think it would help if I included my full code. the table data is going into a table on my page. the student_name field from the practice_sheets and parents_student from parent_pin will be matched.
<?php
$con=mysqli_connect();
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM practice_sheets
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
$numrows = mysqli_num_rows($result);
if($numrows == 0) {
echo "<div class='alert alert-danger'>";
echo "No Entries, See your instructor for details.";
echo "</div>";
} else {
echo "<table class='mws-table table-striped table-hover'>";
echo "<thead align='center'>";
echo "<tr>";
echo "<th>Sheet Number</th>";
echo "<th>Total Minutes</th>";
echo "<th>Due Date</th>";
echo "<th>PIN</th>";
echo "<th>View</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody align='center'>";
while($row = mysqli_fetch_array($result)){
if ($row["total_min"]>=$row["required_min"]) {
echo "<tr class='success'>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['total_min'] . "</td>";
echo "<td>" . $row['due_date'] . "</td>";
echo "<td>" . $row['parent_pin'] . "</td>";
echo "<td> <a href='account/practiceSheets?id=" . $row["id"] . "&total_min=" . $row["total_min"] ."&due_date=" . $row["due_date"] ."&mon_min=" . $row["mon_min"] ."&tues_min=" . $row["tues_min"] ."&wed_min=" . $row["wed_min"] ."&thurs_min=" . $row["thurs_min"] ."&fri_min=" . $row["fri_min"] ."&sat_min=" . $row["sat_min"] ."&sun_min=" . $row["sun_min"] ."&name=" . $row["student_name"] ."&assignment=" . $row["assignment"] ."&required_min=" . $row["required_min"] ."'> <i class='icon-eye-open'> </i> </a> </td>";
echo "</tr>";
} else {
echo "<tr class='info'>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['total_min'] . "</td>";
echo "<td>" . $row['due_date'] . "</td>";
echo "<td>" . $row['parent_pin'] . "</td>";
echo "<td> <a href='account/practiceSheets?id=" . $row["id"] . "&total_min=" . $row["total_min"] ."&due_date=" . $row["due_date"] ."&mon_min=" . $row["mon_min"] ."&tues_min=" . $row["tues_min"] ."&wed_min=" . $row["wed_min"] ."&thurs_min=" . $row["thurs_min"] ."&fri_min=" . $row["fri_min"] ."&sat_min=" . $row["sat_min"] ."&sun_min=" . $row["sun_min"] ."&name=" . $row["student_name"] ."&assignment=" . $row["assignment"] ."&required_min=" . $row["required_min"] ."'> <i class='icon-eye-open'> </i> </a> </td>";
echo "</tr>";
}
}
echo "</tbody>";
echo "</table>";
mysqli_close($con);
}
?>
$result = mysqli_query($con,"SELECT *
FROM practice_sheets, parent_pin
WHERE student_name = parents_student
AND student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
Use explicit names for WHERE statament, e.g.
$result = mysqli_query("SELECT student_name.practice_sheets FROM practice_sheets AND parent_pin WHERE student_name.practice_sheets = '{$_SESSION['SESS_FIRST_NAME']} {$_SESSION['SESS_LAST_NAME']}'");
MySQL will not AFAIK automatically check where the constraints are and rightly so considering that you may have conflicting names. Note that this is still pseudo code and you will need to change the fetched results accordingly. Usually it is considered to be good practice to also define explicitly the columns you wish to fetch, but otherwise you can use JOIN as well.
And to help writing shorter code, you can also use shorthands for the table names, e.g.
$result = mysqli_query("SELECT student_name.ps AS name, pin.pp AS pin FROM practice_sheets AS ps, parent_pin AS pp WHERE student_name.ps = '{$_SESSION['SESS_FIRST_NAME']} {$_SESSION['SESS_LAST_NAME']}'");
Update
You also have in your updated version an issue. You call mysqli_fetch_array, which returns an ordered (i.e. numbered) array. If you wish to use keyed, use mysqli_fetch_assoc.
And you are closing the MySQL connection at the moment only if the query was successful. Move mysqli_close outside of the brackets.

Filtering mysql results via select dropdown

I'm a new member of StackOverflow, and although I've been using the website for a long time, it's my first time posting a question, in a hope that someone will be able to help me. I'll start by saying that my knowledge of PHP and MySQL is basic, but what I'm trying to do isn't too complex in my opinion, so hopefully I won't be asking for much. I've done a lot of prior research, but I just couldn't find the right answer.
In short, this is what I'm trying to do:
I've got an html form, which upon submission writes data to a database, and then publishes a table on a separate html page. With each successful submission a new table gets generated and published, while the old one gets pushed underneath. This all works fine, and I've also implemented pagination so that only 5 tables are visible per page.
What I'd like to be able to do is allow people to ONLY view/display results (tables) based on a specific criteria, in this case "rating", by selecting a rating from a drop-down on the page where tables are published. Rating is one of the fields in my form which gets submitted to a database and then published in one of the rows in a table.
Below is the code which publishes tables. Thanks in advance for your help!
<?php
include('dbconnect.php');
mysql_select_db("vtracker", $con);
$result = mysql_query("SELECT * FROM userdata");
$age = "Age:";
$rating = "Rating:";
$country = "From:";
$name = "Name:";
while($row = mysql_fetch_array($result))
{
echo "<table id='mft_table' cellspacing='0'>";
echo "<tbody>";
echo "<tr>";
echo "<td class='row1'>" .$name . " " . $row['personsname'] . "</td>";
echo "<td rowspan='4'>";
echo "<div class='mft_column'>" . $row['mft'] . "</div>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row2'>" . $country . " " . $row['nationality'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row3'>" . $age . " " . $row['personsage'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row4'>" . $rating . " " . $row['rating'] . "</td>";
echo "</tr>";
echo "</tbody>";
echo "<br>";
echo "</table>";
}
?>
for both true and false use can add thid in your code:
if($_POST['rating_dropdown']!='')
{
$temp_rating = $_POST['rating_dropdown'];
$query=mysql_query("SELECT * FROM userdata WHERE rating = '$temp_rating'");
}
else
{
$query=mysql_query("SELECT * FROM userdata");
}
Dunno if this works, it's just a hinch. haha.
It will see if the rating is true(not null), if it's true it will echo the results.
while($row = mysql_fetch_array($result))
{
if ($rating)
echo "<table id='mft_table' cellspacing='0'>";
echo "<tbody>";
echo "<tr>";
echo "<td class='row1'>" .$name . " " . $row['personsname'] . "</td>";
echo "<td rowspan='4'>";
echo "<div class='mft_column'>" . $row['mft'] . "</div>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row2'>" . $country . " " . $row['nationality'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row3'>" . $age . " " . $row['personsage'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row4'>" . $rating . " " . $row['rating'] . "</td>";
echo "</tr>";
echo "</tbody>";
echo "<br>";
echo "</table>";
}
}
Once the dropdown gets selected and posted to your display page, use this code:
$temp_rating = $_POST['rating_dropdown'];
mysql_query("SELECT * FROM userdata WHERE rating = '$temp_rating'");
Keep in mind, however, that you should be using PDO or mysqli extension, not the mysql extension. According to PHP's website:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information.

Require help validating data inside MySQL

I currently have 2 different sections for this program, the first half takes the users input from a web page and then transfers it over onto a PHP side which will access MySQL and display the requested information.
Example: If I enter AX12 for the ID it will display information for that ID which does infact exist, but if I enter AX13 (which doesn't) it will display blank information, so I'm wondering if someone can show me how I can validate this once the information has been transferred over onto the PHP side. So if it detects that the information you've submitted does not exist simply display a message saying "ID DOES NOT EXIST" or something along those lines.
Here's the code for the PHP side if you need it for more information.
<?php
$part_number = $_GET['txtInput'];
$part_description;
$units_on_hand;
$item_class;
$warehouse_number;
$unit_price;
$query;
$result_set;
$connection;
$record;
echo "<html>";
echo "<head>";
echo "<title>SQL Application</title>";
echo "<style type = 'text/css'>body{text-align: center; background-color: #CC3333; color: #660000; font-size: 30;}</style>";
echo "</head>";
echo "<body>";
echo "<center><h1>SQL Application</h1></center>";
echo "<br />";
echo "<br />";
echo "<br />";
$connection = #mysql_connect("localhost","m_stanicic","")
or die ("\n\n PROBLEM CONNECTING TO DATABASE! \n" . mysql_error() . "\n\n");
mysql_select_db("m_stanicicdb");
$query = "select * from part where part_number = '" . $part_number . "'";
$result_set = mysql_query($query)
or die ("\n\n PROBLEM WITH QUERY! . \n" . mysql_error() . "\n\n");
$record = mysql_fetch_assoc($result_set);
if($part_number == "")
{
//
}
else
{
$part_description = $record['part_description'];
$units_on_hand = $record['units_on_hand'];
$item_class = $record['item_class'];
$warehouse_number = $record['warehouse_number'];
$unit_price = $record['unit_price'];
echo "<center>";
echo "<table border='1' width=400 style ='table-layout:fixed' cellpadding='5' cellspacing='0'>";
echo "<col width = 200>";
echo "<col width = 200>";
echo "<tr>";
echo "<th colspan='2'>DETAILS OF THE PART YOU REQUESTED</th>";
echo "</tr>";
echo "<tr>";
echo "<td>part_description</td>";
echo "<td>" . $part_description . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>units_on_hand</td>";
echo "<td>" . $units_on_hand . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>item_class</td>";
echo "<td>" . $item_class . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>warehouse_number</td>";
echo "<td>" . $warehouse_number . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>unit_price</td>";
echo "<td>$" . $unit_price . "</td>";
echo "</tr>";
echo "</table>";
echo "</center>";
mysql_close($connection);
}
echo "<br />";
echo "<br />";
echo "<br />";
echo "<input type = 'button' value = 'RETURN' style = 'width: 75px; height: 75px;' onclick = \"javascript:window.location.href = 'jdpset1_4.html'\">";
echo "</body>";
echo "</html>";
You aren't validating anywhere that the result did return any data at all. Right after your call to mysql_query(), you should use mysql_num_rows() to see how many rows were returned by your query -- if mysql_num_rows($result_set) is zero, your query returned no data.
Notice how $part_number is never modified by mysql_query(), mysql_fetch_array() or any of those functions; so it will never be empty unless it started as such (rendering your current if almost useless).
You can check the output of your query $record...
if (count($record)==0) {
echo "the ID you entered does not exist! Try again...";
} else {
// code to output the part's details...
}
put the if (count... part instead of ...
if($part_number == "")
from your code i notice 2 things
$query = "select * from part where part_number = '" . $part_number . "'";
as your part number is a string, i recommend you to use LIKE not =
$query = "select * from part where part_number LIKE '" . $part_number . "'";
another is inspect your record is returning in multidimensional array like
$record = Array([0]=>array('part_description'=>A123...)).
then you must assign like so
$part_description = $record[0]['part_description'];
i hope it helps you

Categories