January 31, 2008

DIY Quick and Dirty MySQL query tool with PHP

We all love phpmyadmin it’s a great tool for managing databases, but it’s nice to have a web based query tool that you can allow others to access where they can get and save a query as a bookmark, and not endanger your database security too much. This is a quick and dirty way to write up a query tool that you can use over and over.

//Function to get current time
function getmicrotime(){
@list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}

//Implementation like this
$start = getmicrotime();
print('
');
print('');
print('');
print('
'); print('

SQL Queries against MySQL database

'); //Set a default query if no query was specified if (isset($_GET['query'])) { $sql = $_GET['query']; $sql = stripslashes($sql); if(strtoupper(substr($sql, 0, 6)) == 'SELECT' ||strtoupper(substr($sql, 0, 4)) == 'SHOW' || strtoupper(substr($sql, 0, 7)) == 'EXPLAIN'){ $sql = $sql; }else{ echo "Query Failed. Your query must begin with SELECT, SHOW, OR EXPLAIN. "; exit(); } }else{ $sql="SELECT * FROM tablename LIMIT 20"; } //Connect and select database $link = mysql_connect('localhost', 'database_user', 'password') or die("Connection Failed"); mysql_select_db(track) or die("DB Select Failed"); //Run query $result = mysql_query($sql, $link) or die("Query Failed.\n " . mysql_error()); print('
'); print('Enter your SQL Statement:'); print('
'); print('
'); print('
'); print(''); print('
'); print('
'); //links to resources here... print(' '); print(' '); print('
'); $numfields = mysql_num_fields($result); $numrows = mysql_num_rows($result); print('
'); print('
'); print('Query results: ' . $numfields . ' field(s), ' . $numrows . ' row(s)'); print('
'); print('
'); //Table to display results----------------------- print(' '); print(' '); for ($i=0; $i < $numfields; $i++){ $tablename = mysql_field_name($result, $i); print(' '); } print(' '); //end header row $j = 0; // initialize for modulo... while( $row=mysql_fetch_row($result)){ $j++; print(' '); for ($i=0; $i < $numfields; $i++){ if($j % 2){ // I'm in an even row $c = ""; }else{ // I'm in an odd row $c = "class=d"; } print(' '); } print(' '); } //end while loop print('
' . $tablename . '
' . $row[$i] . '
'); mysql_free_result($result); $end = getmicrotime(); echo '

Operation took: '.($end-$start).' seconds

'; print(' Back to the main menu '); print('
'); print('
'); print('');

Leave a comment