Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sending your query to MySQL in 3 lines

Retrieving Data

Sending your query to MySQL in 3 lines

by  Glowball  Posted    (Edited  )
This involves one script to be used throughout your site (and included on pages that need it). You'll have three lines on your page to send the SQL and get the recordset.
Code:
---------------------------------------------
sendquery.php
---------------------------------------------

define("SQL_HOSTNAME", "myhost");
define("SQL_USERNAME", "myusername");
define("SQL_PASSWORD", "mypassword");
define("SQL_DATABASE", "mydatabase");
$logpath = "/path/to/a/writable/directory/errorlog.txt";
$exitMsg = "<p>Sorry, this utility is currently unavailable.  Please <a href='mailto:webmaster@yoursite.com'>email the Webmaster</a> for more information.</p>";

function exitOut($logMsg,$logpath,$exitMsg) {
	error_log($logMsg . chr(13) . chr(10), 3, $logpath);
	echo $exitMsg;
	exit();
	}

if (isset($query)) {	
	if (!mysql_pconnect(SQL_HOSTNAME,SQL_USERNAME,SQL_PASSWORD)) exitOut(chr(10) . "Unable to connect to " . SQL_HOSTNAME,$logpath,$exitMsg);
	if (!mysql_select_db(SQL_DATABASE)) exitOut(chr(10) . "Unable to select database '" . SQL_DATABASE,$logpath,$exitMsg);
	
	if (!isset($queryname)) $queryname = "recordset";
	if (!$$queryname = mysql_query($query)) exitOut(chr(10) . "Database query failed: " . $query,$logpath,$exitMsg);
	}
else {
	exitOut(chr(10) . "The 'query' variable was not passed to sendquery.php",$logpath,$exitMsg);
	}	

---------------------------------------------
yourfile.php
---------------------------------------------

$query = "SELECT * FROM mytable";
$queryname = "getInfo";
include "/your/directory/structure/sendquery.php";

while ($info = mysql_fetch_array($getInfo)) {
    ...
    }
You can call that three-line block repeatedly in the same file without issues. It has very basic error message display but it wouldn't be difficult to add some Look & feel to it.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top