Read only first ten words from a text file using php - php

<?php
include 'db_connection.php';
if (isset($_POST['submit'])) {
$file = fopen("quiz3.txt","r") or die("Unable to open file!");
$line = fgets($file);
$sql = "INSERT INTO quiz3 (FromFile) VALUES ('".$line."')";
$result = mysqli_query($conn,$sql);
if (!$result) {
echo mysqli_error($conn);
}
else
{
echo "Your File Has Been Read & Stored In Database Successfully<br>Line Stored = ";
echo $line;
}
fclose($file);
}
?>
I want to store only first ten words from the line. How Can i do that?
currently it is saving the first line.

function get_words($sentence, $count = 10) {
preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
return $matches[0];
}
$file = fopen("quiz3.txt","r") or die("Unable to open file!");
$line = fgets($file);
$convertedLine = get_words($line );
$sql = "INSERT INTO quiz3 (FromFile) VALUES ('".$convertedLine ."')";
$result = mysqli_query($conn,$sql);

Not sure if your data contains comma, or other symbols.
This might be quick solution, and it also works with CJK words.
<?php
function cut_words($source, $number_take){
$result = "";
$wc = 0;
$source = str_replace(" ", " ", $source); // Simple sanity
$string = explode(" ", $source);
while ($wc < $number_take){
if(isset($string[$wc])){ // Prevent index out of bound.
$result .= $string[$wc];
if($wc < $number_take) {
$result .= " ";
}
$wc++;
} else {
break;
}
}
$result = trim($result);
return $result;
}
$line = cut_words($line, 10);
?>

Related

Importing text file into MySQL php program

I have a code that I took from https://www.howtoforge.com/community/threads/importing-text-file-into-mysql.7925/ and changed to what I needed it for but when I run the program it doesn't import the data into the database
Text file
GeoID|X|Y|Wood|Clay|Iron|Stone|Food|TerrainSpecificTypeID|TerrainCombatTypeID|RegionID
7025277|279|-1321|0|0|0|0|0|62|14|31
7025278|279|-1320|0|0|0|0|0|62|14|31
7025279|279|-1319|0|0|0|0|0|62|14|31
7025280|279|-1318|0|0|0|0|0|62|14|31
7025281|279|-1317|0|0|0|0|0|62|14|31
7025282|279|-1316|0|0|0|0|0|62|14|31
7025283|279|-1315|0|0|0|0|0|62|14|31
7025284|279|-1314|0|0|0|0|0|62|14|31
7025285|279|-1313|0|0|0|0|0|62|14|31
7025286|279|-1312|0|0|0|0|0|62|14|31
PHP code that i am currently using
<?php
// Set Mysql Variables
$username = "root";
$auth = 'i-have-removed-it';
$db = mysql_connect("localhost", $username, $auth);
mysql_select_db("testdb",$db);
$file = "/tmp/map_datafile_test.txtt";
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);
$output = str_replace("\t|\t", "|", $data);
$output = explode("\n", $output);
$language_id = "1";
$categories_id = 0;
foreach($output as $var) {
$categories_id = $categories_id + 1;
$tmp = explode("|", $var);
$GeoID = $tmp[0];
$X = $tmp[1];
$Y = $tmp[2];
$Wood = $tmp[3];
$Clay = $tmp[4];
$Iron = $tmp[5];
$Stone = $tmp[6];
$Food = $tmp[7];
$TerrainSpecificTypeID = $tmp[8];
$TerrainCombatTypeID = $tmp[9];
$RegionID = $tmp[10];
echo " categories_id: " . $categories_id . " Artikelgroep: " . $Artikelgroep . "<br>";
$sql = "INSERT INTO `World_Map`(`GeoID`, `X`, `Y`, `Wood`, `Clay`, `Iron`, `Stone`, `Food`, `TerrainSpecificTypeID`, `TerrainCombatTypeID`, `RegionID`) VALUES ('$GeoID','$X','$Y','$Wood','$Clay','$Iron','$Stone','$Food','$TerrainSpecificTypeID ','$TerrainCombatTypeID ','$RegionID')" or die("Insert failed: " . mysql_error());
mysql_query($sql);
}
echo "Done!";
?>
You need to set the variables $GeoID, $X, $Y, $Wood, $Clay, ...
In the foreach loop you get each line of the file, and in $tmp you get each column. So $GeoID should be $tmp[0], $X should be $tmp[1] and so on.

Insert an array in the database

I want to insert an array in the database. The array can be changed all the time. I want different rows in the database.
My code:
$var = file_get_contents("test2.txt");
$test = preg_replace('/\\\\/', '', $var);
$poep = explode(" ", $test);
Yeah, there is no database connection, because I want to know how to 'split' the array to insert it in the database.
I have tried this:
foreach($poep as $row) {
$row = $mysqli->real_escape_string($row);
if($mysqli->query("insert into data('array') VALUES ($row)") == false){
echo 'Doesnt works!';
}
It returns 'Doesnt works', so I think there is a problem with query?
#NadirDev Hi. Assuming that you are using Core PHP programming. After exploding the string by the space, run foreach loop and then insert individual rows. Look at this rough code to get idea:
foreach($poep as $row) {
// $row now contains one word. Add that in database.
$row = mysql_real_escape_string($row);
$query = mysql_query("insert into tableName('fieldName') VALUES ($row)");
}
here's some code I wrote. It processes a CSV file and stores separate rows into a db table (difference is just that you have a TXT file). It does the mysql insertion in batches of 250 rows. Hope it can help you!
// read all input rows into an array
echo "Processing input..<br /><br />";
$row = 0;
$input = array();
if (($handle = fopen($file['tmp_name'], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$input[$row][] = addslashes($data[$c]);
}
$row++;
}
fclose($handle);
}
$count = 0;
$q = "INSERT INTO `inputs` (`keyword`, `percent`, `link`, `added_on`) VALUES ";
foreach ($input as $inp) {
$q .= "('" . addslashes($inp[0]) . "', '" . addslashes($inp[1]) . "', '" . addslashes($inp[2]) . "', '" . date('Y-m-d H:i:s') . "'), ";
$count++;
if ($count >= 250) {
$q = substr($q, 0, -2);
$q = mysqli_query($con, $q);
$q = "INSERT INTO `inputs` (`keyword`, `percent`, `link`, `added_on`) VALUES ";
$count = 0;
}
}
if ($count > 0) {
$q = substr($q, 0, -2);
$q = mysqli_query($con, $q);
}
echo "Successfully added " . count($input) . " rows to the input list.";

Exporting a CSV file from Php with query from Database

I am using following code to Export a CSV file
I am having very strange Problem.
My $newQuery gives me (when i do echo)
SELECT * FROM quotes WHERE storeEmail = 'xxxxxxx ';
If I use this above query in my phpmyadmin, i get atleast 1000 rows. However in this same code, its returning null.
$quotes is just empty.
what is wrong here
<?php session_start();
require_once("common/commonfiles.php");
$menuItem="stores";
$title="Stores";
if (isset($_GET['name']))
{
$name = trim($_GET['name']);
}
$filename = "export.csv";
$delimiter= ",";
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the (input array
fputcsv($f, array("Call Details"), "\r\n\r\n");
fputcsv($f, array("UserId","Call Date","Firstname","Lastname","Phone","Zip","Email"), ",");
$query = "SELECT callDetails.* , clients.* FROM callDetails JOIN clients ON clients.id = callDetails.userId WHERE storeName = '" . $name ."' ";
db::open();
$result = mysql_query($query) or die(mysql_error());
$records = Array();
if(!mysql_num_rows($result)==0)
{
$i=0;
while ($row = mysql_fetch_array($result))
{
$records[$i] = $row;
$i++;
}
}
else
{
$records = false;
}
db::close();
if($records)
{
foreach ($records as $line)
{
$newArray = array($line['userId'],
$line['creationDate'],
$line['firstname'],
$line['lastname'],
$line['phone'],
$line['zip'],
$line['email']
);
// generate csv lines from the inner arrays
fputcsv($f, $newArray, $delimiter);
}
}
$query = "SELECT * FROM stores WHERE name LIKE '%".$name."%' LIMIT 1";
db::open();
$result = mysql_query($query) or die(mysql_error());
if(!mysql_num_rows($result)==0){
$recordset = mysql_fetch_assoc($result);
}else{
$recordset = false;
}
db::close();
$recordset = db::getRecord($query);
$storeEmail = $recordset['email'];
fputcsv($f, array(""), "\r\n\r\n");
fputcsv($f, array(""), "\r\n\r\n");
fputcsv($f, array(""), "\r\n\r\n");
fputcsv($f, array("Quote Details"), "\r\n\r\n");
fputcsv($f, array("Ring","Quote Time","Firstname","Lastname","Phone","Zip","Email"), ",");
$newQuery = "SELECT * FROM quotes WHERE storeEmail = '" . $storeEmail ."'";
db::open();
$newResult = mysql_query($newQuery) or die(mysql_error());
if(!mysql_num_rows($newResult)==0)
{
$i=0;
while ($row = mysql_fetch_array($newResult))
{
$quotes[$i] = $row;
$i++;
}
}
else
{
$quotes = false;
}
db::close();
if($quotes)
{
foreach ($quotes as $line)
{
$newArray = array($line['ring'],
$line['quoteTime'],
$line['firstname'],
$line['lastname'],
$line['phone'],
$line['zip'],
$line['email']
);
// generate csv lines from the inner arrays
fputcsv($f, $newArray, $delimiter);
}
}
// rewrind the "file" with the csv lines
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachement; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
//fclose($fp);
?>
Try to use trim in line:
$newQuery = "SELECT * FROM quotes WHERE storeEmail = '" . trim($storeEmail) ."'";
Maybe $storeEmail variable has some additional whitespace characters.
Are you actually making it into your mysql_num_rows loop? If not, then $quotes is being set to false. Try printing something out if you make it there or don't.
if(!mysql_num_rows($newResult)==0) {
print "Made it!";
}
else {
print "Didn't Make It. How Sad.";
}
Then you will know if it's your query or not.
If it is your query, then it is probably failing at the email part. ($storeEmail = $recordset['email'];) Try printing your query to see if that looks right:
$newQuery = "SELECT * FROM quotes WHERE storeEmail = '" . $storeEmail ."'";
print $newQuery;
If not there, then your query that gets the email is having problems.

Get individual ID of ROW, and make the result linkable

I need to get the 'id' column from my table 'reports' to get the unique value and make it linkable.
The link of the element has this format: http://www.mysite.com/id, (coma included)
Can you help me how to get the info from id column and make it clikable in the results?
<?php
$MySQLPassword = "*****";
$HostName = "***";
$UserName = "***";
$Database = "****";
mysql_connect($HostName,$UserName,$MySQLPassword)
or die("ERROR: Could not connect to database!");
mysql_select_db($Database) or die("cannot select db");
$default_sort = 'ID';
$allowed_order = array ('name','description');
if (!isset ($_GET['order']) ||
!in_array ($_GET['order'], $allowed_order)) {
$order = $default_sort;
} else {
$order = $_GET['order'];
}
if (isset($_GET['keyword'])) {
if(!$_GET['keyword']) {
die('<p>Please enter a search term.</p>');
}
/////////////////////////HERE IS THE BEGINING OF CODE WHERE I THINK SHOULD BE THE PROBLEM ////////////////////////////
$tables = 'reports';
$return_fields = 'name organizer_id no_pages publication_date price';
$check_fields = 'name description';
$query_text = $_GET['keyword'];
$clean_query_text =cleanQuery($query_text);
$newquery=bq_simple ($return_fields, $tables, $check_fields, $clean_query_text);
$newquery = $newquery . " ORDER BY $order;";
$result = mysql_query($newquery) or die(mysql_error());
$numrows = mysql_num_rows($result);
if ($numrows == 0) {
echo "<H4>No data to display!</H4>";
exit;
}
echo "<p>Your search '$query_text' returned ".$numrows. " results.</p>\n";
echo "<p>Click on the headings to sort.</p>\n";
$row = mysql_fetch_assoc ($result);
echo "<TABLE border=1>\n";
echo "<TR>\n";
foreach ($row as $heading=>$column) {
echo "<TD><b>";
if (in_array ($heading, $allowed_order)) {
echo "$heading";
} else {
echo $heading;
}
echo "</b></TD>\n";
}
echo "</TR>\n";
$results = mysql_query("SELECT id, name FROM reports WHERE id = $id") or die(mysql_error());
while ($row = mysql_fetch_assoc ($result)) {
echo "<TR>\n";
echo '' . $row['name'] . '';
echo "</TR>\n";
}
echo "</TABLE>\n";
}
////////////////////////FINISH OF THE CODE WITH PROBLEM ////////////////////////////
/* * * * * * * * * * * * * * F U N C T I O N S * * * * * * * * * * * */
function cleanQuery($string)
{
$string = trim($string);
$string = strip_tags($string); // remove any html/javascript.
if(get_magic_quotes_gpc()) // prevents duplicate backslashes
{
$string = stripslashes($string);
}
if (phpversion() >= '4.3.0')
{
$string = mysql_real_escape_string($string);
}
else
{
$string = mysql_escape_string($string);
}
return $string;
}
function bq_handle_shorthand($text) {
$text = preg_replace("/ \+/", " and ", $text);
$text = preg_replace("/ -/", " not ", $text);
return $text;
}
function bq_explode_respect_quotes($line) {
$quote_level = 0; #keep track if we are in or out of quote-space
$buffer = "";
for ($a = 0; $a < strlen($line); $a++) {
if ($line[$a] == "\"") {
$quote_level++;
if ($quote_level == 2) { $quote_level = 0; }
}
else {
if ($line[$a] == " " and $quote_level == 0) {
$buffer = $buffer . "~~~~"; #Hackish magic key
}
else {
$buffer = $buffer . $line[$a];
}
}
}
$buffer = str_replace("\\", "", $buffer);
$array = explode("~~~~", $buffer);
return $array;
}
function bq_make_subquery($fields, $word, $mode) {
if ($mode == "not") {
$back = " LIKE '%$word%'))";
}
else {
$back = " LIKE '%$word%')";
}
if ($mode == "not") {
$front = "(NOT (";
$glue = " LIKE '%$word%' AND ";
}
else {
$front = "(";
$glue = " LIKE '%$word%' AND ";
}
$text = str_replace(" ", $glue, $fields);
$text = $front . $text . $back;
return $text;
}
function bq_make_query($fields, $text) {
$text = strtolower($text);
$text = bq_handle_shorthand($text);
$wordarray = bq_explode_respect_quotes($text);
$buffer = "";
$output = "";
for ($i = 0; $i<count($wordarray); $i++) {
$word = $wordarray[$i];
if ($word == "and" or $word == "not" and $i > 0) {
if ($word == "not") {
$i++;
if ($i == 1) { #invalid sql syntax to prefix the first check with and/or/not
$buffer = bq_make_subquery($fields, $wordarray[$i], "not");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "not");
}
}
else {
if ($word == "and") {
$i++;
if ($i == 1) {
$buffer = bq_make_subquery($fields, $wordarray[$i], "");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "");
}
}
else {
if ($word == "and") {
$i++;
if ($i == 1) {
$buffer = bq_make_subquery($fields, $wordarray[$i], "");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "");
}
}
}
}
}
else {
if ($i == 0) { # 0 instead of 1 here because there was no conditional word to skip and no $i++;
$buffer = bq_make_subquery($fields, $wordarray[$i], "");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "");
}
}
$output = $output . $buffer;
}
return $output;
}
function bq_simple ($return_fields, $tables, $check_fields, $query_text) {
$return_fields = str_replace(" ", ", ", $return_fields);
$tables = str_replace(" ", ", ", $tables);
$query = "SELECT $return_fields FROM $tables WHERE ";
$query = $query . bq_make_query($check_fields, $query_text);
#
# Uncomment to debug
#
return $query;
}
?>
I don't see the query in your code but the general idea is as follows:
$result = mysql_query("SELECT id, name FROM reports WHERE field = value") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo '' . $row['name'] . '';
}
Keep in mind the mysql_* functions are deprecated. You should use mysqli or PDO.

Remove occurances of ",,," from MySQL Database Output PHP

I am outputting the contents of my MySQL Database into a text file using the below code:
<?php
$host = 'localhost';
$user = 'myusername';
$pass = 'mypassword';
$db = 'mydbname';
$table = 'mytablename';
$file = 'outputfilename';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
//$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].",";
}
$csv_output .= "\n";
}
//echo $csv_output;
$myFile = "output.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $csv_output;
fwrite($fh, $stringData);
fclose($fh);
exit;
?>
However I would like to know how I could replace the occurances of the string ",,," with this: "," before it goes into the text file.
No need for preg_replace().
A simple str_replace will suffice.
$stringData = str_replace(',,,', ',', $csv_output);
problem is in:
$values = mysql_query("SELECT * FROM ".$table."");
if you got ,,,, it means that some columns has no value. Detect those columns, do not include them in SELECT statement.
if you will automatically (preg_replace, str_replace) change multiple commas to one comma, you are on good way to corrupt CSV file.
Use preg_replace(). Something like this (untested):
$pattern = '/\,\,\,/';
$replacement = ',';
echo preg_replace($pattern, $replacement, $stringData);
add this code:
while ($csv_output=str_replace(',,', ',', $csv_output)) echo '.';
OR change the for code:
for ( $j=0; $j<$i; $j++) {
$csv_output .= (isset($rowr[$j])) ? $rowr[$j]."," : '';
}
str_replace()
$stringData = str_replace(',,,', ',', $stringData);
http://php.net/str-replace

Categories