문제

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.

도움이 되었습니까?

해결책

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

다른 팁

If you read the manual at PHP.net (link), it will show you exactly what to do.

In short, you perform the query using mysql_query (as you did), which returns a Result-Resource. To actually get the results, you need to perform either mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_object on the result resource. Like so:

$res = mysql_query("SELECT something FROM somewhere"); // perform the query on the server
$result = mysql_fetch_array($res); // retrieve the result from the server and put it into the variable $result
echo $result['something']; // will print out the result you retrieved

Please be aware though that you should not use the mysql extension anymore; it has been officially deprecated. Instead you should use either PDO or MySQLi. So a better way to perform the same process, but using for example the MySQLi extension would be:

$db = new mysqli($host, $username, $password, $database_name); // connect to the DB
$query = $db->prepare("SELECT price FROM items WHERE itemId=?"); // prepate a query
$query->bind_param('i', $productId); // binding parameters via a safer way than via direct insertion into the query. 'i' tells mysql that it should expect an integer.
$query->execute(); // actually perform the query
$result = $query->get_result(); // retrieve the result so it can be used inside PHP
$r = $result->fetch_array(MYSQLI_ASSOC); // bind the data from the first result row to $r
echo $r['price']; // will return the price

The reason this is better is because it uses Prepared Statements. This is a safer way because it makes SQL injection attacks impossible. Imagine someone being a malicious user and providing $itemId = "0; DROP TABLE items;". Using your original approach, this would cause your entire table to be deleted! Using the prepared queries in MySQLi, it will return an error stating that $itemId is not an integer and as such will not destroy your script.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top