How to get sum of mysql column using PHP as usable variable - php

I've been searching for a week now on how to accomplish this but none of the tutorials have worked - I typically get a message "resource id 18."
I'm creating a bank simulation game.
End goal: I want a variable "$player_balance" to be the sum of all account balances owned by that player so that it can be displayed at the bottom of the table under account balances.
Here is my code, thanks for any help or direction that you can provide.
function displayMyAccounts(){
global $database, $session;
$q = "SELECT game_account_number,game_account_owner,game_account_name,game_account_balance FROM ".TBL_ACCOUNTS." WHERE game_account_owner='".$session->username."'";
$result = $database->query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "Database table empty";
return;
}
/* Display table contents */
echo "<table align=\"left\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\" width=\"100%\">\n";
echo "<tr><td><b>Account Number</b></td><td><b>Account Name</b></td><td><b>Balance</b></td></tr>\n";
for($i=0; $i<$num_rows; $i++){
$anumber = mysql_result($result,$i,"game_account_number");
$aowner = mysql_result($result,$i,"game_account_owner");
$aname = mysql_result($result,$i,"game_account_name");
$abalance = mysql_result($result,$i,"game_account_balance");
setlocale(LC_MONETARY, 'en_US');
$abalance2 = money_format('%(#10n', $abalance);
echo "<tr><td>$anumber</td><td>$aname</td><td>$abalance2</td></tr>\n";
}
echo "<tr><td></td><td></td><td>$player_balance</td></tr>\n";
echo "</table><br>\n";
}
displayMyAccounts();
The above code is what appears on each player's "account page." I want the sum of their accounts to appear on the last row. Thanks for any help, I'll continue searching and trying in the meantime.
Here is the output based on the above:
Account Number Account Name Balance
1000083690 Maverick $ 50,000.00
1000083696 WellsFargo $ 50,000.00
1000083697 Wachovia $ 50,000.00

Don't use mysql_result(). It's slow and inefficient, and what you're doing is better done with mysql_fetch_assoc():
$player_balance = 0;
// Also, ditch the for loop. This is the typical convention for retrieving results.
while ($row = mysql_fetch_assoc($result)) {
$abalance1 = money_format('%(#10n', $row['game_account_balance']);
echo "<tr><td>{$row['game_account_number']}</td><td>{$row['game_account_name']}</td><td>$abalance1</td></tr>\n";
// Now add to the balance
$player_balance = $player_balance + $row['game_account_balance'];
}
// And output your balance
$abalance_sum = money_format('%(#10n', $player_balance);
echo "<tr><td></td><td></td><td>$abalance_sum</td></tr>\n";

resource error means
YOU DO NOT HAVE THE TABLE OR THE PERMISSION, OR YOU ARE TRY TO ACCESS A COLUMN WHICH DOES NOT EXIST

Related

How do you add a variable Count on the end of a $row->variable?

We are trying to make life easier on one of our website coded platforms.
There are 8 rows in the database, each with 1-4 at the end of them.
ie. childrensrange1, childrensrange2 and so on.
Then childrennumber1, childrennumber2...
But I don't want to be creating a ton of code, so I have started writing this. But I cannot work out how to assign the number to the end of the $row->variable.
Look at the row starting with: $childrenamountrow
I need it to query the database for $row->childrenamount1, then $row->childrenamount2 and so on.
I'm sure I have done this before, but I cannot remember how to do it.
This block should cover all 4 blocks of age ranges rather than reams of code for each set.
$countchild = 1;
while ($countchild <=4) {
echo "<tr><td><select name='childrensrange$countchild'>";
$querychildren = ("SELECT * FROM `childrensagerange` ORDER BY id");
$resultchildren = $pdo->query($querychildren);
while ($rowchildren = $resultchildren->fetch(PDO::FETCH_OBJ)) {
$childrenrangerow = "$rowchildren->agerange"."$countchild";
echo "<option value='$rowchildren->agerange'";
if ($rowchildren->agerange == $childrenrangerow) { echo " selected='selected'";}
echo ">$rowchildren->agerange</option>";
}
echo "</td><td>";
$childrenamountrow = "$row->childrenamount$countchild";
echo "<input type='text' name='childrenamount$countchild' value='$childrenamountrow'></td></tr>";
$countchild ++;
}
echo "</table>```
why not something like this ?
for (var i=1;i<=4;i++) {
$querychildren = ("SELECT childrensrange"+i+" FROM `childrensagerange` ORDER BY id");
$resultchildren = $pdo->query($querychildren);
(...)
}

Checking if data exists working, but doesn't display what I'm asking it too

Okay, so, I'm checking whether to see if random data selected from a php array already exists within my database.
Here is the code for the snippet that is not working.
$check = "SELECT * FROM contest WHERE Loser = '".$input[$rand_keys[$i]]."' AND Hamantha = '".$input[$rand_keys[$i+30]]."'";
$rs = mysqli_query($con, $check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($data[$i] > 1){
while($data[$i] > 1){
echo'DO NOT USE THIS GUESS';
$rand_keys2 = array_rand($input, 2);
$input[$rand_keys[0]] = $input[$rand_keys[$i]];
$input[$rand_keys[1]] = $input[$rand_keys[$i + 30]];
}
echo $input[$rand_keys2[0]];
echo '-';
echo $input[$rand_keys2[1]];
echo '<br>';
} else {
echo $input[$rand_keys[$i]];
echo '-';
echo $input[$rand_keys[$i + 30]];
echo'<br>';
}
it displays the data that doesn't exist correctly, but when it does exist, the code under the 'if' doesn't run. I put error_reporting on, and all the lines that the data does exist for, it shows an error for all those lines, which is good, it's finding the lines that do exist within the database, yet the stuff under the if don't run why? Like it doesn't display 'DO NOT USE THIS GUESS' ect.
Edit: Here is a picture of the problem i.imgur.com/F35vGzO.png
As you see if found the first guess to be good, while the second guess was already used, but it didn't display the messages i wanted it to.
Ok, changing my above query state to this worked perfectly.
$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}....

Echo statement in PHP not executing in a specific manner

I'm having a problem with some specific PHP code that I've been working on for a few days. It's meant to be a reporting code where I can input a day and a month and it will list the total sales of that particular day.
But, I can't seem to make the last statement whereby, if there are no values(there are no data) in the query, it will display 'No Sales on this particular day'. Here's the code I've been working on. But the last echo statement is not executing. Any ideas?
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
$day=#$_POST['day'];
$month=#$_POST['month'];
echo "<center><h2>Sales report on " .$day. "." .$month. ".2013</h2></center>";
echo "<center><table style='border:2px solid black;' align=center width=600>";
echo "<tr><th colspan=12><center><h2>Sales Report</h2><hr size='2' color='black' /></center></th></tr>";
echo " <th width=400> Amount Collected</th>";
?>
<br>
<?php
$x = 1; //counter
//open a connection to a MySQL server using function mysql_connect
//returns a MySQL link identifier on success, or FALSE on failure.
$conn= mysql_connect("localhost","root","");
if (!$conn)
die ("Connection error: ".mysql_error());
else {
//select a MySQL database
//returns TRUE on success or FALSE on failurue.
$db=mysql_select_db("cqfos");
if(!$db)
die ("DB not found: ".mysql_error());
else {
//put query in a variable $query
$query= "select ROUND(sum(orderdetails.tprice),2)
from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '$day' AND MONTH(orders.date) = '$month'";
$result=mysql_query($query);
if(!$result)
die ("Invalid query: ".mysql_error());
//if record exists
else {
//fetch a result row as both associative array and numeric array
if(mysql_num_rows($result)== 1){
while ($row=mysql_fetch_array($result,MYSQL_BOTH)){
echo "<tr>";
echo "<td align='center'>RM ".$row[0]."</td></tr>";
$x++; //increase the counter
}
}
else {
echo "<tr><th colspan=12>No sales made.</td></tr>";}
}
}
}
echo"</table></center>";
?>
Several problems here
your HTML table syntax is incorrect, and your using an old sql library - and it dose not look like your SQL syntax is right... try this code (not tested as I don't have your data)
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
echo '<div style="margin:auto; textalign:center;">';
echo "<h2>Sales report on " .$_POST['day']. "." .$_POST['month']. ".2013</h2>";
echo "<h2>Sales Report</h2>"
echo "<table style='border:2px solid black;' align=center width=600>";
echo "<tr><th width=400> Amount Collected</th></tr>";
?>
<br>
<?php
$conn = new mysqli("localhost","root","","cqfos");///use mysqli, not mysql : mysql is depricated
if ($conn->mysqli)
exit ("Connection error: ".$conn->errno ." : " $conn->error);
else {
//put query in a variable $query
$eDay = $conn->mysql_real_escape_string($_POST['day']);//escape these to protect the database
$eMonth = $conn->mysql_real_escape_string($_POST['month']);;//escape these to protect the database
//your column name is probably not a rounded value, replaced it with * (return all columns)
$query= "select * from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '"
.$eDay."' AND MONTH(orders.date) = '".$eMonth."'";
$result=$con->query($query);
if($conn->errno)
exit ("Invalid query: ".$conn->errno ." : " $conn->error);
//if record exists
else {
$numericArray = $result->fetch_array(MYSQLI_NUM); //fetch a result row as numeric array
$associativeArray = $result->fetch_array(MYSQLI_ASSOC); //fetch as an associtive array this is not used, just an example
$bothArray = $result->fetch_array(MYSQL_BOTH); //both associtive and numeric this is not used, just an example
}
if(!empty($numericArray))
{
foreach ($numericArray as $value) {
echo "<tr><td>RM ".$value[0]."</td><tr>";//is there more then 1 col? if not you should consider an html list
}
} else {
echo "<tr><td>No sales made</td><tr>";
}
echo"</table></center>";
}
?>
Your SQL (likely) returns more than only one row, so change the line I mentioned before to this:
if(mysql_num_rows($result)>0){
Just letting you know your code is vulnerable to SQLi because you have not sanitized $day and $month. Also please consider using PDO.
If you haven't already - Try running the SQL statement into PHPMyAdmin and see where it outputs the error (if there is one), else it will output the data.*
*Manually inputting the day/month substituting for the variables.

Showing database entries on a PHP calendar

I'm creating a web-based booking system where a user can add bookings into a database, and the details stored in the database are (among others) "DateBooked, StartTime, EndTime, Room".
Here's the bit that pulls the relevant info for the day the user has clicked on from the database:
$query="SELECT * FROM bookings WHERE DateBooked = '{$year}-{$selectedmonth}-{$selectedday}'";
$result = mysql_query($query);
$todayarray = mysql_fetch_array($result);
And the PHP:
$roomcount = 4;
$room = 1;
while ($room <= $roomcount)
{
echo "\n<div class=\"roomtimes\">";
echo "\n<table border=1>";
echo "\n<tr><th class=\"titlecell\">Room $room</th></tr>";
$cellnum = 10;
while ( $cellnum < 23 )
{
echo "\n<tr>";
echo "\n<td class=\"linkcell";
if ($selectedtime==$cellnum)
{
echo " selectedcell";
}
echo "\">";
echo "$cellnum:00</td>";
echo "\n</tr>";
$cellnum++;
}
$room++;
echo "\n</table>";
echo "\n</div>";
}
So my question is, how can I add a bit of text saying "BOOKED" inside each table cell if a entry exists for that room and the number in that cell is in between the start time and end time of that booking?
I'm new to this site so let me know if I've done something wrong or you need more information, thanks!
You need to divide the cell content html and insert your "BOOKED" text there. And I suggest you use mysql_fetch_assoc so you get and associative array and it's easier to get the fields. If I'm understanding your code correctly you might be able to use something like this. This example is a replacement for the row that has the link output in it. I've used mysq_fetch_assoc here to get the StartTime and EndTime fields from the database. You might need to change the fields a bit depending in what data format they are.
echo "$cellnum:00";
if ($todayarray['StartTime'] <= $cellnum && $todayarray['EndTime'] >= $cellnum && $todayarray['Room'] == $room) echo 'BOOKED';
echo "</td>";

Displaying results after MySQL JOIN query with PHP

$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
echo $rows[0][1].$rows[0][0];
/* for($i=0;$i<=10;$i++)
{
echo $rows[i][1].$rows[i][0];
}
*/
This script is supposed to show the last 10 messages in a chat.What I'm doing is getting the Name of the user from the users table and the text from the message table and I want to display them in my chat window.Right now I have only 4 messages recorded and don't know how this affects the whole script I should implement a check for this too, but the bigger problem is that when i use echo $rows[0][1].$rows[0][0]; the info is displayed correctly, but when I try to make a loop so I can show tha last 10 (I tried the commented one) then nothing is displayed.I thought at least when I use this loop I'll see the 4 recorded messages but what really happen is a blank window.Obvously I have the info recorded in $rows[] and can echo it, but don't understand why this loop don't work at all.I'll appreciate if someone can help me with this and with the check if the messages are less then 10.
Thanks.
Leron
P.S
Here is the edited script, thanks to all of you, I need the array because otherwise the most recent message is shown at the top which is not an opiton when I use it for diplaying chat masseges.
for($i=10;$i>=0;$i--)
{
if($rows[$i][1]!="" || $rows[$i][0]!="")
{
echo $rows[$i][1].' : '.$rows[$i][0];
echo "</br>";
}
}
Your FOR loop was running 11 times even if only 10 records. The second clause should be a < instead of <=. Plus the $ was missing on the i variable.
For example sake, you don't really need to make an array from the rows, and you can refer to the fields by name:
while($row = mysql_fetch_array($result))
{
echo $row['name'] . ' says: ' . $row['message'] . '<BR>';
}
why not just do
while($row = mysql_fetch_array($result))
{
echo $row[1]." ".$row[0];
}
Your query, auto limits it to the last 10, this will then show anything from 0 to 10 which get returned.
PS I added a space between username and message for readability
You need $ symbols on your i variable:
for($i=0;$i<10;$i++)
{
echo $rows[$i][1].$rows[$i][0];
}
A more robust solution would be like this:
$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row[1].$row[0];
}

Categories