How to calculate the sum of variables in PHP - php

It calculates, but starting from the second row.
<?php
include('connect-db.php');
$query = "select * from users";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$sold= array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo "<table><tr><td>" . $sold. "</td></tr></table>";
}
?>

Your code has many issues:
Your code starts to calculate from the second row because of the line:
$row = mysql_fetch_array($result);
which obtains the first result from the opened recordset before the while loop.
$sold = array();Why is that an array?
If you want to sum to $sold, threat the variable as an integer and initialize it with a 0.
$sold = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
$sold += $row['contract']+$row['tva'];
echo "<table><tr><td>" . $sold. "</td></tr></table>";
It seems to me also that you may want to print the table only once. If this is true, consider to query the database with an aggregation function like SUM():
SELECT SUM(contract + iva) AS contractIva FROM users GROUP BY <some column in your table>;
The above allows to remove the while loop.

Since you already extracted a row from the result, with $row = mysql_fetch_array($result);, the script starts adding only with the next row. Th correct code would be:
<?php
include('connect-db.php');
$query = "select * from users";
$result = mysql_query($query);
$sold= array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo "<table><tr>
<td>" . $sold. "</td>
</tr></table>";
}
?>

you can do that via query as well so that you don't need to perform calculation on the application level, database level can do this job for you.
select sum(col1+col2) as total from users
And you want one table instead of multiple tables I guess, if yes then do it like this:
echo "<table>
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo <tr><td>" . $sold. "</td></tr>";
}
echo "</table>";

Related

Getting number of rows form SQL Server table

I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.

Compare MySQL data with another table

This code below echoes out 8 names from tableOne, but I want to compare those names with 8 names in another table. I want to compare the rows echoed in $row['weight'] with tableTwo, and if the results don't match, then add a <span class="strike"> </span> to the result echoed in $row['weight'].
How do I go about adding an if/else to $row['weight'] compare each name with the names in another table?
$result = mysqli_query($con,"SELECT * FROM tableOne LIMIT 0, 8");
$i = 1;
while($row = mysqli_fetch_array($result)) {
echo $i. " - " . $row['weight'] . '<br>';
$i++;
}
Here is some simple code to get you started:
$result = mysqli_query($con,"SELECT * FROM tableOne LIMIT 0, 8");
$result2 = mysqli_query($con,"SELECT * FROM tableTwo LIMIT 0, 8");
$i = 1;
while($row = mysqli_fetch_array($result)) {
$value1 = $row['weight'];
$row2 = mysqli_fetch_array($result2);
$value2 = $row2['weight'];
echo $i . " - table 1: ";
echo $value1;
echo ", table 2: - ";
if ($value2 != $value1) {
echo '<span class="strike">$value2</span>';
} else {
echo $value2;
}
echo '<br>';
$i++;
}
You can make the code smarter, to handle cases where there aren't 8 values to compare, and to display the values in an HTML table too, but hopefully this can get you started.
Try this:
$sql="select * from tableone to left join tabletwo tw on to.weight=tw.weight ";
This query will return all the rows in tableone which matches and empty rows for the ones where the weight dont match.
So in your php code:
while($row = mysqli_fetch_array($result)) {
if(empty($row['weight'])){
echo '<span class="strike">$row[weight]</span>';
}
}
This would work with any dynamic number of records in the tables.
How about keeping the values ($row[]) in one array($tableOne) and doing the same thing for table two ($tableTwo) and then perform your comparison in foreach()? (For the sake of simplicity, if you don't want any joins)

Get a PHP Variable From the Bottm to the Top

I am not sure how to do this. From the answer I've found on here, I think it's possible using jquery/ajax maybe. I need to get the value of my variable $i and echo it at the top, but it has to go through my logic to get to the value. Here is my code:
echo "<div id='records'><h1 align='center'>Today's Transfers (" . $i . ") </h1>
<table cellspacing='0' cellpadding='0'>
<tr>
<th>Customer Name</th><th>Phone Number</th><th>Disposition</th><th>User</th><th>Date Called</th>
</tr>
";
$i=0;
$sql = "SELECT * FROM vicidial_closer_log WHERE DATE(call_date) = DATE(NOW()) ORDER BY call_date DESC";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
while($row = $result->fetch_assoc()){
$i++;
$phone_number = $row['phone_number'];
$lead_id = $row['lead_id'];
$disposition = $row['status'];
...then echo those variable in my columns and rows...
}
echo "</table> </div>";
echo $i;
Maybe there is another way to write my code so the logic comes before I output everything? Not sure how to do that though since I'm using a mysql query.
You should get the number of rows from the result set and display those where the i is, since it is essentially the same thing.
$num_rows = mysql_num_rows($result);
Move your code above the echo statement:
$i=0;
$sql = "SELECT * FROM vicidial_closer_log WHERE DATE(call_date) = DATE(NOW()) ORDER BY call_date DESC";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
and add
$num_rows = mysql_num_rows($result);
echo "<div id='records'><h1 align='center'>Today's Transfers (" . $num_rows . ") </h1>
and use the rest of your code as before .. Might think about removing i if you don't need it for something else.
If $i is the total number of returned results, you could do:
echo mysqli_num_rows($result)
... and have your query executed at the top of the page.
This would ideally be all in a model and being set in a view by a controller however. That way you're separating the presentation from the functional logic.
I suggest you have a read about MVC:
Sure, you can just move the echo above your logic. But the best to do is to separate logic from presentation. You can create a class to handle this or maybe just another file, it depends on your needs.
$i=0;
$sql = "SELECT * FROM vicidial_closer_log WHERE DATE(call_date) = DATE(NOW()) ORDER BY call_date DESC";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
while($row = $result->fetch_assoc()){
$i++;
$phone_number = $row['phone_number'];
$lead_id = $row['lead_id'];
$disposition = $row['status'];
echo "<div id='records'><h1 align='center'>Today's Transfers (" . $i . ") </h1>
<table cellspacing='0' cellpadding='0'>
<tr>
<th>Customer Name</th><th>Phone Number</th><th>Disposition</th><th>User</th><th>Date Called</th>
</tr>";
Do your computations first, then display your data.
Horribly mangled example code:
$count = 0;
$output = '';
$res = mysqli_query("SELECT * FROM...");
while( $row = mysql_fetch($res) ) {
$output .= "<tr><td>..." . $row['somevar'] . "</td></tr>";
$count++;
}
echo "<h1>Yadda yadda $count</h1>";
echo "<table>";
echo $output
echo "</table>";

PHP mysql_fetch_array is not returning all rows - one row is always ignored

I am running a fairly straight forward mysql request and returning the results to a table. There were three record in the db, and the query is pulling from two tables. As a result, I am getting a count of three records (echoing mysql_num_rows), but only two show in the table. Using a print_r command on the array result shows only one particular record - the other records do show in the print-r.. I added another record to the db, and now three records show - and the same record as before does not show and is the only record in the print_r command.
Here's the relevant code:
<td id="page1">
<?php
$limit = 15; // Set limit to show for pagination
$page = $_GET['page']; // get page number from submit
if($page)
$start = ($page - 1) * $limit; // first item to display on this page
else
$start = 0; // if no page var is given, set start to 0
$query = "SELECT PartyMstr.PartyMstrID, UserName, FirstName, LastName, XrefPartyRoleID
FROM PartyMstrRole, PartyMstr
WHERE PartyMstr.PartyMstrID = PartyMstrRole.PartyMstrID &&
PartyMstrRole.XrefPartyRoleID = 1
ORDER BY LastName, FirstName ASC
LIMIT $start, $limit
";
$result = mysql_query($query, $connection);
$row = mysql_fetch_array($result) or die(mysql_error());
$totalitems1 = mysql_num_rows($result);
?>
<center><h3> Admin User List </h3></center>
<?php
echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>PartyMaster ID</th>";
echo "<th>UserName</th>";
echo "<th>Last, First</th>";
echo "<th>Link</th></tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr><td>";
echo $row['PartyMstrID'];
echo "<td>";
echo $row['UserName'];
echo "<td>";
echo " " . $row['LastName'] . ", " . $row['FirstName'] . " ";
echo "<td>";
echo "<a href = \"http://www.505575.com/editUser.php?id=" . $row['PartyMstrID'] . "\" >Edit</a>";
// echo "<td>";
// echo $row['XrefPartyRoleID'];
echo "</td></tr>";
}
echo "</table><br/><br/> ";
$paginaton = getPaginationString( $page, $totalitems, $limit,
$adjacents = 1,
$targetpage = "adminUserList.php",
$pagestring = "?page="
); // Functon found in functions.php
echo $paginaton;
?>
</td>
I've spent a lot of time online looking for an explanation without success. I've switched off the $pagination code line without effect. I have tried various other tricks and echoed output. The number of rows returned (n) is always correct, but only n-1 rows appear in the table. Any ideas out there?
Thanks - Don
Every time you call mysql_fetch_array you are taking a row from the resource. When the resource has no more rows to give, it returns false. That's how while ($a = mysql_fetch_array($resource)) loops work.
$result = mysql_query($query, $connection);
$row = mysql_fetch_array($result) or die(mysql_error());
$totalitems1 = mysql_num_rows($result);
// first row is taken from resource
....
while($row = mysql_fetch_array($result))
// now take the rest of the rows
As you can see, your code is doing exactly what you tell it to! Just remove the first $row = mysql_fetch_array($result) or die(mysql_error()); as it doesn't serve any purpose anyway.
You are fetching the first result outside your while loop.
$query = "SELECT PartyMstr.PartyMstrID, UserName, FirstName, LastName, XrefPartyRoleID
FROM PartyMstrRole, PartyMstr
WHERE PartyMstr.PartyMstrID = PartyMstrRole.PartyMstrID && PartyMstrRole.XrefPartyRoleID = 1
ORDER BY LastName, FirstName ASC
LIMIT $start,$limit";
$result = mysql_query($query, $connection);
$row = mysql_fetch_array($result) or die(mysql_error());
$totalitems1 = mysql_num_rows($result);
needs to be:
$query = "SELECT PartyMstr.PartyMstrID, UserName, FirstName, LastName, XrefPartyRoleID
FROM PartyMstrRole, PartyMstr
WHERE PartyMstr.PartyMstrID = PartyMstrRole.PartyMstrID && PartyMstrRole.XrefPartyRoleID = 1
ORDER BY LastName, FirstName ASC
LIMIT $start,$limit";
$result = mysql_query($query, $connection);
$totalitems1 = mysql_num_rows($result);
As the others intimate, the problem is that you're calling mysql_fetch_array() once, on the line after $result = mysql_query( ..., before you go into your while loop. This takes the first row from your results, but you never do anything with it. Then when you start your while loop you call mysql_fetch_array() again, but since you've already taken the first row, it starts with the second row.
okay you must understand why it ignore 1 row lets see $row = mysql_fetch_array($result) or die(mysql_error()); this code fetch your 1st row already and then you fetch in loop so it pointed row after the row is already fetched.
$limit = 15; // Set limit to show for pagination
$page = $_GET['page']; // get page number from submit
if($page)
$start = ($page - 1) * $limit; // first item to display on this page
else
$start = 0; // if no page var is given, set start to 0
$query = "SELECT PartyMstr.PartyMstrID, UserName, FirstName, LastName, XrefPartyRoleID
FROM PartyMstrRole, PartyMstr
WHERE PartyMstr.PartyMstrID = PartyMstrRole.PartyMstrID &&
PartyMstrRole.XrefPartyRoleID = 1
ORDER BY LastName, FirstName ASC
LIMIT $start, $limit
";
$result = mysql_query($query, $connection);
$row = mysql_fetch_array($result) or die(mysql_error());
$totalitems1 = mysql_num_rows($result);
?>
<center><h3> Admin User List </h3></center>
<?php
echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>PartyMaster ID</th>";
echo "<th>UserName</th>";
echo "<th>Last, First</th>";
echo "<th>Link</th></tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr><td>";
echo $row['PartyMstrID'];
echo "<td>";
echo $row['UserName'];
echo "<td>";
echo " " . $row['LastName'] . ", " . $row['FirstName'] . " ";
echo "<td>";
echo "<a href = \"http://www.505575.com/editUser.php?id=" . $row['PartyMstrID'] . "\" >Edit</a>";
// echo "<td>";
// echo $row['XrefPartyRoleID'];
echo "</td></tr>";
}
echo "</table><br/><br/> ";
$paginaton = getPaginationString( $page, $totalitems, $limit,
$adjacents = 1,
$targetpage = "adminUserList.php",
$pagestring = "?page="
); // Functon found in functions.php
echo $paginaton;
?>
</td>

Display only queried ID+row PHP/MySQL

I have my data stored in a MySQL table, which includes an auto_increment ID number (unique) for each new row.
I'd like users to be able to get a certain ID number, using the $_GET function.
eg. User loads http://mysite.com/id.php?id=123
Page displays ID number 123 along with the row.
echo $row['id'];
echo "<table>";
echo "<tr> <th>Unit</th> <th>Message</th> <th>Date</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['title'];
echo "</td><td>";
echo $row['description'];
echo "</td><td>";
echo $row['pubDate'];
echo "</td></tr>";
}
echo "</table>";
echo "</center>";
I'm stuck as to where I put the $_GET bit.
Thanks :)
You should append it to your query (using intval to avoid SQL injection) like this:
// use the id in your WHERE clause, convert it to an integer to avoid sql injections
$query = 'SELECT fields FROM table WHERE id = ' . intval($_GET['id']);
$result = mysql_query($query);
$row = mysql_fetch_row($result);
... do stuff with $row ...
Firstly, your code does not make much sense, since you use $row before it was defined.
Secondly, $result isn't defined at all, and it should be, for example like this:
$id = intval($_GET['id']);
$result = mysql_query("SELECT FROM table WHERE id = '$id'");
And now you know how and where to use $_GET['id'].
Dont waste your time doing the comparison afterwards, you'll save yourself alot of time by adding it to the original query
$id = intval($_GET['id']);
$query = "SELECT whatever FROM table WHERE id=$id";
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `Table` WHERE `id`='" . $id . "'";
$res = mysql_query ($query);
$exist = mysql_num_rows($res);
if ($exist) {
$row = mysqlfetch_assoc($res);
...
}

Categories