Created
October 4, 2015 20:25
-
-
Save RandomArray/01beafc3c86f3294e9f8 to your computer and use it in GitHub Desktop.
PHP Array to MySQL PDO Statement (Not a function/Saved From Project)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
/* Takes an array of checklist elements from a form and converts it all to a PDO SQL Insert Statemet. | |
* This was saved from a project where the following code was no longer being used. | |
* It won't do anything without proper input. I put this here as a reference on how to build PDO SQL statements from PHP Arrays. | |
*/ | |
if (isset($_REQUEST['vehicleChecklistForm']) && !empty($_REQUEST['vehicleChecklistForm'])) { //Checks if action value exists | |
$vehicleChecklistForm = $_REQUEST['vehicleChecklistForm']; | |
$checklist = array(); | |
foreach($vehicleChecklistForm as $ele => $val){ // <- Checklist | |
$checklist[$val['name']] = $val['value']; | |
} | |
// Build SQL Query for PDO | |
$checklistSQL = 'INSERT INTO thetable SET id = :user_id, user_log_id = :user_log_id, vehicle_id = :vehicle_id, '; | |
// Add in all the values that were submitted | |
foreach($checklist as $key => $val){ | |
$checklistSQL .= $key.' = :'.$key.', '; | |
} | |
$checklistSQL = rtrim($checklistSQL, ', '); // Remove last comma | |
// Setup PDO Query | |
$stmt = $db->prepare($checklistSQL); | |
// Bind all submitted data | |
foreach($checklist as $key => $val){ | |
$theval = strval($val); | |
$stmt->bindParam(':'.$key, $theval, PDO::PARAM_STR); | |
} | |
// Bind user_id and VehicleID | |
$stmt->bindParam(':user_id', $_SESSION['agent_id'], PDO::PARAM_STR); | |
$stmt->bindParam(':user_log_id', $log_id, PDO::PARAM_STR); | |
$stmt->bindParam(':vehicle_id', $_SESSION['vehicle_id'], PDO::PARAM_STR); | |
$stmt->execute(); | |
$errors1 = $stmt->errorInfo(); // grab errors | |
}else{echo 'vehicleChecklistForm is not set..';} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment