Here's how I'm thinking about inserting values into two tables. Each reservation
will have a set of services
the amount of which can vary, so I need to setup the query dynamically, here's my first sketch, although not tested yet.
function saveBooking($fullBook) {
$mysqli = new mysqli(HOST, USER, PASSWORD, DB_PRICE);
if (mysqli_connect_errno()) {
echo ("Connect failed: " .mysqli_connect_error());
exit();
}
$reservation =
"BEGIN;
INSERT INTO reservations (userID, fullPrice)
VALUES(?, ?);
SELECT LAST_INSERT_ID() INTO @reservationID;";
$reservationParamType = 'id';//int, double
$serviceQuery =
"INSERT INTO services (reservationID, fromDestination, toDestination)
VALUES(@reservationID,?, ?);";
$serviceParamType = 'ii';//int int
$fullService;
$fullServiceParamType;
$fullServiceParams;
foreach($fullBook as $k => $booking){
$reservationParams = $booking['userID'].', '.$booking['fullPrice'];
$serviceParams = $booking[$k]['fromDestination'].', '.$booking[$k]['toDestination'];
$fullServiceQuery .= $serviceQuery;
$fullServiceParamType .= $serviceParamType;
$fullServiceParams .= $serviceParams;
}
$query = $reservation.$fullServiceQuery."COMMIT;";
$paramTypes = $reservationParamType.$fullServiceParamType;
$params = $reservationParams.$fullServiceParams;
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param($paramTypes, $params);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
}
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
} else {
echo 'There was a problem connecting to the database, please refresh your browser.';
}
$mysqli->close();
}
Would this type of logic concern you in any way? Given that the values have already been sanitized with the following:
function sanitize($input) {
if (is_array($input)) {
$output = array();
foreach ($input as $key => $value){
$output[$key] = sanitize($value);
}
return $output;
}
return htmlentities(strip_tags(trim($input)));
}
Meaning I haven't taken care of quotes, but I'm assuming that's what prepared statements are for.
Any pointers as to what could not be a best practice, something that will fail on a certain occasion or another way to go about this is what I'm looking for.
Thanks in advance.