将MySQL数据库值分配给PHP变量 [英] Assign MySQL database value to PHP variable
问题描述
我有一个包含产品和价格的MySQL数据库表. 虽然是html格式,但我在某个php文件中获得了产品名称. 对于此文件中的操作,我还需要相应的价格.
I have a MySQL Database Table containing products and prices. Though an html form I got the product name in a certain php file. For the operation in this file I want to do I also need the corresponding price.
在我看来,以下内容足以说明问题:
To me, the following looks clear enough to do it:
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
但是,它的回声返回:
Resource id #5
而不是像这样的值:
59.95
似乎还有其他选择,例如 mysqli_fetch_assoc mysqli_fetch_array 但是我不能让他们输出任何有意义的东西,也不知道该使用哪个.
There seem to be other options like mysqli_fetch_assoc mysqli_fetch_array But I can't get them to output anything meaningful and I don't know which one to use.
谢谢.
推荐答案
您将需要从数据库中获取数据
You will need to fetch data from your database
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
$result = mysql_fetch_array($price);
现在您可以使用
echo $result['price'];
作为旁注,我建议您切换到 mysqli
> ,因为 mysql_*
api已被弃用,很快就会不再需要
As side note I would advise you to switch to either PDO
or mysqli
since mysql_*
api are deprecated and soon will be no longer mantained
这篇关于将MySQL数据库值分配给PHP变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!