Currently I run a SELECT
query on a table and if the num_rows
is zero i then run a new function that INSERT
s the record into the table. This seems very inneficient and I am struggling to find a good solution.
Current set up (simplified): Select Function -
$sql = "SELECT * FROM myTable WHERE col1 = ".$val1." AND col4 = ".$val4." AND col6 = ".$val6
// rest of code returns $numRows variable
If no $numRows
is 0
then run a fresh query inserting the new record.
if($numRows == 0) {
try {
$dbh = $this->_dbSite;
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO myTable (col1, col2, col3, col4, col4, col6, col7) VALUES (:val1, :val2, :val3, :val4, :val5, :val6, :val7");
$stmt->bindParam(':val1', $val1, PDO::PARAM_STR);
$stmt->bindParam(':val2', $val2, PDO::PARAM_STR);
$stmt->bindParam(':val3', $val3, PDO::PARAM_STR);
$stmt->bindParam(':val4', $val4, PDO::PARAM_STR);
$stmt->bindParam(':val5', $val5, PDO::PARAM_STR);
$stmt->bindParam(':val6', $val6, PDO::PARAM_STR);
$stmt->bindParam(':val7', $val7, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e) {
return $e->getMessage();
}
} else {
$message = "Sorry this record already exists";
}
Table structure:
col1 | col2 | col3 | col4 | col5 | col6 | col7
________________________________________________
user1 abc sol red doo 3a def
user2 abc ast Blue doo 4a def
user1 abc ast blue doo 3a def
user4 abc ast red doo 6a def
user1 abc ast Green doo 3a def
user2 abc ast red doo 7a def
user1 abc ast red doo 3a def
The above example should be avoided as the first and last rows are identical in terms of col1,col4
and col6
This does not seem the most efficient way of doing this. Has anybody encountered this before? Any advice would be greatly appreciated.