Noreply Noreply Noreply Noreply - 3 months ago 6
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:

<?php
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
$dk=strtotime("today");
$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)");
while($row=mysql_fetch_array($res))
{
?>

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


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/tst.scienceontheweb.net/admin/manager/result-weekly.php on line 44
)

What am I doing wrong? Please someone help me.

Answer

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)