note 63362 deleted from function.mysql-query by betz
| From: | betz@php.net | Date: | Tue, 21 Mar 2006 17:15:19 +0000 |
| Subject: | note 63362 deleted from function.mysql-query by betz | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-106169@lists.php.net to get a copy of this message | ||
Note Submitter: matt
----
I got tired of writing new code to convert lines of data manually into the database so I added this
to my MySQL class.
Note: I've only included the insert_query and compile_insert_string functions here so you can
see how it's all working...
<?php
//------------------------------------------
// file_to_data
//
// Converts lines of data into MySQL friendly
// data and inserts it into a table
//------------------------------------------
function file_to_data($file='file.txt', $cols=array(), $table='',
$seperator='|')
{
if (!is_file($file))
{
$this->fatal_error("Could not open file '{$file}' in
<i>file_to_data()</i>");
}
foreach (file($file) as $line)
{
$data = array();
$_data = explode($seperator, $line);
foreach ($cols as $k => $v)
{
$data[$v] = $_data[$k];
}
$this->insert_query($data, $table);
}
return TRUE;
}
//------------------------------------------
// insert_query
//
// Wrapper for an insert query
//------------------------------------------
function insert_query($data, $table)
{
if (!is_array($data) or count($data) < 1)
{
$this->fatal_error("Insert data missing");
}
$insert = $this->compile_insert_string($data);
$query = "INSERT INTO {$table} (".$insert['FIELD_NAMES'].") VALUES
(".$insert['FIELD_VALUES'].")";
return $this->query($query);
}
//------------------------------------------
// compile_update_string
//
// Turns an array of MySQL data to be updated,
// into MySQL friendly data
//------------------------------------------
function compile_update_string($data)
{
$return_string = "";
foreach ($data as $k => $v)
{
$v = preg_replace( "/'/", "\\'", $v );
$return_string .= $k . "='".$v."',";
}
$return_string = preg_replace( "/,$/" , "" , $return_string );
return $return_string;
}
?>