954,568 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

MySql commands in a text file

How would you execute MySql commands found in a text file? It's really beginning to bug me!

DangerM0use
Newbie Poster
2 posts since Apr 2007
Reputation Points: 10
Solved Threads: 0
 

i dont know you want to load the sql into the mysql directly or using php?
anyway u could try this it works with oracle but i didnt try it with mysql
@filename.sql
.sql is a text file

w_3rabi
Junior Poster
160 posts since Dec 2006
Reputation Points: 18
Solved Threads: 9
 
How would you execute MySql commands found in a text file? It's really beginning to bug me!

If your code is just for your own server, you could try using the command line:

[PHP]<?php
exec("mysql -u USER -p DBNAME < dump.sql");
?>[/PHP]

or try this class from: http://www.phpclasses.org/browse/file/12857.html

[PHP]<?php
/**
* Author : MA Razzaque Rupom (rupom_315@yahoo.com)
* Version : 1.0
* Date : 12 Feb, 2006
* Purpose : Importing valid SQL dump to DB
* Release : Released under GNU Public License
*/

class parse
{
var $file;

function parse($file)
{
$this->setFile($file);
$this->startParsing();
}

/**
* @purpose : Sets filename to be parsed
* @params $file
* @return none
*/
function setFile($file)
{
$this->file = $file;
}

/**
* @purpose : Gets filename to be parsed
* @params none
* @return filename
*/

function getFile()
{
return $this->file;
}

/**
* @purpose : Parses SQL file
* @params none
* @return none
*/

function startParsing()
{

$file = $this->getFile();
// Getting the SQL file content
$content = file_get_contents($file);

// Processing the SQL file content
$file_content = explode("\n",$content);


$query = "";

// Parsing the SQL file content
foreach($file_content as $sql_line)
{
if(trim($sql_line) != "" && strpos($sql_line, "--") === false)
{
$query .= $sql_line;
// Checking whether the line is a valid statement
if(preg_match("/(.*);/", $sql_line))
{
$query = substr($query, 0, strlen($query)-1);
//Executing the parsed string, returns the error code in failure
$result = mysql_query($query)or die(mysql_error());
$query = "";
}
}
} //End of foreach

return true;
} //End of function

} //End of class
?> [/PHP]

from the look of the class though, I think it will choke on SQL queries that have new lines - "\n" - inside queries.

digital-ether
Nearly a Posting Virtuoso
Moderator
1,293 posts since Sep 2005
Reputation Points: 461
Solved Threads: 101
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You