Noreply Noreply Noreply Noreply - 2 months ago 5x
PHP Question

I find it difficult to use sum()

I want to sum the values of a particular coloumn where the date is between the "last Tuesday" and "Today". I wrote this code:

define('DB_HOST', '****');
define('DB_USER', '****');
define('DB_PASSWORD', '****');
define('DB_DATABASE', '****');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
return mysql_real_escape_string($str);

//Sanitize the POST values
$d=strtotime("previous Tuesday");

$res=mysql_query("SELECT sum(mball202) FROM manager WHERE dateid >= date('Y-m-d', $d) AND dateid <= date('Y-m-d', $dk)");

<td align="center"><?php echo $row['sum(mball202)']; ?></td>

but if i run the file, it returns (Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /srv/disk11/1165502/www/ on line 44

What am I doing wrong? Please someone help me.


mysql_error returns false, because thereis an error in you query. You should correct it to :

$dateStart = date('Y-m-d', $d);
$dateEnd = date('Y-m-d', $dk);

$res=mysql_query('SELECT sum(mball202) FROM manager WHERE dateid >= "' . $dateStart . '" AND dateid <= "' . $dateEnd . '"');

Otherwise, your query is :

SELECT sum(mball202) FROM manager WHERE dateid >= date('Y-m-d', 1470693600) AND dateid <= date('Y-m-d', 1470780000)