Jump to content

is there a better way to query this?


glennn.php

Recommended Posts

i'm calling about 350 records from a table all at once and displaying the results in different areas of the page:

 

$sql = "select id, makeid, model from models order by model asc";
	$rs = mysql_query($sql);
$acura =  "";
$audi =  "";
$bmw=  "";

// and so on...

	while ($row = mysql_fetch_array($rs)) {
		$makeid = $row['makeid'];
		$checkbox = "<input type=\"checkbox\" name=\"model\" value=\"".$row['id']."\">".$row['model']." ";

		switch ($makeid) {
			case '1' : $acura .= $checkbox;
			break;
			case '3' : $audi .= $checkbox;
			break;
			case '4' : $bmw .= $checkbox;
			break;
// and so on...

		}

	}
		echo $acura;	
		echo "<br />";
		echo $audi;
		echo "<br />";
		echo $bmw;

// and so on...

 

this works, but i can't help but think there's a more efficient way to do this.

 

anyone?

 

thanks much.

GN

Link to comment
https://forums.phpfreaks.com/topic/203030-is-there-a-better-way-to-query-this/
Share on other sites

$query = 'SELECT id, makeid, make, model
  FROM models
  JOIN make ON make.id = models.makeid
  ORDER BY make ASC, model ASC';
$result = mysql_query($query);

$make = '';
while ($row = mysql_fetch_assoc($result)) {
  if ($make !== $row['make']) {
    echo '<h3>', $make = $row['make'], '</h3>';
  }
  echo '<label for="model', $row['id'], '">', $row['model'], '</label>',
       '<input type="checkbox" id="model', $row['id'], '" name="model" value="', $row['id'], '">';
}

 

Outputs:

 

<h3>Acura</h3>
<label for="model1">Acura model #1</label>
<input type="checkbox" id="model1" name="model" value="1">
2..
3..
<h3>Audi</h3>
..

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.