質問

I want to enable users to insert only information they want to insert into table, and some form fields to stay empty (if user doesn't have need to fill it). But when I try to insert only some data in db table "catalog" in the following way:

if (!empty($_POST['name'])){ $name = $_POST['name'];}
if (!empty($_POST['city'])){ $city = $_POST['city'];}
if (!empty($_POST['country'])){ $country= $_POST['country'];}
if (!empty($_POST['year'])){ $year = $_POST['year'];}

$sql = "INSERT INTO catalog(name,city,country,year)VALUES('$name','$city','$country','$year')";
mysql_query($sql);

it returns me error: undefined variable. Of course, it is the same variable that take it's value from content in html form field I lefted empty.

For example if I almost complete html form for inserting data in db, and left only "city" field empty, script returns me error letting me know that my $city variable is not defined. In other words, how to make fields emptiness unnecessary for successful inserting data?

Thanks!

役に立ちましたか?

解決

remove all the if statements therefore you define the variables even if the variable contains no data as in even if the user did not enter any information into that field. Therefore, if the user does not enter their city, the record would still be inserted into the catalog table but with an empty value for city

from

if (!empty($_POST['name'])){ $name = $_POST['name'];}
if (!empty($_POST['city'])){ $city = $_POST['city'];}
if (!empty($_POST['country'])){ $country= $_POST['country'];}
if (!empty($_POST['year'])){ $year = $_POST['year'];}

to

$name = $_POST['name'];
$city = $_POST['city'];
$country= $_POST['country'];
$year = $_POST['year'];

他のヒント

try this:

$name = (isset($_POST['name']) && !empty($_POST['name'])) ? $_POST['name'] : '';
$city = (isset($_POST['city']) && !empty($_POST['city'])) ? $_POST['city'] : '';
$country = (isset($_POST['country']) && !empty($_POST['country'])) ? $_POST['country'] : '';
$year = (isset($_POST['year']) && !empty($_POST['year'])) ? $_POST['year'] : '';

Insert NULL instead:

Change your code to:

$name = !empty($_POST['name']) ? $_POST['name'] : NULL;
$city = !empty($_POST['city']) ? $_POST['city'] : NULL;
$country = !empty($_POST['country']) ? $_POST['country'] : NULL;
$year = !empty($_POST['year']) ? $_POST['year'] : NULL;

That way, even if the user didn't input any values for a field, it'll be NULL and will be inserted into your database as NULL. This will remove the Undefined variable notices.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top