I am inserting a name, number, and company into a DB.
My table is simply:
id(primary key)
name
slideView
company
I need to update this information if a name passed to it exists, if not create a new row with this data. I have looked at REPLACE INTO but I dont think that will work for me… as I dont touch the ID at all.
My code is:
insertData($name,$count,$company);
function insertData($name, $count, $company) {
#Try/Catch statement to connect to DB, and insert data
try {
#DB username/password
$usernameDB = '****';
$passwordDB = '****';
#Create new PHP Database Object with the address, username, and password as parameters
$pdo = new PDO('mysql:host=localhost;dbname=*****', $usernameDB, $passwordDB);
#Set pdo attributes to handle errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
#assign the sth variable (sth means statement handle) to insert the data
$sth = $pdo->prepare("REPLACE INTO ***** SET name = ?, slideView = ?, company = ?");
#Execute the insert
$sth->execute(array($name,$count,$company));
#Error if can't connect or insert
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}#/try
}
I’m new to SQL and havnt found a good way to do this yet.
REPLACE INTO should work just fine – it also checks for columns with UNIQUE constraints. So you would just need to mark your
namecolumn as unique so that REPLACE INTO will identify it as duplicate.I haven’t tried this particular use case, but the documentation seems to allow it.