2015-10-19 61 views
1

好的。所以我有一個應該得到用戶信息的表單,包括應該存儲在數組中以允許多個選擇的種族信息,但是它也應該是可選的,以便沒有人有義務做出任何選擇PHP:ARRAY中的NULL值作爲字符串存儲在表中

輸入頁面 人種(選擇所有適用):

<input type="checkbox" name="ethnicity[]" value="Indian"> American Indian or Alaska Native<br> 
    <input type="checkbox" name="ethnicity[]" value="Asian"> Asian<br> 
    <input type="checkbox" name="ethnicity[]" value="African-American"> Black or African-American<br> 
    <input type="checkbox" name="ethnicity[]" value="Pacific"> Native Hawaiian or other Pacific Islander<br> 
    <input type="checkbox" name="ethnicity[]" value="White"> White<br> 
我的過程數據頁一切

然後存儲到變量

$email = filter_input (INPUT_POST, 'email'); 
$passwordUser = filter_input (INPUT_POST, 'passwordUser'); 
$phone = filter_input (INPUT_POST, 'phone'); 

$sex = filter_input (INPUT_POST, 'sex'); 
if ($sex == NULL) { 
    $sex = 'unknown'; 
} 

$age = filter_input (INPUT_POST, 'age'); 
$state = filter_input (INPUT_POST, 'state'); 

$ethnicity = filter_input (INPUT_POST, 'ethnicity', FILTER_SANITIZE_SPECIAL_CHARS, FILTER_REQUIRE_ARRAY); 
if ($ethnicity !== NULL) { 

} else { 
    'No answer selected.'; 
} 
include 'insertData.php'; 

和所有的insertData頁信息將被插入到表格中。

include 'database.php'; 

try { 
$query = "INSERT INTO accounts 
      (ageGroup, emailAddress, gender, password, phoneNumber, stateAbbr) 
      VALUES 
      (:ageGroup, :emailAddress, :gender, :passwordUser, :phoneNumber, :stateAbbr)"; 

$statement = $db->prepare($query); 
$statement->bindValue(':ageGroup', $age); 
$statement->bindValue(':emailAddress', $email); 
$statement->bindValue(':gender', $sex); 
$statement->bindValue(':passwordUser', $passwordUser); 
$statement->bindValue(':phoneNumber', $phone); 
$statement->bindValue(':stateAbbr', $state); 
$statement->execute(); 
$statement->closeCursor(); 


foreach ($ethnicity as $result) { 
    $query = "INSERT INTO customerethnicity 
      (emailAddress, ethnicity) 
      VALUES 
      (:emailAddress, :ethnicity)"; 

    $statement = $db->prepare($query); 
    $statement->bindValue(':ethnicity', $result); 
    $statement->bindValue(':emailAddress', $email); 
    $statement-> 
    execute(); 
    $statement->closeCursor(); 
} 
echo "Account created successfully!"; 
    } catch (PDOException $e) { //Catches and handles db errors to prevent site crash 

    $title = 'Error'; 
    $caption = 'System message:'; 
    $message = $e->getMessage() . '<br><br> An error has occurred. Please check the information entered and try again.'; 

    include 'Database_error.php'; 

數據庫使用的電子郵件和電子郵件和種族上專門針對種族設計了表一起創建新行鏈接兩個表。另一個表存儲其餘的信息。一切都基本正常。我可以將性別空白並在表中存儲「未知」,但是我不能將種族框未選中並在表中插入類似「未知」值而不是NULL,但不會收到此消息:

警告:在C的foreach()提供參數無效:\ XAMPP \ htdocs中\ FORMDATA \ insertData.php上線26

Account created successfully! 

這是在線路26:foreach ($ethnicity as $result) {

成功創建的帳戶測試儀消息彈出p,如果我在表格中查看,我可以看到輸入的所有其他信息顯示在帳戶表中,但沒有顯示在客戶關係表中。如果我填寫信息,或者即使我留下其他值爲空,並且只選擇一個或多個種族,那麼一切正常。問題是沒有選擇任何種族。我需要有一個值表示沒有選擇任何東西。

+0

問題:如果只選擇了一個種族:它仍然是一個數組嗎? – Thomas

+0

如果僅選擇1,則它會在customerethnicity表中正確顯示,並且電子郵件和一個選擇都出現在同一行中。如果有多個選擇,那麼有多個行共享相同的電子郵件。問題在於,如果沒有選擇,所有東西仍然運行,但我收到警告消息,並且在該表中沒有任何類型的輸入。另一個很好。 – Kr4ckl3s

回答

0

Appologies的延遲,但最終,我結束了使用的解決方案是這樣的:

$ethnicity = filter_input (INPUT_POST, 'ethnicity', FILTER_SANITIZE_SPECIAL_CHARS, FILTER_REQUIRE_ARRAY); 
if ($ethnicity !== NULL) { 


} else { 
    $ethnicity = array('unknown'); 
} 
include 'insertData.php'; 
?> 

發佈此信息可能會證明對其他人有益。

0

有如果條件未設置的情況下,該複選框來添加ID,並有類似的東西:
if (document.getElementById('yourCheckBoxID').checked) { alert("checked"); } else { alert("Please check"); }

+0

「,但它也應該是可選的,以便沒有人有義務做出任何選擇」 – VolkerK

+0

@VolkerK嗯,在這種情況下,我認爲他需要的Radibuttons組而不是Checkboxes。 –

+0

使用單選按鈕,因爲有些人識別多個種族,而那些希望識別它的人必須是一種選擇。這意味着可以選擇不選擇少數族羣或選擇一個或多個族羣。單選按鈕不提供這種靈活性。這就是爲什麼它在foreach循環內。這樣,如果選擇了多個選擇,每個選擇都可以附加到單個行上的相同用戶電子郵件。 – Kr4ckl3s

0

你可以簡單地測試$ethnicity是否「是」試圖重複之前的數組。

if (is_array($ethnicity)) { 
    $query = ' 
     INSERT INTO customerethnicity 
      (emailAddress, ethnicity) 
     VALUES 
      (:emailAddress, :ethnicity) 
    '; 

    $statement = $db->prepare($query); 
    $statement->bindParam(':ethnicity', $result); 
    $statement->bindParam(':emailAddress', $email); 

    foreach ($ethnicity as $result) { 
     $statement->execute(); 
     ... 

sscce

<?php 
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false, 
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false, 
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION 
)); 
setup($pdo); // creating temporary tables for the example 

// the array is more or less what you got from your filter_input script 
// doInsert will extract it, so the code in that function looks like your second script 
doInsert($pdo, array(
    'age'=>'21-39', 
    'email'=>'emailA', 
    'sex'=>'m', 
    'passwordUser'=>'1234', 
    'phone'=>'5678', 
    'state'=>'neverneverland', 
    'ethnicity'=>['de','fr','au'] 
)); 

doInsert($pdo, array(
    'age'=>'80+', 
    'email'=>'emailB', 
    'sex'=>'m', 
    'passwordUser'=>'abcd', 
    'phone'=>'9876', 
    'state'=>'midleearth', 
    'ethnicity'=>null 
)); 

// example for querying the data 
// not sure if that's a really good way to do it; but ...just an example ;-) 
showUser($pdo, 'emailA'); 
showUser($pdo, 'emailB'); 

function doInsert($db, $params) { 
    extract($params); 

    try { 
     $db->beginTransaction(); // that should answer your second question, see http://docs.php.net/pdo.transactions 
     $query = " 
      INSERT INTO soFoo 
       (ageGroup, emailAddress, gender, password, phoneNumber, stateAbbr) 
      VALUES 
      (:ageGroup, :emailAddress, :gender, :passwordUser, :phoneNumber, :stateAbbr) 
     "; 
     $statement = $db->prepare($query); 
     $statement->bindValue(':ageGroup', $age); 
     $statement->bindValue(':emailAddress', $email); 
     $statement->bindValue(':gender', $sex); 
     $statement->bindValue(':passwordUser', $passwordUser); 
     $statement->bindValue(':phoneNumber', $phone); 
     $statement->bindValue(':stateAbbr', $state); 
     $statement->execute(); 
     $statement->closeCursor(); 

     if (is_array($ethnicity)) { 
      $query = ' 
       INSERT INTO soBar 
        (emailAddress, ethnicity) 
       VALUES 
        (:emailAddress, :ethnicity) 
      '; 

      $statement = $db->prepare($query); 
      $statement->bindParam(':ethnicity', $result); 
      $statement->bindParam(':emailAddress', $email); 

      foreach ($ethnicity as $result) { 
       $statement->execute(); 
      } 
     } 

     $db->commit(); 
    } 
    catch(Exception $e) { 
     $db->rollBack(); 
     throw $e; 
    } 
} 

function showUser($db, $email) { 
    $statement = $db->prepare(' 
     (
      SELECT 
       ageGroup,gender,stateAbbr 
      FROM 
       soFoo 
      WHERE 
       emailAddress=:e1 
     ) 
     UNION ALL 
     (
      SELECT 
       ethnicity,null,null 
      FROM 
       soBar 
      WHERE 
       emailAddress=:e2 
     ) 
    '); 
    $statement->bindValue(':e1', $email); 
    $statement->bindValue(':e2', $email); 
    $statement->execute(); 

    $user = $statement->fetch(); 
    if (!$user) { 
     echo 'no user with email=', $email, "\r\n"; 
    } 
    else { 
     printf("%s %s %s\r\n", $user['ageGroup'], $user['gender'], $user['stateAbbr']); 
     $eth = $statement->fetch(); 
     if (!$eth) { 
      echo ' unknown ethnicity'; 
     } 
     else { 
      do { 
       echo ' ', $eth['ageGroup'], "\r\n"; 
      } 
      while(($eth=$statement->fetch())); 
     } 
    }  
} 


function setup($pdo) { 
    $pdo->exec(' 
     CREATE TEMPORARY TABLE soFoo (
      id int auto_increment, 
      ageGroup varchar(32), 
      emailAddress varchar(32), 
      gender varchar(32), 
      password varchar(32), 
      phoneNumber varchar(32), 
      stateAbbr varchar(32), 
      primary key(id), 
      unique key(emailAddress) 
     ) 
    '); 

    $pdo->exec(' 
     CREATE TEMPORARY TABLE soBar (
      id int auto_increment, 
      emailAddress varchar(32), 
      ethnicity varchar(32), 
      primary key(id), 
      unique key(emailAddress, ethnicity) 
     ) 
    '); 
} 

打印

21-39 m neverneverland 
    au 
    de 
    fr 
80+ m midleearth 
    unknown ethnicity 
+0

是否允許我實際上將一個字符串放入表中以代替NULL,以便爲電子郵件附加條目以顯示沒有進行選擇? – Kr4ckl3s

+0

@VolkerK insert語句不應該在foreach之後? – Thomas

+0

是的,當您查詢種族並且沒有記錄被返回時,請添加您喜歡的任何字符串。如果您使用JOIN在一個查詢中查詢所有表中的數據,請使用LEFT JOIN並在種族字段中檢查NULL值。 – VolkerK

0

可以使用

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

    foreach ($ethnicity as $result) { 

    .... 
    } 
} 
+1

有點解釋會很好。 – MaggsWeb