Jump to content

Looping though a loop


tgavin

Recommended Posts

I have an array of document types that I need to display, and then visually show if that type has been uploaded into the database. The code below works, but it's obviously not ideal. it's probably the best way to show you want I want to accomplish though. I'm trying to find a better, more efficient way of doing this without having to make so many queries.

 

Any thoughts?

 

$types = array('Word','Excel','PDF');

foreach($types as $type) {
   if($db->get_row("SELECT doctype FROM documents WHERE doctype ='$type' AND id = 100")) {
       echo $type.' (uploaded)<br>';
   } else {
       echo $type.'<br>';
   }
}

Link to comment
https://forums.phpfreaks.com/topic/273294-looping-though-a-loop/
Share on other sites

Oh good lord that's not a good method.

 


$types = array('Word','Excel','PDF');

// Construct SQL first
$sql = "SELECT `doctype` FROM `documents` WHERE `doctype` IN (";
foreach($types as $type) 
   $sql.= "'{$type}',";
$sql.= rtrim($sql, ",") . ")";
$sql.= " AND `id` = 100";

// Execute SQL
$data = $db->get_row($sql);

// Now do whatever you want with results.

 

That said why would it return more than 1 row? Surely the ID should be primary or at least unique?

Thanks guys,

 

Those were the first things I tried actually. :)

 

Neither of your examples loop through the $types array and display ALL of the types. I don't want to only display the types that are only in the database, I want to display ALL types, and then highlight the type that's ALSO in the database. it's a checklist to show the user the list of documents, plus what's been uploaded and what hasn't.

 

For instance, let's say PDF and Word are found in the database, my printed result would look like this

 

Word (uploaded)

Excel

PDF (uploaded)

Perhaps something along the lines of this:

 

// Associative array keyed by my Document Types (set each to false to start)
$types = array_fill_keys(array('Word','Excel','PDF'), false);

// Select all doctypes from the database
$sql = 'SELECT doctype FROM documents WHERE doctype IN ("' . 
 implode('","', array_keys($types)) . '")';

// Set the array element to -true- for any doctypes we find
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
   $types[$row['doctype']] = true;
}

 

I used mysql_* functions because I'm not sure what your database object is; but you get the idea.

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.