简体   繁体   中英

How to display field from MySQL?

I'm trying to display a field from my MySQL database. It's in the table tblproducts in the row with the id is set to 1 . And under the column qty .

This is the code I'm using:

<?php 
mysql_connect("localhost","username","password");
mysql_select_db("database_name");
$available = "SELECT qty FROM tblproducts WHERE id = 1";
$result = mysql_query($available);  
echo $result;
?>

However, I keep getting this message: Resource id #2

I've done a bit of research and seen where other people are having similar problems but most of them are trying to display their data in an HTML table whereas I just need the data from 'qty' to display. And of course I'm definitely not a MySQL guru.

Can anyone help me out with this please?

Try changing this:

$result = mysql_query($available);  

To this:

$result = mysql_result(mysql_query($available), 0);  

Let's start from the start. (I'll assume you have the connection set)

Form the query

$query = "SELECT `qty` FROM `tblproducts` WHERE `id` = 1";

Execute the query

$run = mysql_query($query);

Now, put the result in an assoc array

$r = mysql_fetch_array($run);

See the contents of the array

echo $r['qty'];

It's also advised that you move up from mysql to either mysqli, or PDO. PDO is preferred as you're not bound to the MySQL database model.

Try this:

Here you need to generate associative array and then get the resulting row.

$query = "SELECT `qty` FROM `tblproducts` WHERE `id` = 1";
$run = mysql_query($query);
$r = mysql_fetch_array($run);
echo $r['qty'];

- Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM