Page 1 of 1

sending files to the database (PHP &MySQL)

Posted: Sun Dec 21, 2003 9:43 am
by Miss.Apache
Hello every body :)

i have a probelm with sending a file to the database (MySQL)

i implement a code (with PHP) that will call a C compiler then recieved the outpt from the compiler. it saves this output in a file. now i want to send the file to the database!

i don't know how?

would you please give a help? :oops:

Posted: Sun Dec 21, 2003 1:53 pm
by Pyrite
Does the file contain text that you want to send into records in the db?

Posted: Sun Dec 21, 2003 2:37 pm
by Miss.Apache
Yes

Posted: Sun Dec 21, 2003 2:51 pm
by Pyrite
Then you'll have to look into the file functions for php and then look into the LOAD INTO SQL queries.

Posted: Sun Dec 21, 2003 4:52 pm
by infolock
you could also do something like a parser that will read the file line by line, and insert into a table.

if the log file itself contains the HEADER's on the first line or so, you can grab those and generate a table dynamically based on whatever information you have.

then, after creating the table, you can just read line by line. however, there is the problem with dealing with delimitations. who is the file formatted? is it comma delimited? space delimited? hyphen delimited? Etc...

in any case, here is a pretty nifty way to do this sorta thing assuming that you have headers, and then the actual information.. all space delimited : (note, this is untested, but should give you a general idea)

Code: Select all

mysql_connect('localhost', 'username', 'password') or die(mysql_error()); 
	mysql_select_db('my_db') or die(mysql_error()); 
	$file_contents = file('log.txt');
	foreach ($file_contents as $num => $line_data) 
	{
		$line_no = $num + 1; 
	//if it is line 4, then we are at the header, so parse it and post it.
   		if ($line_no == 4) 
		{ 
			$parsed_data = preg_split("/[\s,]+/", $line_data);
			$parsed_data[0] = 'Header 1';
			$parsed_data[1] = 'Header 2';
			$parsed_data[2] = 'Header 3';
			$sql = "CREATE TABLE loginfo(".$parsed_data[0]." varchar(18), ".$parsed_data[1]." varchar(18),".$parsed_data[2]." date";
			mysql_query($sql) or die(mysql_error());
		}
	// if we are at line 5 or any other line to EOF, then we are seeing data, so update to table
		elseif ($line_no > 4) 
		{ 
			// Read column and update.
			$info_data = preg_split("/[\s]+/", $line_data);
			$qry="insert into loginfo (".$parsed_data[0].",".$parsed_data[1].",".$parsed_data[2].") values ('".$info_data[0]."','".$info_data[1]."','".$info_data[2]."')";
			mysql_query($qry) or die(mysql_error());
   		} 
	}

in any case, a good resource would be :

http://www.php.net/file

Posted: Mon Dec 22, 2003 3:19 am
by Pyrite
That's what I said :D