I built two tables with the following SQL:
CREATE TABLE state(
IDstate INTEGER not null auto_increment,
state_name VARCHAR(40) not null,
UNIQUE(state_name),
CONSTRAINT IDstate PRIMARY KEY(IDstate)
)auto_increment=100;
CREATE TABLE city(
IDcity INTEGER not null auto_increment,
city_name VARCHAR(60) not null,
IDstate INTEGER not null,
CONSTRAINT IDcity PRIMARY KEY(IDcity),
CONSTRAINT IDstate FOREIGN KEY(IDstate) REFERENCES state(IDstate)
)auto_increment=100;
I want to create a function with PHP-PDO-MySQL, I am sure about the next:
- My function receives two parameters:
$state,$city. -
I have to avoid the repetition of values.
$dbcon=new PDO('mysql:host=localhost; dbname=hotel','root', ''); $sql = "SELECT IDstate FROM state WHERE state_name=:state_name"; $query = $dbcon->prepare($sql); $query->execute(array(':state_name'=>$state_name)); $array = $query->fetchAll(); if ($query->rowCount() == 0){ $sql = "INSERT INTO state (state_name) VALUES (:state_name);"; $query = $dbcon->prepare($sql); $query->execute(array(':state_name'=>$state_name)); $sql = "INSERT INTO city (city_name, IDstate) VALUES (:city_name, :IDstate);"; $query = $dbcon->prepare($sql); $query->execute(array(':city_name'=>$city_name, ':IDstate'=>$dbcon->lastInsertId())); } else { $IDstate = $array[0]['IDstate']; $sql = "INSERT INTO city (city_name, IDstate) VALUES (:city_name, :IDstate)"; $query = $dbcon->prepare($sql); $query->execute(array(':city_name'=>$city_name, ':IDstate'=>$IDstate)); print_r($query->rowCount()); }
I need to cover the following options:
- Insert new both state and city.
- Insert new city for an existing state.
- Avoid insert for both existing state and city.
The code above works fine, but I’d like improve it. I was reading about the best option is to write a transaction instead of the previous code.
On the other hand, I need to add a third table, maybe a fourth table, I think I am repeating a lot of code: boilerplate coding.
I would like your opinions and advice.
So, this may not fully answer your question, but here are my thoughts: