simple echo SUM and Group by from mysqli - php

I have something that may seem very simple for some people but for the life of me I cannot figure it out (and I've been trying all day long). I have simple DB from which I am trying to get SUM by the client by date. All works fine to the last moment where I add SUM(item) to SELECT - from this point I cannot echo anything. Can anyone help me what is wrong with my code below:
<?php
$q_billing = intval($_GET['q_billing']);
$dblink = mysqli_connect("localhost", "User", "Pass", "Exam_2018");
/* If connection fails throw an error */
if (mysqli_connect_errno()) {
echo "Could not connect to database: Error: ".mysqli_connect_error();
exit();
}
$sqlquery = "SELECT id, client_id, SUM(item) AS total_sales, date
FROM test
WHERE date BETWEEN '".$q_billing."' AND '2018-12-31'
GROUP BY client_id ";
if ($result = mysqli_query($dblink, $sqlquery)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
echo $row["client_id"]." ".$row['total_sales']."<br />";
}
/* free result set */
mysqli_free_result($result);
}
/* close connection */
mysqli_close
?>
Just a note that q_billing is DATE, which I tried to replace with constant 2018-01-01.
I tried also adding ORDER BY, but it does not make any difference. I cannot see any error either - just a blank div where the echo should be.
Thank you for any help

if you group by client_id then you should not select id and date
$sqlquery = "SELECT client_id, SUM(item) AS total_sales
FROM test
WHERE date BETWEEN '".$q_billing."' AND '2018-12-31'
GROUP BY client_id ";

Related

How to get the sum in a column using MySQL and PHP

I've been searching for the better part of five days (no joke, don't want to bother you guys for nothing), but I can't seem to be getting this right. I want to display the total amount of a column (tech) on the screen using a function in PHP. Don't worry, the $day part works in other functions. I don't think it is part of the problem. Thank you in advance.
function calc_tech($day){
include("connect.php"); // include database connection
$res = $mysqli -> query(" SELECT * FROM sales WHERE day = $day ") or die($mysqli->error); // Fetch data from the table
while($val = $res -> fetch_array()){
$tech_total = $val[tech] += $val[tech];
}
echo $tech_total; // Echo the result
//echo "42";
$res -> free(); // Free the query results
$mysqli -> close(); // Close mysqli object
}
My database table looks like this:
You need to make the SUM() the column in the query :
function calc_tech($day){
include("connect.php"); // include database connection
$res = $mysqli -> query(" SELECT SUM(tech) as sum FROM sales WHERE day = $day ") or die($mysqli->error); // Fetch data from the table
$val = $res -> fetch_array();
$tech_total = $val['sum'];
echo $tech_total; // Echo the result
}
1) '$day' should be enclosed by single quotes .
FOR SUM of column name query should be like this
"select sum(tech) as Toatal from sales where day='$day';"

Can't echo array properly

My table in the database contains 3 columns that all has qwe for a username and have the respective dates of January, February and March but when I try to echo them it only displays January. I'm trying to get them all into a drop down list but I can't get past this so I have to make sure I get all of these dates before I put them elsewhere.
{
$con=mysqli_connect('localhost','root','') or die(mysqli_error());
mysqli_select_db($con, 'useddates') or die("cannot select DB");
$request="SELECT date FROM mytable WHERE username='qwe'";
$result=mysqli_query($con, $request);
$fetch=mysqli_fetch_assoc($result);
echo $fetch['date']; echo "<br>";
print_r($fetch);
}
You are missing loop, data come up. You can see when you are printing data using print_r($fetch), use loop to show one by one.
And also try to don't use user input directly in query before checking mysql injection. like you have putted username='qwe' if username is user input then use it like this directly in query Suggestion for query
$request = "SELECT date FROM mytable WHERE username=".mysql_real_escape_string('qwe');
and your with loop try this,
$con = mysqli_connect('localhost', 'root', '') or die(mysqli_error());
mysqli_select_db($con, 'useddates') or die("cannot select DB");
$request = "SELECT date FROM mytable WHERE username='qwe'";
$result = mysqli_query($con, $request);
print_r($fetch);
while ($fetch = mysqli_fetch_assoc($result)) {
echo $fetch['date'];
echo "<br>";
}
?>

Previous data still shows after filter using PHP

I have a query to show all data using PHP and then I have a second query for filtering using startdate and enddate but when I use the second query, the data table shows the first query output plus the second query output.
Here's my code.
Here is my query for the first output:
<?php
session_start();
$con=mysqli_connect("localhost","root","","leavecalendar");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = mysqli_query($con,"SELECT * FROM timekeeping ");
while($row = mysqli_fetch_array($sql))
if(!empty($row)){
$_SESSION['row'][] = $row;
header("location:timekeepinglogs.php");
//print_r($_SESSION);
}
//header("location:timekeepinglogs.php");
//print_r($_SESSION);
?>
Here's a screenshot of what the result looks like:
Now here's the second query which is triggered by the generate button
<?php
session_start();
$row = $_SESSION['row'];
$con=mysqli_connect("localhost","root","","leavecalendar");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = mysqli_query($con,"SELECT * FROM timekeeping WHERE createddate >= '$_POST[startdate]' AND createddate <='$_POST[enddate]' ");
while($row = mysqli_fetch_array($sql))
if(!empty($row)){
$_SESSION['row'][] = $row;
//header("location:timekeepinglogs.php");
//print_r($_SESSION);
}
header("location:timekeepinglogs.php");
//print_r($sql);
?>
Now here's what the second query does (notice that in the first picture the last row has empty clockout) I filtered it using date range may 2 to may 3 so it should only show 3 rows. Take a look
As you can see it just select the data in date range and shows it on the bottom of the data table. I want the filtered data only to show.
Any help will be greatly appreciated.
Probably you are appending the data on each request in table, So you need to clear the sessions data on each new request
Suppose you are searching by dates , before that you need to clear sessions data using
unset($_SESSION['row']);

MySQL Database PHP Specific Rows

My current code is this:
<?php
$con=mysqli_connect("stevie.heliohost.org","rbxdataa_Art","mydata123art");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
mysqli_select_db($con, "rbxdataa_Data");
$Amount=$_GET["Amount"];
$GetType=$_GET["Type"];
$sql = "SELECT * FROM EventRecord WHERE EventType='$GetType' ORDER BY EventId DESC";
$sql_run = mysqli_query($con, $sql);
while($sql_row = mysqli_fetch_assoc($sql_run)){
echo $sql_row['EventId'].'<br>';
}
mysqli_close($con);
?>
As I am currently very new to PHP and MySQL, I have no idea why this code will not work. I am also confused as to how I would make it echo only the top ($Amount) as determined by how large the "EventId" value is.
My intent is to gather the [$Amount] highest rows in the table with the EventType $GetType.
I am aware of SQL Injection vulnerability, however for my purposes this does not affect me.
Error:
"Parse error: syntax error, unexpected T_STRING on line 4"
As I see, you have a normal code, may be you have no any rows in DataBase with requested EventType ?
At second: you have SQL Injection vulnerability. Use PDO and Prepared Statements instead your mysqli_query code.
If you want to get the row with the max eventid, you need do this:
$sql = "SELECT MAX(EventId) FROM EventRecord WHERE EventType='$GetType';
is not necessary order by eventid when u can get the max using MAX(An AGGREGATION FUNCTION)
P.D: you can add more attributes in select statement.
Try this
if you need highest amount with EventType.
$sql = "SELECT MAX(amount_field) FROM EventRecord WHERE EventType='$GetType';
If you want record sorted based on amount from highest to lowest then order by amount desc. (if you have amount column in table)
<?php
$con=mysqli_connect("Removed for Privacy");
mysqli_select_db($con, "Removed") or die(mysqli_error());
$Amount=$_GET["Amount"];
$GetType=$_GET["Type"];
$sql = "SELECT * FROM EventRecord WHERE EventType='$GetType' ORDER BY amount DESC";
$sql_run = mysqli_query($con, $sql);
while($sql_row = mysqli_fetch_assoc($sql_run)){
echo $sql_row['EventId'].'<br>';
}
mysqli_close($con);
?>

MYSQL does not return result in PHP when asked for the first ranking only

I am trying to get hold of 1 record from a MySQL table using PHP. I have tried many different SELECT statements, while they all work in MYSQL they refuse to return any result in php.
The countriesRanking table is a simple two column table
country clicks
------ ------
0 222
66 34
175 1000
45 650
The mysql returns the ranking of the country column (1, 2, 3, etc..) and it returned all results EXCEPT the first ranked country. Eg when country=175, should return 1 but no result returned. Direct query via web browser return blank page, no error message. My PHP code
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country'") or die(mysql_error());
$row = mysql_fetch_assoc($result) or die(mysql_error());
$theranking = $row['rank'];
echo $theranking;
EDIT
I tried the following but get the same blank page
var_dump($row['rank']);
EDIT 2
For a successful query print_r($result) returned something like Resource id #4. While print_r($row) returned Array ( [0] => 4 [rank] => 4 ). But when querying for the top ranking country. eg country=175, it returned a blank page.
Give this a try. It is based on your earlier question. MYSQL returns empty result in PHP
MYSQLI version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysqli_connect($hostname,$user,$password,$database);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 175";
$result = mysqli_query($link,$query);
$arr_result = mysqli_fetch_array($result,MYSQLI_BOTH);
return $arr_result['rank'];
}
mysqli_close($link);
}
echo rank();
?>
MYSQL version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysql_connect($hostname,$user,$password);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 66";
mysql_select_db($database);
$result = mysql_query($query);
$arr_result = mysql_fetch_array($result,MYSQL_BOTH);
return $arr_result['rank'];
}
mysql_close($link);
}
echo rank();
?>
Assuming you are not getting an error that means you are successfully connecting to your database. You are just not getting back any values.
Try:
$row = mysql_fetch_row($result);
I would usually think $row = mysql_fetch_assoc($result); would work but if neither of these work it must be something within your mysql_query.
You can debug this as below.
make sure your SQL is correct by running it on PHPMyAdmin and check the result.
make sure you don't have any fatal errors, if you get a blank page there is something wrong. Turn on PHP errors and see.
print_r($result) and see whether it's empty.
if you want first ranking only then add the LIMIT 1 to your query
If you want only one record from database than you have to use limit in query
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country' LIMIT 1") or die(mysql_error());
and after that use while loop
while($row = mysql_fetch_assoc($result)) {
$theranking = $row['rank'];
}
echo $theranking;

Categories