For Programmers: Free Programming Magazines  


Home > Archive > PHP DB > July 2007 > Re: [PHP-DB] PHP Script to Run SQL file









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: [PHP-DB] PHP Script to Run SQL file
Chris

2007-07-29, 9:58 pm

Arena Servers wrote:
> If it helps, after posting this question, I did some searching, and I found an installation script which creates a database and creates the tables using pure sql statements in a php file. Here's the coding...


<?php
mysql_connect(....);

$queries = array();
$queries[] = 'create table abc(a int)';
$queries[] = 'create table def(a int, b text)';

foreach ($queries as $query) {
$result = mysql_query($query);
if (!$result) {
echo 'Unable to run query ' . $query . ': ' . mysql_error() . '<br/>';
exit;
}
}

--
Postgresql & php tutorials
http://www.designmagick.com/
Goltsios Theodore

2007-07-30, 7:58 am

In an another case that you have exported the database using mysqldump
(using unix) then this could do the job:

<?php

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$db = 'test';
$file ='/tmp/file_restore.sql';

if ($dbpass != '') {
$cmd = '/usr/bin/mysql -h '.$dbhost.' -u '.$dbuser.' -p
'.$dbpass.' < '.$file;
exec($cmd,$out,$retval);
} else {
$cmd = '/usr/bin/mysql -h '.$dbhost.' -u '.$dbuser.' < '.$file;
exec($cmd,$out,$retval);
}

?>

using the operating system. Ignore this if you just need to know how to
query using php. If that is the case consider using PDO

http://www.php.net/manual/el/ref.pdo.php


<?php

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$db = 'test';

$dbh = new PDO('mysql:host='.$dbhost.';dbname='.$db, $dbuser, $dbpass);
$query = "SELECT * FROM Table WHERE test='1'";
$sth = $dbh->prepare($query);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
?>

or some other method that php supports.



Chris wrote:
> Arena Servers wrote:
>
> <?php
> mysql_connect(....);
>
> $queries = array();
> $queries[] = 'create table abc(a int)';
> $queries[] = 'create table def(a int, b text)';
>
> foreach ($queries as $query) {
> $result = mysql_query($query);
> if (!$result) {
> echo 'Unable to run query ' . $query . ': ' . mysql_error() .
> '<br/>';
> exit;
> }
> }
>

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com