How to echo with PHP this MySQL command
The following code gives me the following:
$getexpenses = "SELECT sum(expense_amount) FROM projects_expense WHERE project_id=$project_id";
$showexpenses = @mysqli_query ($dbc, $getexpenses); // Run the query.
echo ' . $showexpenses . ';
Gives me a result of
' . $showexpenses . '
instead of 开发者_运维问答the actual sum...
I'm sure it's something simple I'm missing... thanks!
echo " . $showexpenses . "
will work for you. You need double quotes, not single.
I added a call to mysqli_fetch_assoc($showexpenses)
to make it fully functional.
I also sanitized $project_id
to avoid injections and used an alias to make the sum accessible through an associative array.
$getexpenses = "SELECT SUM(`expense_amount`) as `sum_amount` FROM `projects_expense` WHERE `project_id`= ".intval($project_id);
$showexpenses = mysqli_query ($dbc, $getexpenses);
$sums = mysqli_fetch_assoc($showexpenses);
$sum = $sums['sum_amount'];
echo $sum;
We could also have used mysqli_fetch_row
like this:
$getexpenses = "SELECT SUM(`expense_amount`) FROM `projects_expense` WHERE `project_id`= ".intval($project_id);
$showexpenses = mysqli_query ($dbc, $getexpenses);
$sums = mysqli_fetch_row($showexpenses);
$sum = $sums[0];
echo $sum;
The alias is not needed anymore since we know the first column (0) is a match.
NB: you probably also need to GROUP BY project_id
if you want to use SUM()
use
echo $showexpenses;
or
echo "My query is: {$showexpenses}";
Further to Nik's response, PHP treats strings differently based on whether you use Single Quotes or Double Quotes around them.
Single-Quotes interpret text as literal text except for '\'' which would output a single quote mark and '\' which would output a slash mark. For this reason, using single quotes would output your variable name instead of the value.
Examples:
CODE | OUTPUT
-----------------+------------------
echo '\t'; | \t
echo '\r'; | \r
echo '$foo'; | $foo
Double-Quotes interpret certain escape sequences for special characters and also interpret variables. For instance, "\n" ouputs a linefeed and "\r" outputs a carriage return. For this reason, echoing "$myvariable" outputs the value instead of the variable name.
Examples:
CODE | OUTPUT
-----------------+------------------
echo "\t"; | {tab space}
echo "\r"; | {carriage return}
echo "$foo"; | bar
More reading: http://www.php.net/manual/en/language.types.string.php
精彩评论