I have a dog show website and attempting to display the top five kennel affixes with the most point gained over a year.
I have split up the point as seen in code and using an inner join on two tables. One being Results and the Other Dogs
I am having a problem showing the affix name with its points gained next to it. Also can not get the top five based on most points
Warning: A non-numeric value encountered in xxx on line 59
Notice: Undefined variable: total in xxx on line 68
This below is all that shows up and I think it is adding the if statements up.
3
6
Sorry not that great at and need some help.
<?php
$query = "SELECT result.placement, result.award, result.class_name, dogs.affix
FROM result
INNER JOIN dogs
ON result.resultID = dogs.dog_id
ORDER BY dogs.affix LIMIT 5";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
$affix = $row['affix'];
$placement = $row['placement'];
$award = $row['award'];
if($award === 'BCC'){
$points = $affix + 5;
}
if($award === 'DCC'){
$points = $affix + 5;
}
if($award === 'RBCC'){
$points = $affix + 4;
}
if($award === 'RDCC'){
$points = $affix + 4;
}
if($placement === '1st'){
$points = $affix + 3;
}
if($placement === '2nd'){
$points = $affix + 2;
}
if($placement === '3rd'){
$points = $affix + 1;
}
$total += $points;
echo "<li> {$affix} {$total}</li>";
}
?>
Three problems.
ORDER BY dogs.affix LIMIT 5 returns bottom 5 not top. It should be ORDER BY dogs.affix DESC LIMIT 5 to get the top.
affix returns either null or an emprty string and that's why you are getting the first error. Define this field as int not null default 0 in your database.
$total is not initialized. Assign it to 0 before the loop
Related
i want to show Random Item with Select by WHERE code = $Code
But if he finds like 10 Items, i want to show only 1 by 1. All 10 must show in a Row, Random Order with a 5 seconds timer. The Problem is, i dont will show the same Item again and again. If the 10 Items are done, he must look again to database and start again
I already tried to do it with putting all in array but my skills are low :(
Thats my try...
$result = $db->query( 'SELECT * FROM ads WHERE zipcode = "'.$zipcode.'";');
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
$count = mysqli_num_rows($result);
for($i = 0; $i < $count; $i++) {
$random = rand(0, $count);
$count -= 1;
$result[] = $data[$random];
echo json_encode($data);
unset($data[$random]);
}
I have a variable in PHP where values from a database are inserted. It’s about money. I need to summarize all negative and positives values separately.
Example:
February, I have:
+ 10
− 10
+100
− 50
− 15
+ 70
+ 80
—
Credits added: 260 Euro
Credits paid: −75 Euro
The variable is named $amound in my PHP file. I really have no clue how to do that.
In Excel, this would be as follows: =SUMMEWENN(E1:E48;"<0")
But here I only have a variable, not fields.
Heres some Code:
$reportdata["tableheadings"] = array("Transaktions-ID","Kunde","Datum","Beschreibung","Betrag");
if ($startdate && $enddate) {
$query = "SELECT tblcredit.*,tblclients.firstname,tblclients.lastname FROM tblcredit INNER JOIN tblclients ON tblclients.id=tblcredit.clientid WHERE tblcredit.date BETWEEN '".db_make_safe_human_date($startdate)."' AND '".db_make_safe_human_date($enddate)."'";
$result = full_query($query);
while ($data = mysql_fetch_array($result)) {
$id = $data["id"];
$userid = $data["clientid"];
$clientname = $data["firstname"]." ".$data["lastname"];
$date = fromMySQLDate($data["date"]);
$description = $data["description"];
$amount = $data["amount"];
$currency = getCurrency($userid);
$amount = formatCurrency($amount);
$overallamount += $amount;
// $overallamountout -= $amount;
// $overallamountin += $overallamount > 0;
$reportdata["tablevalues"][] = array($id,''.$clientname.'',$date,nl2br($description),$amount);
}
Indeed, this is very simple (I assume that all of your variables are strings, e.g. coming from a text file, but even if not it will work):
$var1 = '+80';
$var2 = '-30';
$result = (int)$var1 + (int)$var2;
var_dump($result);
Will result in: "int(50)" => Working fine.
You can do it in the DB
SELECT SUM(numbers) AS sum1 FROM pepa WHERE numbers > 0;
SELECT SUM(numbers) AS sum2 FROM pepa WHERE numbers < 0;
Okay,
its done.
Heres the Code which was used:
$summeGesamt = 0;
$summeEingezahlt = 0;
$summeAusgezahlt = 0;
$summeGesamt = $summeGesamt + $data["amount"];
if ( $data["amount"] >= 0) {
$summeEingezahlt += $data["amount"];
} else {
$summeAusgezahlt += $data["amount"];
}
I have a news table in MySQL Database I query the table and show the title of the news in one PHP pages but now the table getting bigger so I want to divide the results into pages I mean to show each 50 news title in one page (pagenation).
I use this query to bring the news :
SELECT news.*, categories.category, users.username
FROM news INNER JOIN
users on news.user_id = users.id INNER JOIN
categories on categories.id = news.category_id
order by news.timestamp DESC
limit $min,$max
and this is part of the PHP page (How I calculate the max and min)
$news_per_page = 50;
if(!empty($_GET['p_n']))
{
$p_n = $_GET['p_n'];
$max = $news_per_page*$p_n;
$min = ($max - $news_per_page);
}
else
{
$p_n = 1;
$max = 50;
$min = 0;
}
$news = all_news($max,$min);
The sql giving me wrong result when i pass the limits I do not know why. Is it wrong to specify the max and min of sql query by this way?? Should I correct something in this code?
The LIMIT clause, as explained in the docs, takes arguments offset and count. So if you want to get, for example, results from 201 to 250, you would use LIMIT 200, 50. Start by renaming your variables $min and $max to $offset and $count, and from there everything will fall into place.
Pseudocode:
offset = (requestedPageNumber - 1) * rowsPerPage;
count = rowsPerPage;
PHP Code:
(assuming page number is 0-based)
$rowsPerPage = 50;
$page = empty($_GET['p_n']) ? 0 : $_GET['p_n'];
$offset = $rowsPerPage * (int) $page;
$news = all_news($offset, $rowsPerPage);
If you've got problems handling pagination properly, I suggest you use some code that is working, for example a pagination class that takes three parameters:
The current page.
The total count.
The number of items per page.
And then that class will generate the LIMIT clause for you. Example:
$pageNumber = 1;
$totalCount = 17;
$perPage = 5;
$pagination = new LimitPagination($pageNumber, $totalCount, $perPage);
echo $pagination, "\n";
This would output
LIMIT 0, 5
because you'er on the first page. Such a class then could also filter out those problems you have here, for example setting to a negative page - just automatically. And also it can provide a lot of extra data, like the next and previous page, the current page, the number of total pages, if it is the first or the last page and what not:
$pagination->setPage(-2);
echo $pagination, "\n";
echo "Current: ", $pagination->getPage(),
"; Total: ", $pagination->getTotalPages(),
"; Previous: ", $pagination->getPreviousPage(),
"; Next: ", $pagination->getNextPage(),
"\n";
Output:
LIMIT 0, 5
Current: 1; Total: 4; Previous: 1; Next: 2
This is then easy to integrate with different code, including yours:
$pagination = new LimitPagination($_GET['p_n'], $totalCount, 50);
$limit = sprintf("%d, %d", $pagination->getOffset(), $pagination->getCount());
This should easily do it. Class is here as Gist: https://gist.github.com/4469154
You need to set start (this you can achieve by using current page and per page property) and the second information is how many results you want (again per page property).
LIMIT . ($p_n - 1) * $news_per_page .', ' . $news_per_page
So, in your script it will be:
if(!empty($_GET['p_n']))
{
// You need to protect your variables for SQL injection. For numbers (int) or integer() function it is enough.
$p_n = (int) $_GET['p_n'];
$max = (int) $news_per_page;
$min = (int) ($p_n - 1) * $news_per_page;
}
else
{
$p_n = 1;
$max = 50;
$min = 0;
}
The correct code is:
$news_per_page = 50;
if(!empty($_GET['p_n']))
{
$p_n = intval($_GET['p_n']);
$min = ($p_n-1) * $news_per_page;
$max = $news_per_page;
}
else
{
$p_n = 1;
$max = 50;
$min = 0;
}
$news = all_news($max,$min);
While $_GET['p_n'] is page_number you dont' need to make any multiplies
I have the following code which provides the profit results of my rows depending on what Resultat_ID is set to.
$result = mysql_query('SELECT Indsats, Odds, Resultat_ID, Kamp FROM spil');
$row = mysql_fetch_assoc($result);
echo " Gevinster: ";
$Indsats = $row['Indsats'];
$Odds = str_replace(",", ".", $row['Odds']);
$sum = 0;
while($row = mysql_fetch_array( $result ))
{
$Indsats = $row['Indsats'];
$Odds = str_replace(",", ".", $row['Odds']);
if ($row['Resultat_ID'] == 1) //Win
{
$sum += $Indsats * ($Odds-1);
}
elseif ($row['Resultat_ID'] == 2) //Loss
{
$sum += $Indsats * -1;
}
elseif ($row['Resultat_ID'] == 3) //HalfWin
{
$sum += $Indsats * ($Odds-1) * 0.5;
}
elseif ($row['Resultat_ID'] == 4) //HalfLoose
{
$sum += $Indsats * -0.5;
}
}
echo $sum;
I also have a column called Tipper_ID which contains a number for each tipper and a table that contains Tipper_ID and Tipper_Name.
Besides the total profit results above, I want to get the profit results for each tipper, so basically run the above section for "all" and for each Tipper_Name in the Tipper-table and get the profit results for each part.
How do I do that ?
Danish/English Translations:
Gevinster = Gains<br>
Indsats = Effort<br>
Odds = Odds<br>
Resultat = Results<br>
Kamp = Match/Game<br>
Spil = Games<br>
Tipper = Tips
You have 2 options:
Inside your while, perform another query for each result (depending on the number of results, performance can be not that good)
Create a VIEW with the results grouped by Tipper_Name (or whatever you need) and change your query adding an INNER JOIN using the VIEW you just created. Even if this solution is a little bit more complex, it's faster!
This actually looks like a classic SQL problem:
SELECT t.TIPPER_ID, t.TIPPER_NAME,
SUM(CASE(s.Resultat_ID WHEN 1 THEN Indsats*(Odds-1) ELSE 0 END)) AS Win,
SUM(CASE(s.Resultat_ID WHEN 2 THEN Indsats*(-1) ELSE 0 END)) AS Loss,
SUM(CASE(s.Resultat_ID WHEN 3 THEN Indsats*(Odds-1)*(0.5) ELSE 0 END)) AS HalfWin,
SUM(CASE(s.Resultat_ID WHEN 4 THEN Indsats*(-0.5) ELSE 0 END)) AS HalfLoss
FROM spil AS s
LEFT JOIN TIPPERS AS t ON t.TIPPER_ID=s.TIPPER_ID
GROUP BY s.TIPPER_ID
For the total you should simply add those in the php.
Ok so iv got this code which is suppose to bring back all my results from my database and display 5 results per page. At the moment I have 12 results in my database and it is only showing 10, it wont show the 3rd page as there isnt 5 results to display. Here is my code
//$_GET['page'] is to get the current page opened
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$results_per_page = "5"; //number of results I want displayed per page
$start_from = ($page-1) * $results_per_page;
$query = "SELECT * FROM items WHERE subcat = '$conditions' LIMIT $start_from, $results_per_page";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
while ($row_condition=mysql_fetch_array($result)) {
//Display the results here
}
//Count number of results from database and work out how
//many pages I need to display all the results.
$result1 = mysql_query("SELECT * FROM items WHERE subcat = '$conditions'");
$num_rows = mysql_num_rows($result1);
$num_pages = $num_rows / $results_per_page;
if ($num_rows > $results_per_page){
?>
<div id="pagenum">
<?php
//This creates and displays the page numbers for the user to select
foreach( range( 1, $num_pages) as $i) {
if ($thepage == $i){
echo '<b>' . $i . '</b>';
}else{
echo '' . $i . '';
}
//This places a line between each number of pages
if ($i == $num_pages){
}else{
echo " | ";
}
}
?>
</div>
<?php
}else{ echo "Test";}
?>
So can anyone see a problem with this?, so I have 12 entries in my database. However im only getting 2 pages, 5 on each page and im not getting the 3rd page as there are only 2 results left and it seems to want 5 to finish it.
Thanks
You need to use ceil function:
$num_pages = ceil($num_rows / $results_per_page);
I think your biggest problem is that PHP will make give you a float when you divide two numbers that don't result in a whole one.
$one = 12;
$two = 5;
$result = $one / $two; // That will result in 2.4
Now, the issue is you, technically, have three pages, but PHP will NOT treat the .4 pages as a page, so when you loop through it will technically only do it twice. Since your using range and it's 2.4, it seems like PHP is rounding down. I would suggest something like this:
$result1 = mysql_query("SELECT * FROM items WHERE subcat = '$conditions'");
$num_rows = mysql_num_rows($result1);
$num_pages = ceil($num_rows / $results_per_page);
if ($num_rows > $results_per_page){
for($i = 0; $i < $num_pages; $i++) {
ceil() will force that division to round up every time, which will always give you that extra page.
Give it a shot! Let me know if it fixes your issue!