17.3 Executing a Query and Getting the Results


You want to execute a query and get back the relevant results in an array for easy processing and extraction.

Technique

Use ldap_list() for a quick, single-level search. You can then use the ldap_get_entries() function to extract the results into an array:

 <?php // connect and bind $lh = ldap_connect("localhost")     or die("Cannot connect to LDAP server"); ldap_bind($lh) or die("Cannot Bind"); // perform query $sth = ldap_list($lh,"o=Sterling's Company, c=US","cn=S*"); if (!$sth) {     die(sprintf("Error [%d]: %s",                 ldap_errno($lh), ldap_error($lh))); } $entries = ldap_get_entries($lh, $sth); //  loop and print for ($idx = 0; $idx < $entries["count"]; $idx++) {     print "The distinguished name (dn) is: {$entries[$idx]}\n<br>\n";     print "The common name (cn) of the first entry is:";     pri {$entries[$idx]['cn'][0]}";     print "\n<br>\n"; } // Close the connection ldap_close($lh); ?> 

Comments

In this example, we use the ldap_list() function in conjunction with the ldap_get_ entries() function to perform a search query and then load the results into an array that we then process using a for loop. It is important to note that we do not specify a maximum value in the for loop by the standard "count($entries) ", but rather use the special "count" element of the associative array, which accurately gives the number of matching results.

Note that we search the directory at only a single level. If you want to search entire LDAP directory subtrees, see recipe 17.5.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net