查询结果与PHP变量的绑定

时间:2019-06-04 19:11:03

标签: php mysql sql

我有一个简单的查询,可以找到名为permanent_employee的表的平均工资:

SELECT  AVG(E.salary) 
FROM employee as E,permanent_employee as P
WHERE E.empID=P.empID

我想将其绑定到一个PHP变量。如果返回薪水,我将像这样echo "<td>{salary}</td>";将其绑定,一切都会正常运行。但是echo "<td>{$AVG(E.salary)}</td>";却给了我错误。我可以使该查询返回一个变量,该变量以后可以覆盖到PHP形式吗?

更新: 解决方案是使用AVG(E.salary)AS sth

2 个答案:

答案 0 :(得分:1)

您需要一个适当的别名

SELECT  AVG(E.salary)  my_avg 
FROM employee as E,permanent_employee as P
WHERE E.empID=P.empID


echo "<td>{$my_avg}</td>";

答案 1 :(得分:1)

有多种方法可以将其提取到php变量

$result = mysqli_query($con,"SELECT  AVG(E.salary)  my_avg 
FROM employee as E,permanent_employee as P
WHERE E.empID=P.empID");
$row = mysqli_fetch_array($result));
$avg = $row['my_avg'];
echo "<td>".$avg."</td>";

您也可以使用PDO,请参见Get results from from MySQL using PDO