Validation with the MySQL IF function Jan29 '07
Validation is important when submitting to a database to ensure the integrity of the data.
It's important to validate using as many tools as possible, namely: JavaScript, and a server-side scripting language, such as PHP or ASP.
MySQL can also validate data, using simple IF functions within queries.
For example, here is a traditional approach to validating against blank strings, using PHP:
if ( $_REQUEST["name"] == "" )
{
$name = "Matthom";
}
else
{
$name = $_REQUEST["name"];
}
$query = "SELECT * FROM names WHERE name = '" . $name . "'";
Instead of writing all that code above, you can validate within the SQL query itself:
$query = "SELECT * FROM names WHERE name = IF( '" . $_REQUEST["name"] . "' = '', 'Matthom', '" . $_REQUEST["name"] . "' )";
Here we check to see if $_REQUEST["name"] is empty (equal to ''), and if so, we use the value 'Matthom'. If it's not empty, then we use whatever that value is.
The MySQL IF function uses similar syntax to Excel IF statements.
IF ( expression, value_if_true, value_if_false )
The MySQL IF function is not only limited to simple validation. You can truly empower your queries by using the IF function in many different ways.
Categories: MySQL
, Programming ![]()
Add Feedback (view all)
Leave feedback
matthom
is published and produced by Matt Thommes - an independent publishing enthusiast, mobile blogger, content creator, informative writer, web developer from Chicago.
Never one to conform, Matt intends to promote the effect the web has on our lives, in an effort to intensify, instruct, and clarify all that is happening around us.
Similar Entries
- Install Apache, PHP, MySQL on Windows (185 recent visits)
- MySQL search criteria - column alias (1101 recent visits)
- MySQL integer columns and display width (1131 recent visits)
- MySQL LEFT JOIN syntax (2906 recent visits)
- MySQL viewing saved searches (23 recent visits)
- MySQL changing column types (730 recent visits)
Stats
565 unique visits since August 2008
Recent Referrers (click)
- mysql if example
- mysql validate
- mysql if example
- mysql if +example
- mysql search validation
- MySQL data validation
- mysql if example
- if function mysql
- mysql if example
- mysql if example
- how to validate in mysql
- mysql if functions
- MYSQL IF FUNCTION
- mysql examples if statement
- MYSQL IF EXAMPL
- mysql if statement example
- MySQL IF expression
- mysql if example
- if function in mysql
- mysql if example