Jump to content

[SOLVED] How do I retrieve a single field from MYSQL?


elitegosu

Recommended Posts

MYSQL version: 5.1.30

 

Hello, I have a small database of 20 product names, how do I tell php to get just ONE of the product names?

 

The following code prints ALL product names in the column:

 

<?php

include("dbconnect.php");
$result = mysql_query("SELECT * FROM products") or die(mysql_error()); 

while ($row = mysql_fetch_array($result)) { 

echo $row['productname'] . "<br />";

} ?>

 

What would be the loop to loop through each single product in the column?

 

 

Hey Maq, thanks for a fast reply. What would be the loop to loop through each individual product name though? For example if I wanted to get the name of the product and create an html page with that product name - productname1.html, productname2.html, productname3.html etc.....

Hey Maq, thanks for a fast reply. What would be the loop to loop through each individual product name though? For example if I wanted to get the name of the product and create an html page with that product name - productname1.html, productname2.html, productname3.html etc.....

 

You wouldn't create a page for each product.  Instead you could list all the products on 1 page with a link that passes that products ID number to another page and then extract the appropriate information.

 

So in your example on the first page, we'll call it product_list.php, you could have:

 

include("dbconnect.php");
$result = mysql_query("SELECT * FROM products") or die(mysql_error()); 

while ($row = mysql_fetch_array($result)) { 

   echo "" . $row['productname'] . "
";

} ?>

 

Which will list all the product names and pass the ID, of what product the user clicks, to product.php.  Therefore only needing 1 page to describe the particular product.

 

And then on product.php, where you could extract information for the desired product (whatever the user clicks on):

 

include("dbconnect.php");
$id = $_GET['id];
$result = mysql_query("SELECT * FROM products WHERE productid = $id") or die(mysql_error()); 

$row = mysql_fetch_array($result);
echo "Product ID: " . $row['productid'] . "
Product Name: " .  $row['productname'];

} ?>

 

I think this is what you're looking for.

It worked! That's exactly what I wanted, thanks a lot! :)

 

Sure no problem.  You should invoke mysql_real_escape_string() on variables that are used in queries to prevent SQL Injections.

 

i.e.:

 

$id = mysql_real_escape_string($_GET['id']);

 

Please mark as [sOLVED] too.  ;)

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.