2013-08-21 25 views
0

我想讓用戶只插入他們想要插入到表中的信息,並且一些表單域保持空白(如果用戶不需要填充它)。但是,當我嘗試按以下方式插入只有在數據庫表「目錄」中的一些數據:如何通過表單將數據插入數據庫並保留一些表單域爲空?

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); 

它返回我的錯誤:undefined variable.當然,這是需要它在HTML表單內容的值相同的變量我的領域空了。

例如,如果我幾乎完成html格式插入數據在數據庫中,只留下「城市」字段爲空,腳本返回給我錯誤,讓我知道我的$城市變量未定義。換句話說,如何使成功插入數據不需要字段空白?

謝謝!

回答

0

刪除所有if語句,因此即使變量不包含任何數據(即使用戶沒有在該字段中輸入任何信息)也定義了變量。因此,如果用戶沒有輸入自己city,記錄仍然會被插入到catalog表,但與city

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'];} 

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

謝謝大家,人! – natttan

0

插入NULL空值相反:

將代碼更改爲:

$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; 

這樣,即使用戶沒有爲字段輸入任何值,它也會爲NULL,並將作爲NULL插入到數據庫中。這將刪除Undefined variable通知。

0

試試這個:

$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'] : ''; 
相關問題