How to optimize my code?

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
Alex12345
Forum Newbie
Posts: 1
Joined: Tue Jul 17, 2012 9:18 am

How to optimize my code?

Post 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.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How to optimize my code?

Post by Celauran »

Take a look at JOINs.
Post Reply