我正在尝试创建一个 php 表单,将邮政编码插入到我的数据库中,并将其与用户选择的城市和州相关联,但我已经使用它将近两天了,我束手无策。任何帮助是极大的赞赏。
我有三张桌子:
|state |
|state_id INT | PK
|state VARCHAR(25)|
|city |
|city_id INT | PK
|city VARCHAR(45) |
|state_id INT | PK FK
|zip_code |
|zip_code_id INT |
|zip_code VARCHAR(10) |
|city_id INT | PK FK
|city_state_id INT| PK
我有一个 php 表单,其中输入了邮政编码并选择了城市和州的框(城市选项根据州选择级联):
<form action="address.php" method="post">
<h3>Add ZIP Code</h3>
Zip Code:<br />
<input type="text" name="zipCode" id="zipCode" value="" /><br /><br />
City:<br />
<select name="city" id="cityName">
</select>
<select name="state">
<?php foreach($rows as $row): ?>
<option value="<?php echo htmlentities($row['state'],ENT_QUOTES,'UTF-8');?>"><?php echo htmlentities($row['state'],ENT_QUOTES,'UTF-8');?>
</option>
<?php endforeach; ?>
</select>
<input type="submit" name="zipCode_submit" id="" value="Add Zip Code" />
</form>
这是处理表单的php:
if (!empty($_POST['zipCode_submit'])){
if(empty($_POST['zipCode'])){
die("Please enter a ZIP Code.");
}
if (empty($_POST['city']) || empty($_POST['state'])){
die("Please select a city and a state.");
}
//Check if zip code is already in database
$query = "SELECT 1 FROM zip_code WHERE zip_code = :zip_code";
$query_params = array(':zip_code' => $_POST['zipCode']);
$stmt = DB\query($query, $query_params, $db);
if($stmt){
die("This ZIP code is already entered.");
}
//Insert zip code into database
$query = "SOME Magical SQL query that I cannot seem to figure out...";
$query_params = array(':zipCode' => $_POST['zipCode'], ':city' => $_POST['city'], ':state' => $_POST['state']);
$stmt = DB\query($query, $query_params, $db);
}
这是我必须处理查询的代码:
function query($query, $query_params, $db){
try{
$stmt = $db->prepare($query);
$stmt->execute($query_params);
return ($stmt->rowCount() > 0) ? $stmt : false;
}catch(PDOException $ex){
//On production remove .getMessage().
die("Failed to run query: " . $ex->getMessage());
}
}
至于我似乎无法弄清楚的神奇 SQL 查询,我尝试了几个不同的查询(我对 MySQL 比较陌生,所以我没有尝试过任何太高级的东西)。但这是我认为我得到的最接近的:
INSERT INTO zip_code (zip_code, city_city_id, city_state_state_id) SELECT zip_code, city_city_id, city_state_state_id
FROM zip_code
JOIN (city, state)
ON zip_code.city_city_id = city.city_id
AND zip_code.city_state_state_id = state.state_id
WHERE zip_code.zip_code = :zipCode
AND city.city = :city
AND state.state = :state
同样,我正在尝试创建 INSERT 查询,该查询使用来自邮政编码输入字段的数据以及用户选择的城市名称和状态。我似乎无法理解如何将城市和州的名称与从其他表中选择它们的查询中的城市和州 ID 配对......
再次,非常感谢任何帮助。谢谢你。