note 75637 deleted from function.mysqli-query by bjori
| From: | bjori@php.net | Date: | Sun, 10 Jun 2007 15:19:44 +0000 |
| Subject: | note 75637 deleted from function.mysqli-query by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-127353@lists.php.net to get a copy of this message | ||
Note Submitter: kylealanhale at vanveninc dot com
Reason: useless
----
I created a simple function for the oft used INSERT query:
string queryInsert (string $table, array $query)
This function assumes several things, and is used in cases where a simple INSERT is needed for an
existing table with existing columns.
<?php
function queryInsert ($table, $query) {
if (is_array ($query)) {
foreach ($query as $key => $value) {
$columns[] = $key;
$values[] = $value;
}
unset ($key, $value);
return 'INSERT INTO ' . $table . ' (' . implode(", ", $columns) .
') VALUES (' . implode(", ", $values) . ');';
}
else {
return false;
}
}
?>
Usage:
(Assumes that $dbObject is a valid mysqli object and $formDataPost is an array of data from an HTML
form)
<?php
$query = array (
'date_submission' => "'" . date("Y-m-d H:i:s") .
"'",
'form_values' => "'" .$dbObject->escape_string (json_encode
($formDataPost)) . "'",
'ip_address' => "INET_ATON('$clientIP')",
'web_browser' => "'$clientBrowser'",
'system_os' => "'$clientOS'",
'session_id' => "'" . session_id () . "'"
);
if ($result = $dbObject->query (queryInsert ('form_data', $query))) {
echo '<p>Thank you! Your form has been submitted.</p>';
}
?>
Returns something like this:
INSERT INTO form_data (date_submission, form_values, ip_address, web_browser, system_os, session_id)
VALUES ('2007-06-09 13:23:40', '{\"1\":\"I\'m a rad
form.\",\"2\":1,\"3\":[2,3,5]', INET_ATON('127.0.0.1'),
'MOZILLA 1.8.1.4', 'WIN XP', '52cbb555c6e7950bf7ac245a805b78de');