The following works perfectly. But, I'd like to know if there is a more efficient way to do it -- because I've got another object, with 24 properties, that needs to be loaded into a MySQL table right after this one. Thanks.
// create an array of value lists:
$values = array();
foreach ($res['Identities'] as $x)
{
$values[] = sprintf("($userid,'%','%','%','%','%','%','%')",
mysql_escape_string($x->full_name),
mysql_escape_string($x->email_address),
mysql_escape_string($x->reply_to),
mysql_escape_string($x->signature),
mysql_escape_string($x->use_sig),
mysql_escape_string($x->sig_reply),
mysql_escape_string($x->sig_forward));
}
// now you can do just one insert query with multiple value lists:
$sql = "Insert Into `user_identities` (`userid`, `full_name`, `email_address`, `reply_to`, `signature`, `use_sig`, `sig_reply`, `sig_forward`) VALUES ".implode(', ', $values);
$result = mysql_query($sql) or die(mysql_error() . ": $sql");
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Thanks, NogDog, but I was really also wanting to avoid hard-coding a bunch of property and column names, too.
So, this is what I've come up with -- and it works. Reactions?
PHP Code:
foreach ($res['Identities'] as $obj):
object_to_field_list($obj, $fields='', $values='');
$sql = "Insert Into `user_identities` (`userid`,{$fields}) Values({$userid},{$values});";
if (!$result = execute_sql($sql)) exit;
endforeach;
PHP Code:
function object_to_field_list(&$obj, &$field_list, &$values_list)
{
foreach($obj as $key => $value):
if (strlen($field_list) > 0):
$field_list .= ',';
$values_list .= ',';
endif;
$field_list .= '`' .$key. '`';
if (is_numeric($value)):
$values_list .= $value;
else:
$values_list .= "'" .mysql_escape_string($value). "'";
endif;
endforeach;
}
function report_mysql_error($sql)
{
echo '<p>Error: ' .mysql_errno(). '; ' .mysql_error(). "<br />\n".
"sql = \"{$sql}\"</p>\n";
}
function execute_sql($sql)
{
if (!$result = mysql_query($sql)):
report_mysql_error($sql);
return false;
endif;
return $result;
}
Bookmarks