tags:

views:

41

answers:

2

Hi,

I am building up a site in PHP which takes input of more than 20 fields from user. Hardly 3-4 field values are compulsory, rest can be left blank. I want to display a custom error message instead of blank or zero or null while displaying these values. How can this be done? I am using MySQL as backend.

A: 
<?php

$var1 = 'Foo';
$var2 = '';
$var3 = NULL;

echo ( ! empty($var1)) ? $var1 : 'Not set!'; // Foo
echo ( ! empty($var2)) ? $var2 : 'Not set!'; // Not set!
echo ( ! empty($var3)) ? $var3 : 'Not set!'; // Not set!

/**
 * Alternative function solution based on OP's comment:
 */

function output($str)
{
    echo ( ! empty($str)) ? $str : 'Not set!';
    return TRUE;
}

output($var1); // Foo
output($var2); // Not set!
output($var3); // Not set!
chigley
Is there any other solution so that just one function makes all null values an error message, instead of doing it for all variables
Sanket Raut
There's lots of ways to do it. I've edited my answer above so it uses a custom function called `output()` to echo the handed variable (if not empty) or echo `Not set!` otherwise.
chigley
You could also change the function to return the variable you hand to it, incase you don't want to echo straight away.
chigley
I want just 4 lines of function code so that whenever any null value is encountered it automatically displays an error.
Sanket Raut
What? I don't understand you... maybe edit your original question to include some code so I have more idea what you're on about?
chigley
Could whoever it was explain the -1 please? What I did wrong? How I could improve? My answer does exactly what (I think) the OP wanted and I even added a second way after the OP's comment...
chigley
A: 

I assume you use the $_POST array.

In that case you could just do:

$errors = array();
foreach($_POST AS $key => $value) {
    if(empty($value)) {
        $_POST[$key] = "Custom error message"; // Or place it in an apart array like:
        $errors[$key] = "Custom error message";
    }
}

You can also choose to print the message to the screen immediately. That's up to you.

Besides, did you ever consider a Validation library like:

http://kohanaframework.org/guide/security.validation

Good luck!

Stegeman