php mysql total sum two tables - php

When someone selects a service number, then it will pop down and only give the total one records. I want it to give to total from two tables..
<?php
$qry = mysql_query ("SELECT SUM(fruit) AS total FROM fruitinventory WHERE `fruitcolor` LIKE '%{$_POST['select']}%'");
$row2 = mysql_fetch_assoc($qry);
echo $row['total'];
?>
<?php
$qry = mysql_query ("SELECT SUM(fruitsmart) AS total FROM fruitrotten WHERE `fruitcolor` LIKE '%{$_POST['select']}%'");
$row = mysql_fetch_assoc($qry);
echo $row['total'];
?>
Then
I want the total of both rows to display then too.
<?php
$total return = $row+$row2
?>

You can consolidate your two database calls into a single query, and use the columns of the result as your variables to echo out:
<?php
$input = mysql_real_escape_string($_POST['select']);
$sql = "
SELECT
(
SELECT SUM(fruit)
FROM fruitinventory
WHERE fruitcolor LIKE '%$input%'
) AS totalfruit,
(
SELECT SUM(fruitsmart)
FROM fruitrotten
WHERE fruitcolor LIKE '%$input%'
) AS totalfruitsmart";
$qry = mysql_query($sql);
$row = mysql_fetch_assoc($qry);
echo $row['totalfruit'] . '<br />';
echo $row['totalfruitsmart'] . '<br />';
echo $row['totalfruit'] + $row['totalfruitsmart'];
?>
Please, at the very minimum, use mysql_real_escape_string() to help prevent against SQL injection attacks which is what your original code was wide open to.

Assuming you want to keep that same sort of structure for you code, you can display a total like so (Note: MySQLi (i = improved) functions should be used as MySQL functions are deprecated):
<?php
$qry = mysqli_query ("SELECT SUM(fruit) AS total FROM fruitinventory WHERE `fruitcolor` LIKE '%{$_POST['select']}%'");
$row2 = mysqli_fetch_assoc($qry);
echo $row2['total'];
$qry = mysqli_query ("SELECT SUM(fruitsmart) AS total FROM fruitrotten WHERE `fruitcolor` LIKE '%{$_POST['select']}%'");
$row = mysqli_fetch_assoc($qry);
echo $row['total'];
$total = $row['total'] + $row2['total'];
echo $total;
?>
Since it will come up, I suggest you look at using PDO instead of the mysql_ (or at least wrap mysqli_real_escape_string around your variables) to protect your database.

You can try to do the sum using only SQL. Something like below:
$qry = mysql_query ("
SELECT (
( SELECT SUM(fruit) AS total FROM fruitinventory WHERE `fruitcolor` LIKE '%{$_POST['select']}%' ) +
( SELECT SUM(fruitsmart) AS total FROM fruitrotten WHERE `fruitcolor` LIKE '%{$_POST['select']}% )
) AS total") ;
$row = mysql_fetch_assoc($qry);
echo $row['total'];

Related

PHP how to print a query with SUM and math operators

I need to print a mysql (or better mysqli) query that contain math operators.
If I use a query like that
$sql = "SELECT SUM( `Home` + `Away`) AS Tot\n"
. "FROM `teams`\n"
. "WHERE `idteam` = \'Chelsea\'";
when I go to print the %result with mysql_result:
<?php echo mysql_result($result1,0); ?>
or with mysqli function:
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s \n",$row[0]);
it doesn't works.
The same code works if the Query ask to db just a simple information and not math operators like "SELECT SUM(a+b)*3"
Any ideas?
Thank you for support
try
$sql = "SELECT Home + Away AS Tot FROM teams WHERE idteam='Chelsea'";
SUM() is an aggregate function, your just adding 2 numbers
$sql = "SELECT SUM(Home + Away) AS Tot FROM teams WHERE idteam='Chelsea'"; Works for me. I think the problem is in your php try
echo mysql_result[0];
what if you try this?
$sql = "SELECT SUM(Home + Away) AS Tot FROM teams WHERE idteam='Chelsea'";
$res = mysql_query($sql);
while ($row = mysql_fetch_array($res))
{
echo $row["Tot"]."<br>";
}
(but this will print only one row)

PHP not printing result of MySQL query

I am using PHP/MySql to display some results from a database.
CODE
$query = "select * from users where (fname like '%".$searchTerm."%') OR (lname like '%".$searchTerm."%')";
$result = $db->query($query);
echo "yoooo";
$num_rows = $result->num_rows;
echo "<br/>".$num_rows." results st 2";
for ($i=0; $i<$num_rows ; $i++) {
$row = $result->fetch_assoc();
$fn = $row['fname'];
$ln=$row['lname'];
echo "<br/>".stripslahes($fn)." ".stripslashes($ln);
}
This shows:
yoooo
1 results st 2
But nothing more... Why? I am sure that the names I use in the associative array are the column names in the table...
I'd try to:
turn on error_reporting(E_ALL)
echo the query + make sure $searchTerm is safe(avoid sql injections)
var_dump($row)

max(id) and limit 10, but use them in different places

I have two tables, posts and sections. I want to get the last 10 posts WHERE section = 1,
but use the 10 results in different places. I make a function:
function sectionposts($section_id){
mysql_set_charset('utf8');
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
$maxpost12 =mysql_query($maxpost1);
while ($maxpost_rows = mysql_fetch_array($maxpost12 ,MYSQL_BOTH)){
$maxpost2 = $maxpost_rows[0];
}
$query = "SELECT * FROM posts WHERE id = $maxpost2";
$query2 = mysql_query($query);
return $query2;
}
$query2 = sectionposts(6);
while ($rows = mysql_fetch_array($query2)){
echo $rows['title'] . "<br/>" . "<br/>";
echo $rows['id'] . "<br/>" . "<br/>";
echo $rows['image_section'] . "<br/>";
echo $rows['subject'] . "<br/>";
echo $rows['image_post'] . "<br/>";
}
How can it take these ten results but use them in different places, and keep them arranged from one to ten.
this was the old case and i solve it but i found another problem, that, if the client had deleted a post as id = 800 "so there aren't id = 800 in DB" so when i get the max id minus $NUM from it, and this operation must be equal id = 800, so i have a programing mistake here, how can i take care of something like that.
function getmax_id_with_minus ($minus){
mysql_set_charset('utf8');
$maxid ="SELECT max(id) FROM posts";
$maxid1 =mysql_query($maxid);
while ($maxid_row = mysql_fetch_array($maxid1)){
$maxid_id = $maxid_row['0'];
$maxid_minus = $maxid_id - $minus;
}
$selectedpost1 = "SELECT * FROM posts WHERE id = $maxid_minus";
$query_selectedpost =mysql_query($selectedpost1);
return ($query_selectedpost);
}
<?php
$ss = getmax_id_with_minus (8);
while ($rows = mysql_fetch_assoc($ss)){
$main_post_1 = $rows;
?>
anyway "really" thanks again :) !
A few thoughts regarding posted code:
First and foremost, you should stop using mysql_ functions as they are being deprecated and are vulnerable to SQL injection.
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
When you SELECT MAX, MIN, COUNT, AVG ... functions that only return a single row, you do not need an ORDER BY or a LIMIT.
Given that you are only asking for the MAX(id), you can save work by combining your queries like so:
SELECT * FROM posts
WHERE id = (SELECT MAX(id) from posts WHERE section_id = $section_id)
If I'm understanding what you're trying to do (please correct me if I'm wrong), your function would look something like:
function sectionposts($section_id) {
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$stmt = mysqli_prepare($link, "SELECT title, id, image_section, subject, image_post FROM posts "
. "WHERE section_id = ? ORDER BY id DESC LIMIT 10");
mysqli_stmt_bind_param($stmt, $section_id);
return mysqli_query($link, $stmt)
}
$result = sectionposts(6);
while ($row = mysqli_fetch_assoc($result)) {
echo $rows['title'] . "<br /><br />";
echo $rows['id'] . "<br /><br />";
echo $rows['image_section'] . "<br />";
echo $rows['subject'] . "<br />";
echo $rows['image_post'] . "<br />";
}
Try this instead, to save yourself a lot of pointless code:
$sql = "SELECT * FROM posts WHERE section_id=$section_id HAVING bar=MAX(bar);"
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo ...;
echo ...;
The having clause lets you find the max record in a single operation, without the inherent raciness of your two-query version. And unless you allow multiple records with the same IDs to pollute your tables, removing the while() loops also makes things far more legible.
Seems like you want to store them in an array.
$posts = array(); //put this before the while loop.
$posts[] = $row; //put this in the while loop

How to ignore duplicate rows when echoing mysql query result

I trying to make tag cloud system and i enter the tags in one table with "name" and "product_id".
I make that may have multiple same tags everyone for different product.
My problem is that when echo the tags from the table it show me all tags,this is good,but the repeated tags are in that count. I need to echo repeated tags only once, but i don't know how to make that.
Here is and my code that showed and repeated tags.
$id = $_GET['catid'];
$sql = "SELECT * FROM tags_group";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
//echo $row['name'];
$id = $row['id'];
$sql1 = "SELECT * FROM tags WHERE tag_group='$id'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_array($result1)) {
$name = $row1['tag_name'];
$sql2 = "SELECT * FROM tags WHERE tag_name='$name'";
$resut2 = mysql_query($sql2);
$rows = mysql_num_rows($resut2);
echo $row1['tag_name'] . '(' . $rows . ')' . '<br>';
// echo $row1['tag_name'].$rows.'<br>';
}
echo '<br>';
}
You have to use the DISTINCT keyword do avoid duplicates:
SELECT DISTINCT * FROM tags_group
As I mentioned in the comments above, you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article.
UPDATE
It also looks like you're using nested queries, rather than joining your tables and retrieving the results. Try this instead:
$id = $_GET['catid'];
$sql = "SELECT tags.tag_name, count(*) AS name_count FROM tags
INNER JOIN tags_group
ON tags.tag_group = tags_group.id
GROUP BY tag_name";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$name = $row['tag_name'];
$rows = $row['name_count'];
echo $name . '(' . $rows . ')' . '<br>';
// echo $row['tag_name'].$rows.'<br>';
}
echo '<br>';
Here I don't use DISTINCT but GROUP BY allows you to aggregate the count for each distinct row (based on the GROUP BY column).
Take a look at this diagram to better understand how joins work.

how to count the number of rows we have in a table

I simply want to count the total number of rows I have in a table.
I will put this number in parenthesis at the right of the categories names in my website's sidebar.
In SQL
SELECT COUNT(*) FROM your_table
And from PHP
$result = mysql_query('SELECT COUNT(*) AS count FROM your_table');
$row = mysql_fetch_assoc($result);
$count = $row['count'];
Alternatively if you were to use PDO (without a prepared statement)
$count = (int) $pdo->query('SELECT COUNT(*) FROM your_table')->fetchColumn();
Then simply echo it
echo '(Rows: ' . $count . ')';
Or if you want to be fancy using printf
printf('(Rows: %d)', $count);
It's also possible to do this from PHP in another way using mysql_num_rows() function.
Example:
$result = mysql_query('SELECT id FROM your_table');
$count = mysql_num_rows($result);

Categories