I am adding elements from my SQL query to an associative array and printing them as is shown below;
foreach ($db->query($sql) as $row)
{
?>
<p>
<?php
//Print details of each row
echo "Sale Date: " . $row['saleDate'] . "<br />" .
"Sale Price: " . $row['salePrice'] . "<br />" .
"Buyers Email: " . $row['userEmail'] . "<br />";
?>
</p>
i would like to be able to get the sum of salePrice for elements which match my SQL query.
i know i can use the SQL sum command to get the sum of my whole salePrice column in sql, but i would only like to see the sum of the elements which match my query. Is there a simple way to do this?
Thanks.
$summary = 0;
foreach ($db->query($sql) as $row) {
?>
<p>
<?php
//Print details of each row
echo "Sale Date: " . $row['saleDate'] . "<br />" .
"Sale Price: " . $row['salePrice'] . "<br />" .
"Buyers Email: " . $row['userEmail'] . "<br />";
$summary += $row['salePrice'];
?>
</p>
<?
}
echo 'Summary: '.$summary;
?>
$sum = 0;
foreach ($db->query($sql) as $row)
{
?>
<p>
<?php
$sum += floatval($row['salePrice']);
//Print details of each row
echo "Sale Date: " . $row['saleDate'] . "<br />" .
"Sale Price: " . $row['salePrice'] . "<br />" .
"Buyers Email: " . $row['userEmail'] . "<br />";
?>
</p>
Use this $sum variable for calculation
you can add that codition in sql query only and get sum(yourfield) in query only.
or else if you want to list all $row and sum the price of selected then
$sum = 0;
foreach ($db->query($sql) as $row)
{
?>
<p>
<?php
if()// your condition here
{
$sum += floatval($row['salePrice']);
}
//Print details of each row
echo "Sale Date: " . $row['saleDate'] . "<br />" .
"Sale Price: " . $row['salePrice'] . "<br />" .
"Buyers Email: " . $row['userEmail'] . "<br />";
?>
</p>
You can also do this simply in mysql (it may even be faster).
Assuming a data structure like this:
CREATE TABLE tbl_sales (
buyers_email VARCHAR(50), /* probably should make this foreign key of tbl_buyer */
sale_price DECIMAL(7,2),
sale_date TIMESTAMP
);
An $sql query like this will do:
SELECT SUM(sale_price) AS total_sale FROM tbl_sales;
Then in PHP:
$query = $dbh -> exec ($sql);
$query -> setFetchMode(PDO::FETCH_ASSOC);
$results = $query -> fetchAll();
$total = $results[0]["total_sale"];
I think you should use the right tool for the right Job .. since you are calling MySQL it already has a SUM function
SELECT SUM(salePrice) as total
That would get the Job done much faster
The simplest method by which to do this is to use the sql command.
SELECT SUM(salePrice) as sum
Then calling sum will give you the sum of salePrice for elements which match your associative array
Related
Hello all! This is my first question in stackoverflow so I hope I follow the rules good enough. :)
For my PHP class I have an exercise that makes it difficult for me: Text with about 4 variables in it, all are stored in arrays (one array for each variable, 3 values for each variable).
Position [0] of each array goes in the first echo text, position [1] of each array goes in the second text and so on.
How to echo the text 3 times using all values stored in the array? In the code I must use the main text only 1 time.
$u_name = array('student' => 'Joe','lecturer' => 'Kate', 'assistant' => 'Martin');
$course_name = array('PHP', 'CSS', 'HTML');
$role = array('student', 'lecturer', 'assistant');
echo "Hi," . $u_name['student'] . "! You've been approved to take part in course " . $course_name[0] . " as a " . $role[0] . ". The course " . $course_name[0] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['lecturer'] . "! You've been approved to take part in course " . $course_name[1] . " as a " . $role[1] . ". The course " . $course_name[1] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['assistant'] . "! You've been approved to take part in course " . $course_name[2] . " as a " . $role[2] . ". The course " . $course_name[2] . " will last for two days.";
This is what I did by myself, but as you see in the code I have 3 times the main text.
Thank you in advance.
Normally you go trough arrays with some type of a loop.
To name a few types of loops:
for
while
foreach
In this case the perfect fit is a foreach loop.
It simply goes through each element of the array, but because you have a associative array and two indexed array you also need a counter.
$counter = 0;
foreach($u_name as $key=>$value){
echo "Hi, " . $value . "! You've been approved to take part in course " . $course_name[$counter] . " as a " . $role[$counter] . ". The course " . $course_name[$counter] . " will last for two days.";
echo "<br>";
$counter++;
}
If still are any questions left, don't mind to ask.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I'm looping through some data to display on my page, and then insert each loop to a row in a database (personal learning exercise for PHP and MySQL).
The for loop runs 5 times (for example, sometimes it may loop more/less), and I am able to successfully insert the data for the first 4 loops, but am having difficulty figuring out why the last loop won't insert into the database.
All 5 loop iterations display on my page, I'm not quite sure why the last loop won't insert into the database.
Here is my for loop that includes the MySQL code:
$artworksIterations = 1
count($artworksTitle[$x]) = 5
for ($x = 0; $x < $artworksIterations; $x++) {
for ($y = 0; $y < count($artworksTitle[$x]); $y++) {
$savedartworksTitle = $artworksTitle[$x][$y];
echo "TITLE: " . $savedartworksTitle . "<br>";
$savedartworksArtist = $artworksArtist[$x][$y];
echo "ARTIST: " . $savedartworksArtist . "<br>";
$savedartworksYear = $artworksYear[$x][$y];
echo "YEAR: " . $savedartworksYear . "<br>";
$savedartworksMedium = $artworksMedium[$x][$y];
echo "MEDIUM: " . $savedartworksMedium . "<br>";
$implodeGene = implode(", ", $artworksGene[$x][$y]);
echo "GENRES: " . $implodeGene;
$savedartworksDisplay = $artworksDisplay[$x][$y];
echo "<br><img src='" . $savedartworksDisplay . "'><br>";
echo "<br>----<br>";
$sql = "INSERT INTO Artworks (title, artist, year, medium, display, genres) VALUES ('$savedartworksTitle', '$savedartworksArtist', '$savedartworksYear', '$savedartworksMedium', '$savedartworksDisplay', '$implodeGene');";
mysqli_query($conn, $sql);
} // end of y
} // end of x
Any help would be deeply appreciated. Thank you :)
Thank you to everyone who helped dissect my issue!
It turns out, by mere coincidence, the data from the last loop of each iteration contained an apostrophe ('), which was why they weren't inserted into the database (syntax error).
Thank you to Jacques for pointing out that I should be checking for errors, that is where it informed me of a syntax error (also, thank you for jeff who clued in on my apostrophe issue).
To fix this, I used the mysqli_real_escape_string() function save the data as a safe format for the database (probably something I should have done in the first place, learning experience!).
Updated working code:
for ($x = 0; $x < $artworksIterations; $x++) {
for ($y = 0; $y < count($artworksTitle[$x]); $y++) {
// display the information on the web page
echo "TITLE: " . $artworksTitle[$x][$y] . "<br>";
echo "ARTIST: " . $artworksArtist[$x][$y] . "<br>";
echo "YEAR: " . $artworksYear[$x][$y] . "<br>";
echo "MEDIUM: " . $artworksMedium[$x][$y] . "<br>";
echo "GENRES: " . implode(", ", $artworksGene[$x][$y]);
echo "<br><img src='" . $artworksDisplay[$x][$y] . "'><br>";
// save data to MySQL safe format
$savedartworksTitle = mysqli_real_escape_string($conn, $artworksTitle[$x][$y]);
$savedartworksArtist = mysqli_real_escape_string($conn, $artworksArtist[$x][$y]);
$savedartworksYear = mysqli_real_escape_string($conn, $artworksYear[$x][$y]);
$savedartworksMedium = mysqli_real_escape_string($conn, $artworksMedium[$x][$y]);
$savedartworksDisplay = mysqli_real_escape_string($conn, $artworksDisplay[$x][$y]);
$implodeGene = mysqli_real_escape_string($conn, implode(", ", $artworksGene[$x][$y]));
// insert data into database
$sql = "INSERT INTO Artworks (title, artist, year, medium, display, genres) VALUES ('$savedartworksTitle', '$savedartworksArtist', '$savedartworksYear', '$savedartworksMedium', '$savedartworksDisplay', '$implodeGene');";
if (mysqli_query($conn, $sql) === FALSE) {
printf("ERROR: %s\n", mysqli_error($conn));
}
echo "<br>----<br>";
} // end of y
} // end of x
I want to create an array with the help of MYSQL and display it the following way:
while ($array = mysqli_fetch_assoc($res))
{
echo $array["first_name"] . ", "
. $array["last_name"] . ", "
. $array["personal_id"] . ", "
. $array["salary"] . ", "
. $array["birthday"] . "<br />";
}
To improve usability, I only want to display 10 results, put a link to the next 10 results at the bottom and display these on another page.
How do I have to change the while-condition in order to only display the first 10 results of my result?
I tried searching for a solution but I couldn't find anything that fits my needs, so any help is appreciated!
Thanks in advance!
Check offset and limit conditions in mysql.
Example: to show 16 - 26 records from result query.
$sql = "SELECT * FROM Table LIMIT 10 OFFSET 15"
If what you want is just a way to break out of the loop after the first 10 results.
$counter = 1;
while (($array = mysqli_fetch_assoc($res)) || ($counter < 10))
{
echo $array["first_name"] . ", "
. $array["last_name"] . ", "
. $array["personal_id"] . ", "
. $array["salary"] . ", "
. $array["birthday"] . "<br />";
$counter++;
}
I am working on a "boxing records" database for a school project. The loop retrieves records from a SQL statement. I want to add a "VS" string of text between every other two lines in order to show records outputted somewhat like this.
Upcoming Fights
Sergey Kovalev (28-0-25)
VS
Jean Pascal (30-3-17)
Another Boxer (123-0-5)
VS
Some Boxer (123-3-1)
However, my current loop outputs like this
Sergey Kovalev (28-0-25)
VS
Jean Pascal (30-3-17)
VS
Another Boxer (123-3-1)
VS
Some Other Boxer (123-3-1)
VS
The loop I currently have is the following
foreach($records as $record) {
$i = 0;
echo $record['name'] . " (" . $record['wins'] . "-" . $record['losses'] . "-" . $record['kos'] . ")" . "<br>";
$i=$i*2;
if($i%2 == 0)
{
echo "VS <br/>";
}
else{
echo "<br />";
}
I know I could probably change the SQL in order to display two fighters in the same row, and then append "vs" on the echo, but I thought that just modifying the for loop would work by using a variable counter $i. I thought it would be pretty easy to make the "VS" appear between every two rows but im missing something in my logic.
You need to increment value of $i by one rather than multiplying it by 2 and initialize $i outside foreach loop.
$i = 0; // Initialize counter here
foreach($records as $record) {
echo $record['name'] . " (" . $record['wins'] . "-" . $record['losses'] . "-" . $record['kos'] . ")" . "<br>";
if($i%2 == 0)
{
echo "VS <br/>";
}
else
{
echo "<br />";
}
$i++; // Increment counter here
}
I am getting data from a my database. There is a admin panel also where people can add data to the database. The data gets on the page but some of the rows(<tr>) have less table data tags(<td>) than others. thus the table is not justified. Is there a way to add empty <td> to rows that need them? I have tried everything but i can't figure it out.
Picture on how the table looks at the moment:
The green numbers are the total sum of points but it's not clear because the table rows are jagged. How to fix tis?
If there is a jQuery solution that's also fine.
my code:
echo "<table class=\"zebra1\">";
echo "<th>N. </th>" . "<th>Team name: </th>" . "<th colspan=\"5\">Points: </th>" . "<th>Sum: </th>";
$numbering =1;
$query2 = $db->prepare("SELECT pisteet_1 As PIY, pisteet_2 as PIK, nimi As NIM, opisto As OPI, pisteet.kaupunki_id As KA FROM
pisteet INNER JOIN joukkueet ON joukkueet.id = pisteet.team_id INNER JOIN oppilaitokset ON oppilaitokset.opisto_id = joukkueet.opisto_id ORDER BY team_id ASC");
$query2->execute();
$results = $query2->fetchAll();
$tableD = array();
foreach ($results as $key) {
$tableD[$key['NIM']][] = array('PIY'=>$key['PIY'],'PIK'=>$key['PIK'],'KA'=>$key['KA'], 'OPI'=>$key['OPI']);
}
foreach($tableD as $teamN=>$values2){
//Echoing the Team name
echo "<tr class=\"all " . $values2[0]['KA'] . "\">";
echo "<td>" . $numbering . "</td>";
echo "<td>" . $teamN ."<span>" . $values2[0]['OPI'] ."</span></td>";
$sum1=0;
$sum2=0;
//Echoing the points
foreach($values2 as $v2){
echo "<td class=\"points\">" . $v2['PIY'] . "/" . $v2['PIK'] . "</td>";
$sum1 +=$v2['PIY'];
$sum2 +=$v2['PIK'];
}
//Echoing the total sum of points
echo '<td class="Sum">'.$sum1.'/'.$sum2."</td>";
echo "</tr>";
$numbering ++;
}
echo '</table>';
I have a variable named: $colspancalculated that has the longest row: at the moment it stores the value 5.
Assuming you have a fixed number of columns (I assume this because you've got a colspan on your table header cell), you need to output the td elements as you are doing, or output blank cells if the records don't exist.
Consider something like this instead of your foreach:
// Echoing the points - as you mention in your comment, you've calculated
// the maximum column size as $colspancalculated - so you that as your upper limit
for($i = 0; $i < $colspancalculated; $i++) {
if(!isset($values2[$i]['PIY'])) {
// This record doesn't exist! Output a blank cell
echo '<td></td>';
continue;
}
// Otherwise, output the cell and do your calculations
echo '<td class="points">' . $values2[$i]['PIY'] . '/' . $values2[$i]['PIK'] . '</td>';
$sum1 += $values2[$i]['PIY'];
$sum2 += $values2[$i]['PIK'];
}
Instead of a foreach loop, use a for loop -- or, since you have to work with an iterator, anyway, just do:
$i = $numberOfColumnsLeftAtThisPointInYourScript
foreach($values2 as $v2){
echo "<td class=\"points\">" . $v2['PIY'] . "/" . $v2['PIK'] . "</td>";
$sum1 +=$v2['PIY'];
$sum2 +=$v2['PIK'];
$i--;
}
while($i > 0){
echo '<td> </td>';
$i--;
}