Couldn't get the total amount of each row - php

I was having difficulty trying to get the total amount of each row with this code:
Total Sales for this day:
<b>Php <?php
function formatMoney ($number, $fractional=false) {
if ($fractional) {
$number = sprintf('%.2f', $number);
}
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number) {
$number = $replaced;
}
else {
break;
}
}
return $number;
} // formatMoney
$result1 = mysql_query("SELECT sum(sales) FROM sales where date='$startDate'");
while($row = mysql_fetch_array($result1)) {
$rrr=$row['sum(sales)'];
echo formatMoney($rrr, true);
}
?>
But once I manually inserted the data straight to the database it appears to be working. It’s just that whenever I tried to add a data through the system, the values isn't showing at all.
Apart from it, I’m also having issue with how to refresh a column if the one next to it has placed a value that is connected to it.
Any idea? I’m getting stuck with this one.
Additional Information:
Here's the actual table.
No. of Remaining Property No. of Rented Property Rent Cost Amt. Tendered
1 1 1000 1000
1 1200
If there's a value placed in No. of Rented Property [example 1], the other column beside it No. of Remaining Property, must be refreshed and should display 0. Then the value for the Amount tendered must be=No. of Rented Property x Rent Cost.
You see the first row has values in it. And its working since I do a manual insert on the database. But The second row shows only the value for No. of Remaining Property and the rest is empty. When I tried to add value in NoRentedProperty the NoOfRemaningProperty still displays 1 and the amount was not being multiplied to the Amount Tendered.
I’ve checked my code and am quite sure that it’s all fine. But I don't understand why this is happening.

First & foremost, you should always format your code to make it easier to read. It helps you debug issues like this better & it helps others—like us—aid you in debugging issues:
function formatMoney ($number, $fractional=false) {
if ($fractional) {
$number = sprintf('%.2f', $number);
}
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number) {
$number = $replaced;
}
else {
break;
}
}
return $number;
} // formatMoney
$query_sql = "SELECT SUM(sales) sales_total FROM sales WHERE date='$startDate'";
// echo $query_sql . '<br />';
$result1 = mysql_query($query_sql);
while ($row = mysql_fetch_array($result1)) {
$rrr = $row['sales_total'];
echo formatMoney($rrr, true);
}
The main thing I did beyond basic formatting is to return SUM(sales) as sales_total.
As far as formatting goes, I also set the actual query SQL in a variable named $query_sql and have a commented out line with echo $query_sql . '<br />'; in it. I recommend you uncomment that on your system and look at the query that is being set & test that directly in the database itself.
Given the fact you are not providing examples of what $startDate looks like—or explaining where that comes from—not much else can be done to debug this.

Related

I am getting really long wait times getting results using googles distance matrix

I am building a small project to help find locations to a user and give the distance between the two. I found some code using the distancematrix that works like a charm, that is until I started including more locations to find the distance between the user and the locations. The code below worked great for three or four locations, but when it gets to 20 or above it will take up to eight or nine seconds. After spending a few hours reading into others projects utilizing the distance matrix this should not be the case and should be able to produce hundreds of results in seconds. By results I mean the distance from point A to point B, yet I am getting bogged down with only 20 queries.
Am I utilizing the distance matrix in an incorrect way?
Note: $orgin is outside the scope of the loop, but had the user address.
Any help or recommendations would be greatly appreciated.
foreach ($AllC as $key=>$item){
echo $item;
$userQueryResult2 = mysqli_query($conn2, "SELECT id, addressP, cityP, StateP, zipP, milesTravel FROM `Performers` WHERE id = $item");
while($row = mysqli_fetch_array($userQueryResult2)){
$finaelId = $row['id'];
$AdP = $row['addressP'];
$CityP = $row['cityP'];
$StateP = $row['StateP'];
$ZipP = $row['zipP'];
$miles = $row['milesTravel'];
$origin = "$AD.', '.$city.' '.$State.' '.$zip";
$destination = "$AdP.', '.$CityP.' '.$StateP.' '.$ZipP";
$distance_data = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='.urlencode($origin).'&destinations='.urlencode($destination).'&key=Hidden');
$distance_arr = json_decode($distance_data);
if ($distance_arr->status=='OK') {
$destination_addresses = $distance_arr->destination_addresses[0];
$origin_addresses = $distance_arr->origin_addresses[0];
} else {
//Need to Send to an error page
echo "<p>The request was Invalid. Please Contact Support</p>";
exit();
}
if ($origin_addresses=="" or $destination_addresses=="") {
//Need to send to an error page
echo "<p>Destination or origin address not found</p>";
exit();
}
// Get the elements as array
$elements = $distance_arr->rows[0]->elements;
$distance = $elements[0]->distance->text;
$duration = $elements[0]->duration->text;
echo "From: ".$origin_addresses."<br/> To: ".$destination_addresses."<br/> Distance: <strong>".$distance ."</strong><br/>";
echo "Duration: <strong>".$duration."";
echo "<br>";
if($distance > $miles){
array_push($tooFar, $finaelId);
} else {
array_push($alldone, $finaelId);
}
}
}
//}
echo $countall;
exit();

putting variable into specific rows after math

i am trying to create a golf tourney scoreboard where i input the scores from each round and if i put in what course was played, it will go into the row of my sql database. how do i make a total score that is figured out in my php code go into a row that i specify on the form?
the form is built out like this:
<input name='name/handi/par/course/hole1/etc' type='text'>
to save space/time just short-handing the coding as much as possible. the php looks like this:
$name = $_POST['name/handi/par/course/hole1/etc'];
then i have the math broken out to figure the front 9, back 9, total score (with handicap [handi] worked in)
$totOut = ($hole1 + $hole2...etc)
$totIn = ($hole10 + $hole11 ... etc)
$total = ($totOut + $totIn) - $handi;
$o_u_total = $total - $par; (over/under for the week)
$o_u_today = $total - $par; (over/under for the day)
the total for today (b/c there are 4 rounds) and the total for the whole week. the totals for the whole week are worked out in a query on the display page:
$sql = "SELECT name,
SUM(total) AS Score,
SUM(o_u_total) AS Over_Under,
total AS Total_Today,
o_u_today AS Over_Under_Today
FROM matchplay
GROUP BY name
ORDER BY Score ASC";
$result = mysqli_query($conn, $sql);
and how i am trying to make the inputted value (course name) go into the specific row (designated in my sql dbase) is like this:
$ridge;
if ($_POST['course'] = 'The Ridge') {
($ridge = $total);
}
$cove;
if ($_POST['course'] = 'The Cove') {
($cove = $total);
} etc
i have a feeling that i am doing something terribly wrong with the if/else, but i don't know how else to choose what i want the $total to go into.
can anybody help me?
i figured it out ... thanks if anybody saw it and was in the middle of thumping me on the head with how easy it was
$ridge;
if ($_POST['course'] == 'The Ridge') {
($ridge = $total);
}
and not
$ridge;
if ($_POST['course'] = 'The Ridge') {
($ridge = $total);
}
Glad you did figure it out. To enhance your code and avoid multiple ifs, you can use a switch case statement.
$course_name = $_POST['course'];
switch($course_name){
case ('The Ridge'):
// your code here
break;
case ('The code'):
// an other code here
break;
}
Hope this help.

Using while() and continue in PHP

I am learning PHP and trying to use the while and continue expressions correctly.
I have a script that creates a 6 digit PIN, and I want to ensure that it is unique, otherwise I want to generate another PIN.
while(1) {
$pin = rand(111111,999999);
$sel = mysql_query("SELECT * FROM formusers WHERE pin = '$pin'");
if(mysql_num_rows($sel) != 0) { continue; }
mysql_query("INSERT INTO formusers(email,password,pin) VALUES('".$_POST['srEmail']."','".$_POST['srPass']."','".$pin."')");
if(mysql_affected_rows()!=-1) {
echo "Pin:" . $pin;
exit;
} else {
echo "Existing email, try again<br />";
}
break;
}
Do I have the syntax for the loop correct? It seems to work, but there's no way for me to debug it in the instance the rand() function creates the same PIN twice.
Also, in the event I did run out of unique PINs, what would happen here? Presumably it would loop indefinitely? Is there any way to prevent this?
Yeah, the code works, but as stated the infinite loop is concerning. You could possibly solve that like this:
var $i = 0;
while($i < 10) {
$i++;
$pin = rand(111111,999999);
$sel = mysql_query("SELECT * FROM formusers WHERE pin = '$pin'");
if(mysql_num_rows($sel) != 0) { continue; }
mysql_query("INSERT INTO formusers(email,password,pin) VALUES('".$_POST['srEmail']."','".$_POST['srPass']."','".$pin."')");
if(mysql_affected_rows()!=-1) {
echo "Pin:" . $pin;
exit;
} else {
echo "Existing email, try again<br />";
}
break;
}
This would ensure you would never make more than 10 iterations. However, the larger problem is probably that even that sampling size won't work in the future. This presents a bit of a conundrum. One possible approach is to determine how many unique numbers exist before starting the loop by counting them and then iterate that many times, but that approach is something like n2 (maybe, I'm not real good on big-O, I just know it would be bad).
You can leverage the unique nature of php array keys for this.
function getPins($qty){
$pins = array();
while (count($pins) < $qty){
$pins[rand(111111,999999)] = "";
}
return array_keys($pins);
}
This will make sure that for a given run you will get $qty number of unique pins. You might want to look at appending a unique prefix to each run of the function to avoid multiple runs creating collisions between the two.
You can seed random, so it gives you the same values every time, you run it:
srand (55 ); //Or some other value.
The while loop syntax looks okay to me.

PHP / MySQL Simple IF / ELSE not so simple

I think my mind must be going through a Boxing Day mess.
I am building a basic comment section for every game a sports team plays.
So, when no comments are entered (in the MySQL DB), I simply want to display "Be the first to enter a comment"; otherwise, display the comment results table in html format.
I can easily display the comment result table.
For some reason, I can't get the IF no comments to work properly. Feel so amateurish right now . . . :-)
I have declared row count:
$row_count = 0;
I am adding to the count inside the while statement
while($row = mysql_fetch_array($result))
{
// adding to count
$row_count++;
My count is working as I can display the row number to the screen.
Here is IF / ELSE my code:
if ($row_count === 0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
} else {
// no need to show code as this already works!
you can use
mysql_num_rows($queryReference)
Hope this helps.
Thanks.
Please do one thing print this value using below function and tell me what is output
var_dump($row_count);
or you can use == instead of ===
$query = mysql_query("SELECT * FROM comments");
$c = mysql_num_rows($query);
if($c==0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
}
else {
while($row = mysql_fetch_array($query))
{
$vars = $row[index];
}
}
$row_count = 0;
I am adding to the count inside the while statement
while($row = mysql_fetch_array($result))
{
// adding to count
$row_count++;
}
My count is working as I can display the row number to the screen.
Here is IF / ELSE code:
if ($row_count == 0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
} else {
// no need to show code as this already works!
}

When listing information from a database using php and mysql how would you make the first row look different to the rest?

Basically I have articles in my database and I want to alter the way the first record displays. I want the lastest (Posted) article to be the focus and the older article just to list, (see F1.com). I need to know how to get the first of my values in the array and get it to display differently but I am not sure how to do this, I can do it so all rows display the same just not how to alter the first row. I also need to know how to tell the rest of the rows to display the same afterwards im guessing you use an if statement there and before that some kind of count for the rows.
Current code:
$result = mysql_query("SELECT * FROM dbArticle WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result))
{
echo "<h2 class=\"heading1\">". $row['title'] ."</h2>";
echo "By: ".$row['username']." Type: ".$row['type']." Posted: ".$row['timestamp']."
$body = $row['body'];
echo "<br/><p>";
echo substr("$body",0,260);
echo "...<span class=\"tool\"><a class=\"blue\" href=\"index.php?pageContent=readArticle&id=".$row['id']."\">Read More</a></span></p><hr/>";
}
mysql_close($con);
Ok I have taken Luke Dennis's code and tried to test it, but I am getting this error: Warning: Invalid argument supplied for foreach() this is the line of the foreach statment. Something that has just come to mind is that I will only want 5 or so of the older articles to display. This is what I have thats creating the error:
<? $con = mysql_connect("localhost","****","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("******", $con);
$result = mysql_query("SELECT * FROM dbArticle ORDER BY timestamp DESC");
$first = true;
foreach($result as $row){
if($first)
{
echo"".$row['title']."";
echo"this is the headline";
$first = false;
}
else
{
echo"".$row['title']."";
}
}
?>
Do I need to add mysql_fetch_array somewhere to set the array up?
I would just iterate through the results and apply a css class to the first entry:
$first = true;
while ($row = mysql_fetch_assoc($result)) {
$cssClass = '';
if ($first) {
$cssClass = 'highlight';
}
echo '<p class="' . $cssClass . '">' . $row['text'] . '</p>';
$first = false;
}
It's a bit crude, but I often hard-code a variable to designate the first run through a loop. So something like:
$first = true;
foreach($list_of_items as $item)
{
if($first)
{
// Do some stuff
$first = false;
}
else
{
// Do some other stuff
}
}
A simple if statement when looping through your results will usually do the trick. You can use a boolean to indicate if you've output the first row of results or now. If you haven't then give it a particular style and then set the boolean to true. Then all subsequent rows get a different style.
All of the above are correct. Luke Dennis' post is of course fleshed-out a bit more.
As Brian Fisher said, add some CSS styling to the first link when you encounter it per Luke's post.
I took a look at the article list on the F1 website. Pretty well constructed site - "One would expect that." :-)
Anyway, the article listings are contained within a two row table (summary="Latest Headlines") in descending order (newest first).
Just place a class in the second column (<td class="first-news-article">). Then add the class name and appropriate styling values in the css file - probably your' modules.css. There's already quite a few class values associated with articles in that file, so you may be able to just use an existing value.
That should be about it - other than actually doing it!
By the way, judging by the quality of the underlying html, I'm assuming there's already an "article list emitter." Just find that emitter and place the appropriate conditional to test for the first record.
Darrell
I just noted your code addition. I assume that you were showing the F1 site as an example. Anyway, I think you're on your way.
I presume you have some code that loops through your resultset and prints them into the page? Could you paste this code in, and that might give us a starting point to help you.
I don't know PHP, so I'll pseudocode it in Perl. I wouldn't do it like this:
my $row_num = 0;
for my $row ($query->next) {
$row_num++;
if( $row_num == 1 ) {
...format the first row...
}
else {
...format everything else...
}
}
The if statement inside the loop unnecessarily clutters the loop logic. It's not a performance issue, it's a code readability and maintainability issue. That sort of thing just BEGS for a bug. Take advantage of the fact that it's the first thing in the array. It's two different things, do them in two different pieces of code.
my $first = $query->next;
...format $first...
for my $row ($query->next) {
...format the row...
}
Of course, you must make the first row stand out by using tags.
I'd use array_shift():
$result = mysql_fetch_assoc($resultFromSql); // <- edit
$first = array_shift($result);
echo '<h1>'.$first['title'].'</h1>';
foreach ($result as $row) {
echo '<h2>'.$row['title'].'</h2>';
}
The best way to do this is to put a fetch statement prior to the while loop.
Putting a test inside the while loop that is only true for one iteration can be a waste of time for a result of millions of rows.

Categories