Page 1 of 1

How to optimize my code?

Posted: Tue Jul 17, 2012 9:34 am
by Alex12345
Hi,
I'm a beginner in PHP.. I started to learn a month ago.

I'm working now on a cartidges store online (Printer inks, Laser and more).

My SQL Database looks like this:

Table - printers_product (each product is linked with a printer)
Id, ProductID, PrinterID

Table - Printers
id,name,imageurl,type, vID (vendorID)

Table - Products
id, name, type, color,price, vID(vendorID) and more..

Table - Vendors
id,name, imageurl, description and more..

Code: Select all

		<?php
$i = 0;
$sql_printer_product = $db->Query("SELECT DISTINCT PrinterId FROM `printers_product` WHERE `ProductId` = '{$product_id}'");
	while($printer_product_row = mysql_fetch_assoc($sql_printer_product)) {
		$printer_id = $printer_product_row['PrinterId']; // takes the printerId
				$sql_printer = $db->Query("SELECT DISTINCT name FROM `printers` WHERE `id` = '{$printer_id}'");
					while($printer_row = mysql_fetch_assoc($sql_printer)) {
						$printer_name = $printer_row['name'];
						if($i % 25 == 0) echo "</div><div style=\"float:right;direction:ltr;width:200px;margin:1em;font-size:11px;\">\n";
						echo "<a href=\"printer.php?pID={$printer_id}\" style=\"text-decoration:none;font-size:11px;\"> {$printer_name} </a> <br />\n";
						$i++;
			}	
				} // end of first while (printerId)
			?>
Basically, I did the 2 whiles - The first one to get the printerID of each product. and the second to get the printerName.

How can I avoid from the 2 whiles and do it on the best side?

thanks.

Re: How to optimize my code?

Posted: Tue Jul 17, 2012 9:44 am
by Celauran
Take a look at JOINs.