PHP Example

From #mysql Freenode

PHP Example #2 Prepared by: seekwill

Just a sample of code I made for a person in #mysql. Thought I'd share. Go ahead and modify if needed ;)

This sample demostrates how you can create a dynamic query in PHP.

<?php

// Make the query
$query = "SELECT * FROM table WHERE 1";


// If the user supplied an ID number...
if( isset( $_GET['id'] ) ){
	
	// Assign id number to a variable
	$user_supplied_id = $_GET['id'];
	
	// Check the id is a number
	if( is_numeric( $user_supplied_id) ){
		// Concat id to query
		$query = $query . " AND id = $user_supplied_data";
	} else {
		die( "NOT A NUMBER! DIE YOU HACKER!" );
	}
}


// If the user supplied search critera...
if( isset( $_GET['search'] ) ){
	
	// Assign searchstring to a variable
	$user_supplied_search = $_GET['search'];
	
	// Check the search string is less than  20 chars because that's only how big it is
	if( strlen( $user_supplied_search ) < 20 ){
		
		// Escape funny chars
		$user_supplied_search_clean = mysql_real_escape_string( $user_supplied_search );
		
		// Concat search string to query
		$query = $query . " AND search LIKE '%$user_supplied_search_clean%'";
	} else {
		die( "STRING TOO LONG! DIE YOU HACKER!" );
	}
}


$result = mysql_query( $query ) or die( mysql_error() . ' ' . $query );


?>