数据未正确存储在数据库中

时间:2013-01-10 10:43:51

标签: php

我正在使用此代码在数据库中存储值,但是当我选择多个复选框时,只有一个eid值存储在数据库中(应该是我选择的复选框中的no),并且rid值存储为0 哪里出错了? 这是php代码

<?php //insert selected candidate in table                  
                    //echo "checkcandi".$_POST['check_candi']; 
if(isset($_POST['select_candidate']) && logged_in())
{
  $checkcandi_sel = $_POST['check_candi'];
  if(empty($checkcandi_sel)) 
  {
    echo("You didn't select any Candidates.");
  } 
  else
  {
    $N = count($checkcandi_sel);

    echo("You selected $N Candidate(s): ");
    for($i=0; $i < $N; $i++)
    {
      echo($checkcandi_sel[$i] . " ");
      $eid=$checkcandi_sel[$i];
       echo "candi id".$eid;
    }
  }

//$rid=$value[1];
if(logged_in())
    {
    $emplyrid=$_SESSION['uid'];
    echo "emplyrid".$emplyrid;
    }
//$rid=$_GET['rid'];
//var_dump($emplyrid);
$query = "INSERT INTO selected_candidate (
                            eid,rid
                        ) VALUES (
                             '{$eid}','{$emplyrid}'
                        )";
            $result = mysql_query($query, $connection);
            if ($result) {
                $message = "<p style=\"color:green\">The Candidate selected and saved to your my seleted.</p>";
            } else {
                $message = "Sorry job was not applied.";
                $message .= "<br />" . mysql_error();
            }
}


?>

这是复选框的代码

echo "<td><input id=\"select_candi{$i}\" onclick=\"javascript:func(this.id,{$_SESSION['uid']})\" type=\"checkbox\" name=\"check_candi[]\" value=\"{$data_set['eid']}\"/></td>"; 

3 个答案:

答案 0 :(得分:1)

在插入查询附近拉出for循环,试试这个,

$N = count($checkcandi_sel);

if($N > 0) {
  for($i=0; $i < $N; $i++)
  {
    $eid=$checkcandi_sel[$i];
    $query = "INSERT INTO selected_candidate (
                        eid,rid
                    ) VALUES (
                         '{$eid}','{$emplyrid}'
                    )";
    $result = mysql_query($query, $connection);

  }
}

答案 1 :(得分:1)

将sql查询放在foreach ...

if(count($checkcandi_sel) > 0) {
  for($i=0; $i < count($checkcandi_sel); $i++) {
    $eid=$checkcandi_sel[$i];
    $query = "INSERT INTO selected_candidate ( eid,rid) VALUES ('{$eid}','{$emplyrid}' )";
    $result = mysql_query($query, $connection);
  }
}

答案 2 :(得分:0)

您无法将数组添加到数据库

"INSERT INTO selected_candidate (
                            eid,rid
                        ) VALUES (
                             '{$eid}','{$emplyrid}'
                        )"

在此查询中,$ eid将始终包含数组$ checkcandi_sel的最后一个值,您将数组$ checkcandi_sel转换为字符串并添加到数据库

OR

通过循环sql查询将其添加为多个条目。