PDA

View Full Version : PHP script to create a sql database


gigiloumill
09-24-2011, 01:08 PM
Guys, does any one have a php script to create databases on the fly. I need to create several databases and I really don't want to create 1 field at a time. Thanks

edbr
09-26-2011, 02:09 AM
using PDO this may help. its for mysql lite but PDO can use many different database engines http://henryranch.net/software/ease-into-sqlite-3-with-php-and-pdo/

gigiloumill
09-30-2011, 12:20 PM
Thanks, E...

davidj
09-30-2011, 02:45 PM
PDO is an object which is engine non-specific. It does not create databases it just allows you to store connections and queries in objects to make your app more scalable and extendible. For example you wont use specific MYSQL commands in your queries so just by changing the connection string can connect to any database and your app will run.

What you will have to do is create your databases manually and then export the DDL for future reuse.

gigiloumill
09-30-2011, 02:50 PM
Thanks guys..

edbr
10-01-2011, 02:21 AM
you can create tables within a database though, no?

i have never tried it to be honest but it is documented that you can, although it looks like creating tables and inserting data into a main database to me. In this case a database already created with permissions granted, in this case dogsDb
<?php
try
{
//open the database
$db = new PDO('sqlite:dogsDb_PDO.sqlite');

//create the database
$db->exec("CREATE TABLE Dogs (Id INTEGER PRIMARY KEY, Breed TEXT, Name TEXT, Age INTEGER)");

//insert some data...
$db->exec("INSERT INTO Dogs (Breed, Name, Age) VALUES ('Labrador', 'Tank', 2);".
"INSERT INTO Dogs (Breed, Name, Age) VALUES ('Husky', 'Glacier', 7); " .
"INSERT INTO Dogs (Breed, Name, Age) VALUES ('Golden-Doodle', 'Ellie', 4);");

//now output the data to a simple html table...
print "<table border=1>";
print "<tr><td>Id</td><td>Breed</td><td>Name</td><td>Age</td></tr>";
$result = $db->query('SELECT * FROM Dogs');
foreach($result as $row)
{
print "<tr><td>".$row['Id']."</td>";
print "<td>".$row['Breed']."</td>";
print "<td>".$row['Name']."</td>";
print "<td>".$row['Age']."</td></tr>";
}
print "</table>";

// close the database connection
$db = NULL;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
?>

davidj
10-04-2011, 10:16 AM
Yes you can create databases and tables using PHP but you don't have to use PDO. You can pass in any SQL using any MYSQL command as long as your connection has the rights to do that...

mysql_query("CREATE DATABASE mydatabase");
What I think gigiloumill is after is a script which would just create db's to save him some work but if you have to write the script you may as well just create the database as normal and save the ddl for future use.

edbr
10-04-2011, 10:48 AM
ah right , im just a new convert to PDO and getting carried away with it