2015-10-19 56 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