Adding different values together from same table - php

I have a table. In that table, there is are two fields called to and amount. I need to display the sum of amount of all rows where to value is equal to a particular value. (Say 34). How to achieve this?
Code I have done so far
$result = mysql_query("SELECT * FROM transactions WHERE to = '34'")or die(mysql_error());
while($row = mysql_fetch_array( $result )) { echo $row['amount']; } ?>
The above code gives the individual amount value of each row. But what I want is the sum of these values.
The Database

Use SUM to add all the amounts and echo it
$result = mysql_query("SELECT SUM(amount) as amounts FROM transactions WHERE to = '34'")or die(mysql_error());
while($row = mysql_fetch_array( $result )) { echo $row['amounts']; } ?>

I suggest you to use mysqli_* or PDO because mysql_* is deprecated and not available in PHP 7.
Here is the complete example of your code by using MYSQLi Object Oriented:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT SUM(amount) as amounts FROM transactions WHERE to = 34";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['amounts']. "<br>";
}
}
else
{
echo "0 results";
}
$conn->close();
?>

Related

php echo result from mysql and datetime selection

MySQL database Start = "2017-03-29 01:30:00"
The problem is:
I print the $SQL and search the record in MySQL database, it can search the record. However, I need to debug and test if there is no result, it will be expected to echo "No". But, it always to echo "Yes" no matter I can get the record in MySQL or not.
How can I fixed it.
Main purpose: Get the record if there are and Echo "No" if there don't have record
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$dbName = "fyp";
$tbName = "events";
$String_start = '2017-03-29 01:28:00';
$String_end = '2017-03-29 01:32:00';
$conn = new mysqli($serverName, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$staffID = $_SESSION['userID'];
$staff_ID = '15207800';
$sql = "SELECT *
FROM `$tbName`
WHERE `start` BETWEEN ('$String_start') AND ('$String_end')";
echo $sql;
$result=mysqli_query($conn,$sql);
if($result)
{
echo "Yes";
}
else{
echo "no";
}
?>
Mysql query only return fails if there is an issue, for successful execution it returns TRUE even if there is no record. You can achieve with follwing way
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$dbName = "fyp";
$tbName = "events";
$String_start = '2017-03-29 01:28:00';
$String_end = '2017-03-29 01:32:00';
$conn = new mysqli($serverName, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$staffID = $_SESSION['userID'];
$staff_ID = '15207800';
$sql = "SELECT *
FROM `$tbName`
WHERE `start` BETWEEN ('$String_start') AND ('$String_end')";
echo $sql;
$result=mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($result);
if($num_rows > 0)
{
echo "Yes";
}
else{
echo "no";
}
?>
Use mysqli_num_rows that will return total results returned by the query. If total > 0 then results found else no results.
To fetch rows from MySQL result set, use mysqli_fetch_assoc
$result = mysqli_query($conn,$sql);
// $result contains result set and will return `TRUE` if query was successfully executed
// and will return `FALSE` only in case of error
$total = mysqli_num_rows($result);
if($total > 0)
{
echo "Yes";
// Fetch rows from mysql result set
while($row=mysqli_fetch_assoc($result))
{
print_r($row);
}
}
else
{
echo "no";
}

Count rows in a SQL group

I have a script that I want to put on a dashboard. The SQL works and groups the items in the while and it is displayed in the dashboard correctly. However I also want the QTY's to show.
So if the SQL is grouping how can I count the rows it returns so I can echo the QTY out in to my table for each row. This is my code.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
$custid = $row['CustomerID'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "SELECT * FROM stock
JOIN hardware ON stock.HardwareID = hardware.HardwareID
WHERE stock.CustomerID = $custid GROUP BY stock.HardwareID";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
// output data of each row
while($row1 = $result1->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row1['Hardware']."</td>";
echo "<td></td>";
echo "</tr>";
}
}
?>
So the aim is to have the row
echo "<td></td>";
Have a variable in it that shows the qty for each row that is grouped.
you can use this query, group by query has to select and provide aggregation, here i have provided count, if you require some of appropriate column you can change it accordingly...
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
$custid = $row['CustomerID'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "SELECT stock.Hardwareid, count(*) as CountHardware FROM stock
JOIN hardware ON stock.HardwareID = hardware.HardwareID
WHERE stock.CustomerID = $custid GROUP BY stock.HardwareID";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
// output data of each row
while($row1 = $result1->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row1['Hardware']."</td>";
echo "<td></td>";
echo "</tr>";
}
}
?>

Not able to get from date

if i enter two different values i am getting the date to_date value in from_date value
$to_date=$_POST['date'];
$from_date=$_POST['date'];
$query="SELECT * FROM reports WHERE date BETWEEN $from_date AND $to_date";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['amount'];
}
echo $qty;
what is the right way to do
First of all, use mysqli_* or PDO, because mysql_* is deprecated and closed in PHP 7.
In your code you need to use quotes around $from_date and $to_date.
One more thing, if your start and end date is same than don't know why are you using BETWEEN, you can just simply use =.
Here is the complete example of your code by using MYSQLi Object Oriented:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$to_date = $conn->real_escape_string($_POST['date']);
//$from_date = $conn->real_escape_string($_POST['date']);
$sql = "SELECT * FROM reports WHERE date = '$to_date'";
$result = $conn->query($sql);
$qty = 0;
if ($result->num_rows > 0) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$qty += $row['amount'];
}
echo $qty;
}
else
{
echo "No record found";
}
$conn->close();
?>
Also note that, if this query is just for getting total amount no other use, than you can use your query like:
SELECT SUM(amount) FROM reports WHERE date = '$to_date'
Update:
As per Mr. Magnus suggested, here is the basic example of Prepared Statements.
From the Manual: The user input is automatically quoted, so there
is no risk of a SQL injection attack.
<?php
$sql = "SELECT * FROM reports WHERE date = ?";
$stmt = $conn->prepare($sql);
if ($stmt->execute(array($_POST['date']))) {
while ($row = $stmt->fetch()) {
// your stuff
}
}
?>

How can I stop this from looping?

I am trying to echo the data once in one field. However it is looping and i'm not sure what to change to make it echo once. Does anyone know how? Here is the code:
<?php
$email = $_POST['email'];
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "users";
//Make Connection
$conn = new mysqli($servername, $username, $password, $dbName);
//Check Connection
if(!$conn){
die("Connection Failed. ". mysqli_connect_error());
}
$sql = "SELECT `profilepicurl` FROM users WHERE `email`='".$email."'";
$result = mysqli_query($conn ,$sql);
if(mysqli_num_rows($result) > 0){
//show data for each row
while($row = mysqli_fetch_assoc($result)){
echo $row['profilepicurl'];
}
}
?>
Thanks!
This is quite simple!
Change while($row = mysqli_fetch_assoc($result)){ to $row = mysqli_fetch_assoc($result){
Remove the while() loop and the braces:
if ( mysqli_num_rows($result) > 0 ) {
//show data for each row
$row = mysqli_fetch_assoc($result);
echo $row['profilepicurl'];
}
The correct way to stop a loop is using break:
if(mysqli_num_rows($result) > 0){
//show data for each row
while($row = mysqli_fetch_assoc($result)){
echo $row['profilepicurl'];
break;
}
}
Although, if you just need 1 value, you can remove the while loop and use only:
$row = mysqli_fetch_assoc($result);
echo $row['profilepicurl'];
Notes:
Your script is unsafe due to the possibility of sql injection, make sure you read how can i prevent sql injection in php.

PHP MySQLi echo data in array without doing a while loop

When using MySQLi, do I have to perform a kind of while loop where the actual data from the query is put into a variable array?
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// Check if able to connect to database
if ($conn->connect_error) {
trigger_error("Database connection failed: " . $conn->connect_error, E_USER_ERROR);
}
$sql = "SELECT name FROM users WHERE email = '$email'";
$rs = $conn->query($sql);
$numRows = $rs->num_rows();
I always do the following:
$rs->data_seek(0);
while($row = $rs->fetch_assoc()) {
$name = $row['name'];
}
echo $name;
Isn't there a much more convenient way to echo the data form the query when there is only one row?
If there is only one row, you don't need the loop. Just do:
$row = $rs->fetch_assoc();
$name = $row['name'];

Categories