2016-04-09 81 views
-1

我想根據用戶選擇使用if else語句插入到兩個不同的表中。使用單選按鈕插入數據和if else語句

我有兩個單選按鈕:

   <label for="radioBtn">Back to me</label> <input type="radio" name="radioBtn" id="radioBtn1" value=1 /></br></br> 
      <label for="radioBtn">Direct to recipient</label> <input type="radio" name="radioBtn" id="radioBtn2" value=0 /></br></br> 

我的PHP如下:

$selection = $_POST["radioBtn"]; 

    if ($selection==0) { 
    $sql = "INSERT INTO user_address (user_ID, first_name, last_name, address_line1, address_line2, town, county, postcode) VALUES ($user_ID, '$_POST[first_name]', '$_POST[last_name]', '$_POST[address_line1]', '$_POST[address_line2]', '$_POST[town]', '$_POST[county]', '$_POST[postcode]')"; 
} else if ($selection==1) { 
    $sql = "INSERT INTO recipient_address (user_ID, first_name, last_name, address_line1, address_line2, town, county, postcode) VALUES ($user_ID, '$_POST[first_name]', '$_POST[last_name]', '$_POST[address_line1]', '$_POST[address_line2]', '$_POST[town]', '$_POST[county]', '$_POST[postcode]')"; 
} 

目前只會更新user_address列,即使用戶選擇了「直接收件人「單選按鈕。

+0

您使用布爾同時檢查'如果($選擇== 0)'和'如果($選擇== 1)'你的值是0和1.你需要檢查它是否是一個字符串。 I.e .:「if($ selection ==」0「)'。你也應該引用你的價值觀。此外,使用'isset()'這會更好,而不是你現在使用的。 –

+0

@ Fred-ii-'「1」== 1'工作得很好。如果你想檢查類型,請使用'===' – rjdown

+0

'直接收件人'單選按鈕的值爲0;但是你的代碼使用'$ selection == 0'來運行'user_address'更新。 – andrewsi

回答

0

您的問題在於您的表單中的屬性值。您必須始終使用引號。 使用isset進行最佳實踐。

PHP:

if (isset($_POST['submit'])) { 

    // Get the value 
    $selection = $_POST["radioBtn"]; 

    // Init your statements 
    $sql1 = "Your first sql statement"; 
    $sql2 = "Your second sql statement"; 

    // Make the logic 
    if ($selection == 0) { 
     $sql = $sql1; 
    } else if ($selection == 1) { 
     $sql = $sql2; 
    } 

    // Debug Code 
    echo $sql; 
} 

HTML:

<form method="post" action="test.php"> 
    <label for="radioBtn">Back to me</label> 
    <input type="radio" name="radioBtn" id="radioBtn1" value='1' /></br></br> 

    <label for="radioBtn">Direct to recipient</label> 
    <input type="radio" name="radioBtn" id="radioBtn2" value='0' /></br></br> 

    <button type="submit" name="submit">Submit</button> 
</form>