I'm trying to write a cron job that would run a php script which would insert data from flat (text) file with fixed columns.
My file 'data.txt' looks something like that:
first_column second_column third_column
Eg. first column has width of 30 characters + 1 space for separation from next column, second 20 characters + 1 space for separation, third 15 (including whitespaces). My table 'TEST' has 3 columns: first, second and third.
Question is, how to first trim column data and then insert each row into the table?
<?php
// initial database stuff
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'database';
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
$file = file('/home/user/files/data.txt'); # read file into array
$count = count($file);
if($count > 0) # file is not empty
{
$query = "INSERT into TEST(first,second,third) values";
$i = 1;
foreach($file as $row)
{
$query .= "('TRIM(SUBSTR($row,1,30))','TRIM(SUBSTR($row,32,20))','TRIM(SUBSTR($row,34,49))')";
$query .= $i < $count ? ',':'';
$i++;
}
mysql_query($query) or die(mysql_error());
}
echo "File data successfully imported to database!!";
?>
And here is how it might look like:
<?php
// initial database stuff
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'database';
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
$file = file('/home/user/files/data.txt'); # read file into array
$count = count($file);
// Edited to add loop back in... Silly me.
if($count > 0) # file is not empty
{
foreach ($file as $row){
$first=trim(substr($row,0,30));
$second=trim(substr($row,31,20));
$third=trim(substr($row,33,49));
$query = "INSERT into TEST(first,second,third) values".
"($first,$second,$third)";
mysql_query($query) or die(mysql_error());
}
}
echo "File data successfully imported to database!!";
?>
Consider using PDO and prepared statement, to make it even cleaner ( and safer ).
Try this
<?php
// initial database stuff
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'database';
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
$file = file('/home/user/files/data.txt'); # read file into array
$count = count($file);
if($count > 0) # file is not empty
{
foreach($file as $key => $row)
{
if( $key == 0 ){
$col_1 = str_replace( " ", "" , trim(substr($row,1,30));
$col_2 = str_replace( " ", "" , trim(substr($row,32,20));
$col_3 = str_replace( " ", "" , trim(substr($row,34,49));
$query = "INSERT into TEST(col_1,col_2,col_3) values";
}
else {
$query .= "'TRIM(SUBSTR($row,1,30))','TRIM(SUBSTR($row,32,20))','TRIM(SUBSTR($row,34,49))')";
$query .= $key < $count ? ',':'';
}
}
mysql_query($query) or die(mysql_error());
}
echo "File data successfully imported to database!!";
?>
At the end I ended up using PDO as suggested.
It works fine with strings with commas in the middle, and it skips empty rows.
<?php
// configuration
$dbtype = 'sqlite';
$dbhost = 'localhost';
$dbuser = 'user_for_db';
$dbpass = 'pass_for_db';
$dbname = 'name_of_db';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8",$dbuser,$dbpass); //charset optional
// open data file
$handle = fopen('/home/user/data/file.txt', 'r');
if ($handle)
{
while (($buffer = fgets($handle, 4096)) !== false)
{
// new data
$first =trim(substr($buffer,0,8));
$second =trim(substr($buffer,9,10));
$third =trim(substr($buffer,20,6));
$fourth =trim(substr($buffer,27,100));
$fifth =str_replace(" , ", ", ", trim(substr($buffer,128,113)));
$sixth =trim(substr($buffer,240,30));
// query
$sql = "INSERT INTO table(column_1,column_2,column_3,column_4,column_5,column_6) VALUES (:first,:second,:third,:fourth,:fifth,:sixth)";
$q = $conn->prepare($sql);
$q->execute(array( ':first' =>$first,
':second' =>$second,
':third' =>$third,
':fourth' =>$fourth,
':fifth' =>$fifth,
':sixth' =>$sixth ));
}
if (!feof($handle))
{
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
echo "File data successfully imported to database!";
}
?>
Related
I'm trying to take the data I have from mySQL database and have it replace a certain string in a .txt file. I feel like I'm close but the string I want to replace is only getting replaced with a blank space.
<?php
$servername = "localhost";
$username = "rob1289";
$password = "databasetest";
$dbname = "RobertCornell2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM name ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
//"" . $row["first"]. "<br>";
$fname_from_db = $row["first"];
$mname_from_db = $row["middle"];
//echo $row["id"];
}
} else {
echo "0 results";
echo "<br/>Error: " . mysqli_error($conn);
}
$myFile = "freewill.doc";
$fh = fopen($myFile, 'a') or die("can't open file");
$fname_from_db = $row["first"];
$mname_from_db = $row["middle"];
$placeholders = array('fin', 'min');
$namevals = array($fname_from_db);
$path_to_file = 'freewill.doc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($placeholders,$namevals,$file_contents);
file_put_contents($path_to_file,$file_contents);
fclose($fh);
mysqli_close($conn);
?>
Could it be because $namevals (replace) has one element and $placeholders (search) has two?
From the PHP doc:
If replace has fewer values than search, then an empty string is used for the rest of replacement values.
Im trying to read the data of some divs in a list of urls, but i dont find the correct way, actually i only get a white page, but if do a print_r on the commented code (the $aElements) i can see the url loaded correctly, so i think the error is on the foreach, but i can't fix it, i need the link inside the div with the id=city
require_once('simple_html_dom.php');
set_time_limit (2000);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "buss";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT url FROM business";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$html = file_get_html($row["url"]);
$aElements = $html->find('div[id=city]', 0)->find('a');
$localList = array();
// here if i do a print_r i get the html of each url listed and is fine (of $aElements)
foreach($aElements as $element) {
if(substr($element->href, 0, 1) == '/') {
$ownerName = trim(str_replace('Punto de', '', $element->plaintext));
$localList[$artistName] = $element->href;
$file = fopen("newfile.txt", "a");
fwrite($file, $localList[$ownerName] = $element->href . PHP_EOL);
fclose($file);
}
}
}
} else {
echo "0 results";
}
$conn->close();
I can't seem to get the text file to read into mysql correctly. I have 2 columns artid and artname, both columns seems to go under one column in my mysql. Is there a problem with my code?
txt file
1 Acconci
2 Ames
3 Aserty
4 Baron
5 Battenberg
6 Bindner
php code
<?php
$servername = "localhost"; //mysql
$username = "root";
$password = "";
$dbname = "project1"; //db525
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br />";
$handle = #fopen("artists.txt", "r"); //read line one by one
$values='';
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 4096); // Read a line.
// list($a, $b)=explode(" ",$buffer);//Separate string by
list($a, $b) = array_pad(explode(' ', $buffer, 2), 2, null);
echo $a." ".$b."<br>";
$sql = "INSERT into arts(ArtistID,ArtistName) VALUES('".$a."','".$b."')";
mysqli_query($conn, $sql) or die (mysqli_error($conn));
// use mysql insert query here
}
?>
My table name is generated it has these columns: (id, username, password) - nothing fancy :)
My users.text have this:
expert1001 01995056
expert1002 58381484
expert1003 03154500
expert1004 45885204
expert1005 24750107
expert1006 14096885
expert1007 81250562
expert1008 00910766
expert1009 99830724
I'm trying to export those generated users to my db but I'm trying to do a check if the user already exists; if so I move on to the next one but I'm getting this error and I don't see it.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
(PHP version 5.3.5)
<?php
$host = "localhost";
$user = "root";
$pass = "1234";
$db = "users";
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
$file = file('users.text'); # read file into array
$count = count($file);
if($count > 0) # file is not empty
{
$milestone_query ="INSERT into `generated`(`username`, `password`) values";
$i = 1;
foreach($file as $row)
{
$milestone = explode(' ',$row);
$requete ="SELECT * FROM `lines` WHERE `username`='$milestone[0]'";
$queryset=mysql_query($requete);
while($row2 = mysql_fetch_assoc($queryset)){
$bood = "".$row2['username']."";
$us=$milestone[0];
if ($us == $bood )
{
$i++;
} else {
$milestone_query .= "('$milestone[0]', '$milestone[1]')";
$milestone_query .= $i < $count ? ',':'';
$i++;
}
}
}
if ($milestone_query != NULL ){
mysql_query($milestone_query) or die(mysql_error());
}else{
die();
}
}
echo "Done!";
?>
i made some changers and its seems to work now but i still have one probleme is , at the end of the query i cant find out how to trim it before submiting the query
here is the code
<?php
$host = "localhost";
$user = "root";
$pass = "123456";
$db = "generated";
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
$file = file('users.text'); # read file into array
$count= count($file);
if($count > 0) # file is not empty
{
$milestone_query ="INSERT into `users`(`username`, `password`) values";
$i = 1;
foreach($file as $row)
{
$row = str_replace("\n", '', $row);
$milestone = explode(' ',$row);
$us= $milestone[0];
$requete ="SELECT `username` FROM `users` WHERE `username`='$us'";
$queryset=mysql_query($requete);
$row2 = mysql_fetch_assoc($queryset);
$bood = $row2['username'];
if ($us == $bood)
{
$i++;
} else{
$milestone_query .= "('$milestone[0]', '$milestone[1]')";
$milestone_query .= $i < $count ? ',':'';
}
}
mysql_query($milestone_query) or die(mysql_error());
}
?>
here is the query result
"INSERT into users(username, password) values('aspireupp7p',
'97025407'),('artre1r7pp', '40138199'),('asuiozy4p',
'44896449'),('asuytrdiop', '36582797'),"
u see at the end i have this , can you guys help me with that thank you
I have cleaned up the code a little.. Good luck!
<?php
$host = "localhost";
$user = "root";
$pass = "123456";
$db = "generated";
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
$users = file('users.text'); # read file into array
if ($count = count($users)) # file is not empty
{
$milestone_query = "INSERT into `users`(`username`, `password`) values";
$milestone_query_count = strlen($milestone_query);
foreach ($users as $i => $user) {
$userInfo = explode(' ',trim($user));
$username = current($userInfo);
$password = next($userInfo);
$requete = "SELECT `username` FROM `users` WHERE `username` ='{$username}'";
if(!$result =boolval(mysql_fetch_assoc(mysql_query($requete)))){
var_dump($username." added!");
$milestone_query .= "('$username', '$password'),";
}
}
$milestone_query = trim($milestone_query, ",");
if(strlen($milestone_query) !== 50){
mysql_query($milestone_query) or die(mysql_error());
var_dump("finished!");
}else{
var_dump("No new users!");
}
}
<body>
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "random";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT Channel_Location, Product, Active FROM channels
ORDER BY RAND()
Limit 5";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
echo "<tr><br><td>".$Channel_Location."</td></tr>";
}
} else {
echo "0 results";
}
$myfile = fopen("Log.txt", "w") or die("Unable to open file!");
$txt = "$result";
fwrite($myfile, $txt);
fclose($myfile);
mysqli_close($conn);
?>
</body>
So basically my issue is i'm trying to write the output of $result to a text file but i get the following error
the text file should have 5 lines of text, if i change the $txt = "$Channel_Location" i will have one result but not all 5
$output = '';
$outputArray=[];
while($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
echo "<tr><br><td>".$Channel_Location."</td></tr>";
$output .= $row['Channel_Location']."\n";
$outputArray[] = $row;
}
file_put_contents('Log.txt',$output);
// or you can use json_encode to save whole query result!!
file_put_contents('log.txt',json_encode($outputArray));
You must concatenate your data before writing the string to the file.
$text = '';
while ($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
$text = $text . $Channel_Location . "\n";
}
You can then do something like:
fwrite($myfile, $text);
fwrite writes a string to a document.
$result is an object and as such cannot be written as a string.
Your best option is when you run through the loop to print out the values, also add them to a string.
I would also recommend doing the fwrite function within the if statement as you will need values to write to it otherwise it will just open the file, write an empty variable and then close.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "random";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT Channel_Location, Product, Active FROM channels
ORDER BY RAND()
Limit 5";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$output = '';
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
echo "<tr><br><td>".$Channel_Location."</td></tr>";
$output .= $Channel_Location . '/n';
}
$myfile = fopen("Log.txt", "w") or die("Unable to open file!");
$txt = "$output";
fwrite($myfile, $txt);
fclose($myfile);
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Suppose you want to user record
$output ='';
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$Channel_Location = $row['Channel_Location'];
$output .="<tr><br><td>".$Channel_Location."</td></tr>";
}
} else {
$output .= "0 results";
}
$myfile = fopen("Log.txt", "w") or die("Unable to open file!");
fwrite($myfile,$output);
fclose($myfile);
mysqli_close($conn);