在mysql插入stement

时间:2017-02-13 15:19:49

标签: php mysql

我有两张桌子:

persons(person_id, date_entered, first_name, country_id)

countries(country_id, country_name)

来自国家/地区的Country_id是country_id in person中的外键。

我有一个POST表格,询问人名和国籍,然后将信息输入人员表。国籍字段是来自国家/地区表的查找,并向用户显示国家/地区名称的下拉列表。提交按钮会将数据发送到人员表。

问题是,国籍下拉列表会产生一个国家/地区名称,但实际上我必须将这些国家/地区的ID发送到人员表中。我想我需要从countries表中提取数据并将country_name与国籍字段匹配,然后提取id但不确定......

最后问题是,如何将下拉列表中的国家/地区名称与其ID匹配,并将其放入INSERT查询?

任何帮助表示感谢并提前致谢!

下面是我想用来将数据发送到数据库的非工作代码:

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

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

$data_missing = array();

if(empty($_POST['first_name'])){
$data_missing[] = 'First Name';
} else {
$f_name = trim($_POST['first_name']);
}

if(empty($_POST['nationality'])){
$data_missing[] = 'Nationality';
} else {
$nationality = trim($_POST['nationality']);
}

if(empty($data_missing)){

require_once('includes/db.php');

$get_countries = "SELECT * from countries";

$query = "INSERT INTO persons (candidate_id, date_entered, first_name, country_id) VALUES
(NULL, NOW(), ?, ?)";

$stmt = mysqli_prepare($con, $query);

//  i Integers
//  d Doubles
//  b Blobs
//  s Everything Else

mysqli_stmt_bind_param($stmt, "si", $f_name, $nationality);

mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
if($affected_rows == 1){
$a="Candidate added!";
echo
"<script>alert('$a'); window.location.href='addcandidate.php';</script>";

mysqli_stmt_close($stmt);

mysqli_close($dbc);

}
} else {

echo 'You need to enter the following data<br />';

foreach ($data_missing as $missing) {

echo "$missing<br />";
}
}
}

?>

2 个答案:

答案 0 :(得分:0)

您应该按如下方式创建国家/地区下拉列表:

<?php
  $countries = "SELECT * from countries";
  $results = $mysqli->query($sql);

  echo "<select name='country_code'>";
  foreach($result->fetch_assoc() as $row){
    echo "<option value='".$row['country_id']."'>".$row['country_name']."</option>";
  }
  echo "</select>";
?>

然后,当您获得$_POST['country_code']的值时,它将是您国家/地区表中的国家/地区ID。

答案 1 :(得分:0)

如果您想避免在客户端公开国家/地区ID, 您可以修改INSERT查询以包含相应的国家/地区ID:

INSERT INTO人员(date_entered,first_name,country_id) VALUES(NOW(),?,(SELECT country_id FROM countries WHERE country_name =?));

请注意,插入查询中的 candidate_id 应为 person_id