두 개의 테이블이 있습니다.
persons(person_id, date_entered, first_name, country_id)
countries(country_id, country_name)
국가의 Country_id는 사람의 country_id에있는 외래 키입니다.
나는 사람의 이름과 국적을 묻는 POST 양식이 있고 그 정보를 사람 테이블에 입력합니다. 국적 필드는 국가 테이블의 조회이며 사용자에게 국가 이름의 드롭 다운 목록을 제공합니다. 제출 버튼은 데이터를 개인 테이블로 보냅니다.
문제는 국적 드롭 다운 목록이 국가 이름을 생성하지만 실제로 해당 국가의 ID를 people 테이블로 보내야한다는 것입니다. 나는 국가 테이블에서 데이터를 가져와 country_name을 국적 필드와 일치시킨 다음 ID를 추출해야한다고 생각하지만 확실하지 않습니다 ...
마지막으로 질문은 드롭 다운 목록의 국가 이름을 해당 ID와 일치시키고 INSERT 쿼리에 넣는 방법입니다.
도움을 주시고 미리 감사드립니다!
다음은 데이터를 DB로 보내는 데 사용하려는 작동하지 않는 코드입니다.
<?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 />";
}
}
}
?>
다음과 같이 국가 드롭 다운을 만들어야합니다 .
<?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가됩니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다