PDA

View Full Version : Creating Tables PHP/MySQL


Goober
12-15-2003, 04:32 AM
Hey, I'm trying to write a PHP script that will create tables on a MySQL database. So far I have added this code to the script:
(this is just an example script, the not real data)


<?php

//MySQL Login Information

$db_username = 'my_username'; // Database Username
$db_password = 'my_password'; // User Password
$db_name = 'my_db_name'; // Database Name
$db_host = 'localhost'; // This will usually be localhost

mysql_connect ($db_host, $db_username, $db_password);

mysql_select_db ('$db_name');

create table test_table (
serial int(3) not null auto_increment,
name varchar(16) not null,
id int(3) not null,
primary key(serial) ) ;

insert into test_table (name,id) values ('Scott',1);
insert into test_table (name,id) values ('Ryan',3);
insert into test_table (name,id) values ('James',4);
insert into test_table (name,id) values ('Alex',5);

mysql_close ();

?>


when run the script and look at my database, no tables or values have been created. What have I done wrong?

raf
12-15-2003, 09:49 AM
Well, basically because your not exacuting any sql-statements.

you need to execute the statements with mysql_query()
http://be.php.net/manual/en/function.mysql-query.php

like

$error = '';
$create=("create table test_table (
serial int(3) not null auto_increment,
name varchar(16) not null,
id int(3) not null,
primary key(serial) )") ;
$result = mysql_query($create) or die("Queryproblem in query 1: " . mysql_error());

if ($result) {
$insert = ("insert into test_table (name,id) values ('Scott',1)");
$result = mysql_query($insert) or die("Queryproblem in query 2: " . mysql_error());
if (mysql_affected_rows() != 1) {
$error .= '<br />Failed inserting record' ;
}
....
}


You need to run a seperate query for each insert (if you can, by looping through an array or so).
But why do this over the webserver like this? You can run this in batchmode from thecommandline, or use phpMyAdmin or so and run it as a dumpfile ?