I have the following PHP code that allows me to read in from a text file line by line and write to a MySQL database. The text file consists of 13 values seperated by a space on each line. I have created the table separately in SQL, (with all the relevant Fields needed: Time, WIMU_ID, Ax, Ay etc) and then run the PHP below to INSERT the values into the table. My question is: Is there any way to create the table within the PHP code below and not have to CREATE the table in SQL first? Any help or suggestions appreciated.
Hugh.
<?php
$connection = mysql_connect('localhost','root','bonzo123');
mysql_query('create database gameDB');
mysql_select_db('gameDB');
$wx = array_map('trim',file("Thu-Apr-01-09_41_01-2010.txt_calibrated_120Hz.txt"));
$newwx = array();
foreach($wx as $i => $line)
{
if ($i > 1)
{
$tmp = array_filter(explode(' ',$line));
$q = "insert into test1 (Time, WIMU_ID, Ax, Ay, Az, Gx, Gy, Gz, Mx, My, Mz, Ax70, Ay37) values ('" . implode("','",$tmp) . "')";
$rw = mysql_query($q) or die("Problem with the query: $q<br>" . mysql_error());
}
}
?>
Sure, you can execute a command like:
To get your table creation query, issue this command after you’ve already created it in SQL:
Edit:
Note that you don’t have to create the table in SQL directly, but since you already have, issuing the above command will give you exactly what you need to include in PHP to have it create the table on a future installation should the table not exist.
Note also that as @Jeremy suggests, you don’t have to “roll your own” code to import a data file to a table. Once you’ve created the table, you can use
LOAD DATA INFILE...to populate the table.Edit 2:
Here is an example based on your comment: