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 (169 recent visits)
- MySQL search criteria - column alias (1031 recent visits)
- MySQL integer columns and display width (1060 recent visits)
- MySQL LEFT JOIN syntax (2724 recent visits)
- MySQL viewing saved searches (22 recent visits)
- MySQL changing column types (686 recent visits)
Stats
517 unique visits since August 2008
Recent Referrers (click)
- if else examples in mysql?
- if else examples in mysql?
- mysql if example
- MYSQL length + if
- mysql + if example
- mysql if example
- mysql if example
- MySQL syntax validation function
- mysql if example
- mysql if statement
- IF(,,)mysql example
- mysql if example
- mysql function if then examples
- if cause mysql example
- example IF statement with MySQL
- mysql syntax validator
- mysql if else function
- examples of if function
- examples of the if function
- mysql if functions