note 63362 added to function.mysql-query
| From: | matt at osu1 dot php dot net | Date: | Tue, 21 Mar 2006 11:39:50 +0000 |
| Subject: | note 63362 added to function.mysql-query | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-106145@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 85.116.0.130
Probable Submitter: 80.168.248.66
----
X-Spam-Status: No, hits=3.3 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER,
HTML_MESSAGE autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.mysql-query.php
Edit -- http://master.php.net/note/edit/63362
Del: integrated -- http://master.php.net/note/delete/63362/integrated
Del: useless -- http://master.php.net/note/delete/63362/useless
Del: bad code -- http://master.php.net/note/delete/63362/bad+code
Del: spam -- http://master.php.net/note/delete/63362/spam
Del: non-english -- http://master.php.net/note/delete/63362/non-english
Del: in docs -- http://master.php.net/note/delete/63362/in+docs
Del: other reasons-- http://master.php.net/note/delete/63362
Reject -- http://master.php.net/note/reject/63362
Search -- http://master.php.net/manage/user-notes.php