Click to See Complete Forum and Search --> : running SQL file / database / php


easyskankin
09-29-2006, 05:24 AM
Not sure if anyone can help/right place, but:

I need to run an SQL file on a database, which should be/is normally done through phpMyAdmin which I'm not familiar with, and at a quick glance didn't look self-explanatory to me! I'm also learning php as I go... :)
Is there a way to manually run the SQL file, which contains:

-------------------------------------------------------------


DROP TABLE IF EXISTS products_extra_fields;
CREATE TABLE products_extra_fields (
products_extra_fields_id int NOT NULL auto_increment,
products_extra_fields_name varchar(64) NOT NULL default '',
products_extra_fields_order int(3) NOT NULL default '0',
# Change to make the new extra field active by default
# products_extra_fields_status tinyint(1) NOT NULL default '0',
products_extra_fields_status tinyint(1) NOT NULL default '1',
PRIMARY KEY (products_extra_fields_id)
);

DROP TABLE IF EXISTS products_to_products_extra_fields;
CREATE TABLE products_to_products_extra_fields (
products_id int NOT NULL,
products_extra_fields_id int NOT NULL,
products_extra_fields_value varchar(64),
PRIMARY KEY (products_id,products_extra_fields_id)
);

ALTER TABLE `products_extra_fields` ADD `languages_id` INT( 11 ) DEFAULT '0' NOT NULL ;



-------------------------------------------------------------


Many thanks in advance for any help/pointers/decoding of the above into normal-speak(!).

Jon

chazzy
09-29-2006, 06:23 AM
if you're going to use PHP to do this, you'd have to read in the file, and break each command at the ";" to send each command.

easyskankin
09-29-2006, 06:51 AM
Does it have to be done through phpMyAdmin or similar? thanks

NogDog
09-29-2006, 12:59 PM
Here's an untested script you could try. You'll have to supply the proper database connection parameters.

<?php
// change these to actual values:
$dbHost = 'localhost';
$dbUser = 'db_user_name';
$dbPwd = 'db_password'
$database = 'database_name';
$sqlFile = 'SQL_file.sql';

// connect and select:
$connx = mysql_connect($dbHost, $dbUser, $dbPwd) or die("DB connection failed");
mysql_select_db($database) or die("DB selection failed");

// read/parse SQL file
$fileContents = file_get_contents($sqlFile) or die ("Unable to read file '$sqlFile'");
$sqlStatements = explode(';', $fileContents);

// execute the queries:
foreach($sqlStatements as $sql)
{
$sql = trim($sql);
if($sql !== '')
{
$result = mysql_query($sql) or die ("Query failed: $sql - ".mysql_error());
}
}
?>