Quick Question with Rendering MySQL output to edit in a form

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gymrat23
Forum Newbie
Posts: 2
Joined: Mon Jul 25, 2011 7:42 pm

Quick Question with Rendering MySQL output to edit in a form

Post by gymrat23 »

Im coding a form to upload items into MySQL database, everything works fine except when i click "edit" (to change details with that item) the data doesnt render in the form...

Code: Select all

<?php 
// Gather this product's full information for inserting automatically into the edit form below on page
if (isset($_GET['pid'])) {
$targetID = $_GET['pid'];
    $sql = mysql_query("SELECT * FROM products WHERE id='$targetID' LIMIT 1");
    $productCount = mysql_num_rows($sql); // count the output amount
    if ($productCount > 0) {
	    while($row = mysql_fetch_array($sql)){ 
             
			 $product_name = $row["product_name"];
			 $price = $row["price"];
			 }
    } else {
	    echo "Item doesnt exist!";
		exit();
    }
}
?>

Thanks very much.
B
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Quick Question with Rendering MySQL output to edit in a

Post by twinedev »

First, you state it doesn't render, does this mean that you are not getting the "Item doesn't exist" error?

Some notes on your coding:

If the Product ID is an integer, you should use the following line to protect against SQL injections:

Code: Select all

$targetID = (int)$_GET['pid'];
this forces it to be numeric.

if they are not all integers, then do the following to protect it:

Code: Select all

$targetID = mysql_real_escape_string($_GET['pid']);
For better readability, instead of :

Code: Select all

$sql = mysql_query(...)
use something like:

Code: Select all

$rsProduct = mysql_query(...)
since mysql_query will return a resource identifier (or FALSE on failure), and $SQL is generally used for the variable that contains the actual SQL statement.

Also, since you are limiting the result to a single row, there is really no need to program in a while loop, just do:

Code: Select all

    if ($productCount > 0) {
            $row = mysql_fetch_assoc($rsProduct);
            $product_name = $row['product_name'];
            $price = $row['price'];
    } else {
Or even:

Code: Select all

    if ($productCount > 0) {
            $product_name = mysql_result($rsProduct,0,'product_name');
            $price = mysql_result($rsProduct,0,'price');
    } else {
Just some tips to help you clean up the code a tad bit :-)
Post Reply