Search code examples
phpmysqldatabasevariablesassign

Assign MySQL database value to PHP variable


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'");

However, its echo returns:

Resource id #5 

instead a value like like:

59.95

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.

Thanks in advance.


Solution

  • You will need to fetch data from your database

    $price = mysql_query("SELECT price FROM products WHERE product = '$product'");
    $result = mysql_fetch_array($price);
    

    Now you can print it with

    echo $result['price'];
    

    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