Skip to content

Instantly share code, notes, and snippets.

@maclochlainn
Created February 2, 2013 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maclochlainn/4699277 to your computer and use it in GitHub Desktop.
Save maclochlainn/4699277 to your computer and use it in GitHub Desktop.
This is a reusable artifact that lets you query a COMMON_LOOKUP table from a MySQL Server database. It requires that you create an include file with your valid database credentials.
<?php
/*
|| Program Name: library.inc
*/
function get_common_lookup($table_name, $column_name, $lookup_key = 0) {
// Include the credentials file if omitted.
include_once("MySQLCredentials.inc");
// Define return string.
$out = '';
// Assign credentials to connection.
$mysqli = new mysqli(HOSTNAME, USERNAME, PASSWORD, DATABASE);
// Check for connection error and print message.
if ($mysqli->connect_errno) {
print $mysqli->connect_error."<br />";
print "Connection not established ...<br />";
}
else {
// Initial statement.
$stmt = $mysqli->stmt_init();
// Declare a static query.
$sql = "SELECT cl.common_lookup_id\n"
. ", cl.common_lookup_meaning\n"
. "FROM common_lookup cl\n"
. "WHERE common_lookup_table = ?\n"
. "AND common_lookup_column = ?\n"
. "ORDER BY 2";
// Prepare statement.
if ($stmt->prepare($sql)) {
$stmt->bind_param("ss",$table_name,$column_name); }
// Loop through a result set until completed.
do {
// Attempt query and exit with failure before processing.
if (!$stmt->execute()) {
// Print failure to resolve query message.
print $mysqli->error."<br />";
print "Failed to resolve query ...<br />";
}
else {
// Fetch a row for processing.
$result = $stmt->get_result();
if ($lookup_key == 0) { // Use when value is unset or zero.
$out .= "<option class=dropDown value='' selected>Select Type &nbsp;&nbsp;&nbsp;&nbsp;</option>"; }
else { // Use when value isn't unset or zero.
$out .= "<option class=dropDown value=''>Select Type &nbsp;&nbsp;&nbsp;&nbsp;</option>"; }
// Read through the rows of the array.
while( $row = $result->fetch_array(MYSQLI_NUM) ) {
if ($lookup_key == $row[0]) { // Use when the lookup key matches the surrogate key value.
$out .= "<option class=dropDown value='".$row[0]."' selected>".$row[1]."</option>"; }
else { // Use when the lookup key fails to match the surrogate key value.
$out .= "<option class=dropDown value='".$row[0]."'>".$row[1]."</option>"; }
}
}
} while( $stmt->next_result());
// Release connection resource.
$mysqli->close(); }
// Return the string.
return $out;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment