How to get the sum in a column using MySQL and PHP - 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';"

Related

mysqli_query() returns empty results for full table

I am making a page that queries a table for all columns of all results ordered by entry time in descending order with a limit. When I query for a count of the rows, the query works just fine, but when I try to query the table again for data, I don't get anything. I decided to try cutting the query down to "SELECT * FROM comments" but I still got no results when "SELECT COUNT(*) AS count FROM comments" just beforehand worked. I've tried using mysqli_error(), but that didn't give me any information.
The query doesn't seem to be failing as the result from mysqli_query() isn't false and when I query in phpMyAdmin, the queries work. A little piece of my code below
//open databases
require_once($root . "databases/data.php");
//get number of suggestions in comments table
$cquery = mysqli_query($cbase, "SELECT COUNT(*) AS count FROM comments"); //this works
$c = mysqli_fetch_array($cquery);
$count = $c["count"];
//get all suggestions
//this query fails
$queryText = "SELECT * FROM comments ORDER BY time DESC LIMIT " . (($page - 1) * $pageLimit) . ", " . $pageLimit;
$query = mysqli_query($cbase, $queryText);
//validate query
if($query === false)
{
$failed = true;
}
//get all comments from query
while(!$failed && $array = mysqli_fetch_array($result))
Please try this on line 3
$c = mysqli_fetch_assoc($cquery);
You can also try like this also,
$c = mysqli_fetch_array($cquery, MYSQLI_ASSOC);
You are just using the wrong variable when reading out your query results in your while-loop. mysqli_fetch_array($result) while you saved the query-result in $query so it should be mysqli_fetch_array($query)

Pagination count returning no value

Was hoping someone could give me some help. I have been trying to learn pagination but have run into an issue. when I run this to get my total rows count:
$sql = "SELECT COUNT (*) FROM item WHERE fid='17'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$rows comes back with no value, I am under the impression that $rows should contain the total number of records from item with the fid of 17, when I run SELECT COUNT (*) FROM item WHERE fid='17' in phpmyadmin it returns 98 which is the correct count. Directly before the above code I use this code to connect to the db, which I use again later to display the records which works fine.
$con=mysqli_connect("$host","$username","$password","$dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
This statement displays records later in the script
$sql = mysqli_query($con,"SELECT * FROM item WHERE fid='17' ORDER BY id DESC $limit ");
So there is data and the info is correct.
I have been following this tutorial on the subject http://www.developphp.com/view.php?tid=1349 and it works like a charm on his example in the video, all I have changed is the database particulars to mine. Can't figure this one out, been stuck for days so now I am bothering you fine folks.
Update: Changed
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
to
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rows=mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
And everything is working now. Still wish I knew what was wrong with my original code but I will be moving on. Thanks Phil Perry for all your help this morning!
Well, you could SELECT * FROM... and then call mysqli_num_rows($query). Probably slower than SELECT count(*). BTW, I presume that item is not a reserved word in SQL. You can always wrap table and field names in backticks (not quotes ' or "). You could also try SELECT count(*) AS myCount....
try this,
$sql = "SELECT COUNT(*) FROM item WHERE fid='17'";
$query = mysqli_query($sql);
$row = mysqli_fetch_array($query);
$rows = $row[0];

Get total number of records for a given day in Highcharts and PHP

I'm trying to get my highcharts chart working and I'm almost there.. I just have one little problem: I need that the value will be the total count of the records at the same day but I'm kinda confused with my code now and the chart is totally messed up..
Here is the code that pulls the data:
<?php
header("Content-type: text/json");
include('../includes/config.php');
$tablename = "analytics";
$result = mysql_query("SELECT COUNT(*) AS count FROM $tablename");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$sql = "SELECT id, date FROM $tablename ORDER BY date";
$result = mysql_query( $sql ) or die("Couldn't execute query.".mysql_error());
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row['id'] = (int) $row['id'];
$rows[$i] = array(strtotime($row['date'])*1000, $row['id']);
$i++;
}
echo json_encode($rows);
?>
If it will help here is my database values:
insert into `analytics`(`id`,`user`,`item`,`ip`,`country`,`date`) values
(10,1,1,'127.0.0.1','','2011-12-17 06:41:51'),
(11,1,1,'127.0.0.1','','2011-12-17 06:42:23'),
(12,1,1,'127.0.0.1','','2011-12-17 06:43:07'),
(13,1,1,'127.0.0.1','','2011-12-17 06:44:19'),
(14,1,1,'127.0.0.1','','2011-12-17 06:44:21'),
(15,1,1,'127.0.0.1','','2011-12-17 06:44:22'),
(16,1,1,'127.0.0.1','','2011-12-17 06:44:49'),
(17,1,1,'127.0.0.1','','2011-12-17 06:46:59'),
(18,1,1,'127.0.0.1','','2011-12-17 06:47:20'),
(19,1,1,'127.0.0.1','','2011-12-17 06:47:35'),
(20,1,1,'127.0.0.1','','2011-12-17 06:47:42'),
(21,1,1,'127.0.0.1','','2011-12-17 06:48:07'),
(22,1,1,'127.0.0.1','','2011-12-17 06:48:14'),
(23,1,1,'127.0.0.1','','2011-12-17 06:48:29'),
(24,1,1,'127.0.0.1','','2011-12-18 06:49:10'),
(25,1,1,'127.0.0.1','','2011-12-19 07:05:45'),
(26,1,1,'127.0.0.1','','2011-12-20 08:11:32'),
(27,1,1,'127.0.0.1','','2011-12-21 08:26:45'),
(28,1,1,'127.0.0.1','','2011-12-17 08:44:34');
And here is the final result:
I totally lost my self here, can someone help?
EDIT: did what #ajreal said and here is the output:
This is the query to get count for each date
SELECT date, COUNT(*) AS count
FROM $tablename
GROUP BY date;
You can use this query to replace your first query.
And to a loop (like your second query), set $total += $row["count"] to get a grand total like your original first query does

MySQL not working when ODBC is in the same script

A company I am working for has a Progress DB that store much of their information. They asked me to make a PHP script that can pull data from it and merge it with data inside of a MySQL database.
At first I figured I would just fetch the data, but after a while I found that the Progress DB was incredibly slow. I decided to have the page fetch from either MySQL or Progress depending on which had it (MySQL trumping Progress)
I ran into a problem though in that for some reason ODBC and MySQL don't seem to be able to function when both open. How can I solve this? Is it possible to do what I am needing it to do?
Note: I threw catches for errors all over the place and MySQL never returned an error. The ODBC always goes and returns the content, but it never INSERTs it into the MySQL DB
Here is my code:
$job_num = "59505";
$fields = 'JobNum, Name, City, State, StartDate, ReqDueDate';
$field_queries = 'j.JobNum AS JobNum, Name, City, State, jh.StartDate AS StartDate, ReqDueDate';
//Determine if there is a record in the MySQL DB that has the job
$mysqlr = mysql_query("SELECT * FROM jobsinfo WHERE JobNum='$job_num'");
if(!$mysqlr){
die(mysql_error());
}
//If there is a record, display it from there: faster
if(mysql_num_rows($mysqlr) > 0){
//Take the fields and explode them into an array so that it can be looped through.
$field_array = explode(', ', $fields);
//Return each row from the database
while($row = mysql_fetch_array($mysqlr)){
//Return all fields in the array
foreach($field_array as $key=>$field){
echo $field .": ".$row[$field]."<br>";
}
//Because the Description comes from a different part of the Progress include it here.
echo "Description:<br>".$row['Description'];
}
}else{
//If there is no record in the MySQL display it from the Progress AND copy it over.
//Begin by inserting a record to later be modified
mysql_query("INSERT INTO jobsinfo (JobNum) VALUES ('$job_num')") or die(mysql_error());
$id = mysql_insert_id();
//Connect to the Progress DB
$conodbc = odbc_connect($dsn, $username, $password, SQL_CUR_USE_ODBC);
//Explode the fields so that they can be looped through.
$field_array = explode(', ', $fields);
//Make the query to the Progress DB. Merge many tables into one query using JOINs
$sql = "SELECT TOP 1 ".$field_queries." FROM PUB.JobProd j LEFT JOIN PUB.BookOrd b ON j.OrderNum=b.OrderNum LEFT JOIN PUB.Customer c ON b.CustNum=c.CustNum LEFT JOIN PUB.JobHead jh ON j.JobNum=jh.JobNum WHERE j.JobNum = '$job_num' ORDER BY ReqDueDate DESC";
//Execute the query
$rs = odbc_exec($conodbc,$sql) or die('Select failed!');
//For each record loop through
while(odbc_fetch_row($rs)){
//For each field display
foreach($field_array as $key=>$field){
$value = odbc_result($rs, $field);
echo $field.": ".$value."<br>";
//Update the previously inserted row with the correct information
mysql_query("UPDATE jobsinfo SET ".$field."='$value' WHERE id = '$id'");
}
}
//Because there are multiple job parts it is easiest to just loop through it seperately and not JOIN it
$sql_asmbl = "SELECT * FROM PUB.JobAsmbl AS ja WHERE JobNum = '$job_num'";
//Execture
$rs_asmbl = odbc_exec($conodbc,$sql_asmbl) or die('Select failed!');
echo 'Description:<br>';
$ptdesc ='';
//Loop through all the rows that match the job number
while(odbc_fetch_row($rs_asmbl)){
$ptdesc .= odbc_result($rs_asmbl, 'PartNum') ." - ";
$ptdesc .= odbc_result($rs_asmbl, 'Description') ."<br>";
}
$ptdesc = mysql_real_escape_string($ptdesc);
//Update the MySQL
mysql_query("UPDATE jobsinfo SET Description = '$ptdesc' WHERE id = '$id'");
//Display it
echo $ptdesc;
//Close DB's
odbc_close($conodbc);
mysql_close($conn);
}
You are assuming that MySQL queries always run successfully:
$mysql = mysql_query("SELECT * FROM jobsinfo WHERE JobNum='$job_num'");
if(mysql_num_rows($mysql) > 0){
}
You should always test it explicitly:
$mysql = mysql_query("SELECT * FROM jobsinfo WHERE JobNum='$job_num'")
if( !$mysql ){
die(mysql_error());
}
I see that you make an ODBC connection, but I do not see mysql_connect() or something similar using mysqli or PDO. Are you actually opening a socket connection to mysql and you just left that out of this code example or did you forget to make the connection in your code?
I moved the INSERT up a bit and removed the ' from ('JobNum') and now it works fine.
Found the cause of the error. Both the MySQL and ODBC were using $conn as their connecting variable. This was causing errors.

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

Categories