PHP - Sorting Output From Flat File Db
Given this script:
<?php $file = file('info.txt'); $statelist = array (1=> "California", "Florida", "Illinois", "New York", "Texas"); foreach ($file as $line => $data) { list($state, $abbrev, $population) = explode('|', trim($data)); for ($x=1; $x<5; $x++) { if ($statelist[$x] == $state) { echo $state . ", " . $abbrev . " - " . $population . '<br />'; } } } ?> and this flat file (info.txt): Code: [Select] California|CA|36,756,666 Texas|TX|24,326,974 New York|NY|19,490,297 Florida|FL|18,328,340 Illinois|IL|12,901,563 This is what is outputted: Code: [Select] California, CA - 36,756,666 Texas, TX - 24,326,974 New York, NY - 19,490,297 Florida, FL - 18,328,340 Illinois, IL - 12,901,563 How can I sort the output by the index value of the "statelist array" so get this output: Code: [Select] California, CA - 36,756,666 Florida, FL - 18,328,340 Illinois, IL - 12,901,563 New York, NY - 19,490,297 Texas, TX - 24,326,974 Could ksort($statelist) be implemented? Similar Tutorialsit is displaying the lastnames in the order they are in the profile but do not know how to get it to sort by lastname - please help <?php $lines = file('database/profile.txt'); foreach($lines as $thisline){list($p_id,$p_status,$p_filestart,$p_filemodified,$p_first,$p_middle,$p_last,$p_nick) = explode('|',$thisline);{ $names []= $p_last.', '.$p_first.' '.$p_middle.'.'; foreach($names as $value); {echo ''.$value.'<br>';}}} ?> Hi guys, is there anyway to process this $result from a mysql query inside PHP so that the data below will be formatted to a pivot-like table? The number of rows and columns of the output 'table' will be indefinite. Thanks so much! Data: ID Row Col Name 1 1 A A1 2 2 A A2 3 3 A A3 4 1 B B1 5 2 B B2 6 3 B B3 7 1 C C1 8 2 C C2 9 3 C C3 Results: A1(1) A2(2) A3(3) B1(4) B2(5) B3(6) C1(7) C2( C3(9) I am creating a guestbook for a friend who has access to a hosting server for free, however they are reluctant to let us create databases so i have used a flat file system to create a simple login and register system. On this site I have also included a flatfile guestbook, I've not coded this from scratch as I'm just not php freak enough for it. The guestbook requires a name and email address to submit a post, i would like to change this so that it takes the details straight from the flatfile and not be displayed at all if there is no-one logged in. Guestbook.php <?php // find out the domain: $domain = $_SERVER['HTTP_HOST']; // find out the path to the current file: $path = $_SERVER['SCRIPT_NAME']; $url = "http://" . $domain . $path ; extract($_POST); if($Submit){ $date = date('D d Y h:i'); $comment=eregi_replace("\r\n","*",$comment); $comment=eregi_replace("\n","*",$comment); $fp = fopen("bin/guestbook.nfo","a+"); if(!$fp) { echo 'Error: Cannot open file.'; exit; } fwrite($fp, $date."||".$name."||".$email."||".$comment."\n"); fclose($fp); } ?> <div align="center"> <h2><span class="style1">Guestbook </span><br> </h2> </div> <form name="form1" method="post" action="<?php echo $url;?>"> <label>Name <input type="text" name="name"> </label> <label>Email <input type="text" name="email"> </label> <p> </p> <p> comment<br> <textarea name="comment" cols="40" rows="10"></textarea> <br> <label> <input type="submit" name="Submit" value="Sign"> </label> <br> </p> </form> <hr> <?php $userinfo = file("cgi-bin/guestbook.nfo"); echo '<table border="0">'; foreach($userinfo as $val) { //explode that data into a new array: $data = explode("||", $val); echo '<tr><td>'.$data[0].'</td></tr>'; echo '<tr><td>'.$data[1].' Wrote:</td></tr>'; $data[3]=eregi_replace("\*","<br>",$data[3]); echo '<tr><td>'.$data[3].'</td></tr>'; echo '<tr><td>Email:'.$data[2].'<hr></td></tr>'; } echo '</table>'; ?> Hello Mates, I am in need of help. I have a Flat File News Script. I am not sure how to build the Delete script.. i am not knew to PHP but kinda new to Flat File Database.. the reason why im using FFD is because my service doesn't allow mysql on the cheaper priced web pages.. i have 4 fields ID || user_name || title || message i want it to check the id because it will be in the url like http://webpage.com/delete_news.php?id=3 and the id 3 and the other fields in id 3 is deleted. Thank you Valkeri2010 Hi, I use MySQL for real projects of course... but, I like to challenge myself and I was wondering how people make advance applications with Flat File databases... My questions are... >Display >Reading The Flat File Data >Sorting it Alphabetically For Display >How to create a WHERE clause affect with the data >Storage >Adding Records >Deleting Records >Editing Records I went over a lot of this on my own, but I'm stuck on certain parts because google only has so much on Flat File Databases... also how would u secure a Flat File Database from someone just simply direct linking to it and viewing it? This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=315620.0 I currently have a flat file user registration and login in system. I also have a simple guestbook which i didn't code myself, the guest book currently requires the user to type in there name and e-mail address to make a post. how ever i would like them to have to login and if they aren't logged in then don't display the guestbook. Live version: B50crew.co.uk Guestbook.php: Code: [Select] <?php // find out the domain: $domain = $_SERVER['HTTP_HOST']; // find out the path to the current file: $path = $_SERVER['SCRIPT_NAME']; $url = "http://" . $domain . $path ; extract($_POST); if($Submit){ $date = date('D d Y h:i'); $comment=eregi_replace("\r\n","*",$comment); $comment=eregi_replace("\n","*",$comment); $fp = fopen("bin/guestbook.nfo","a+"); if(!$fp) { echo 'Error: Cannot open file.'; exit; } fwrite($fp, $date."||".$name."||".$email."||".$comment."\n"); fclose($fp); } ?> <div align="center"> <h2><span class="style1">Guestbook </span><br> </h2> </div> <form name="form1" method="post" action="<?php echo $url;?>"> <label>Name <input type="text" name="name"> </label> <label>Email <input type="text" name="email"> </label> <p> </p> <p> comment<br> <textarea name="comment" cols="40" rows="10"></textarea> <br> <label> <input type="submit" name="Submit" value="Sign"> </label> <br> </p> </form> <hr> <?php $userinfo = file("cgi-bin/guestbook.nfo"); echo '<table border="0">'; foreach($userinfo as $val) { //explode that data into a new array: $data = explode("||", $val); echo '<tr><td>'.$data[0].'</td></tr>'; echo '<tr><td>'.$data[1].' Wrote:</td></tr>'; $data[3]=eregi_replace("\*","<br>",$data[3]); echo '<tr><td>'.$data[3].'</td></tr>'; echo '<tr><td>Email:'.$data[2].'<hr></td></tr>'; } echo '</table>'; ?> Login: Code: [Select] <?php // find out the domain: $domain = $_SERVER['HTTP_HOST']; // find out the path to the current file: $path = $_SERVER['SCRIPT_NAME']; $url = "http://" . $domain . $path ; extract($_POST); if($Submit){ $date = date('D d Y h:i'); $comment=eregi_replace("\r\n","*",$comment); $comment=eregi_replace("\n","*",$comment); $fp = fopen("bin/guestbook.nfo","a+"); if(!$fp) { echo 'Error: Cannot open file.'; exit; } fwrite($fp, $date."||".$name."||".$email."||".$comment."\n"); fclose($fp); } ?> <div align="center"> <h2><span class="style1">Guestbook </span><br> </h2> </div> <form name="form1" method="post" action="<?php echo $url;?>"> <label>Name <input type="text" name="name"> </label> <label>Email <input type="text" name="email"> </label> <p> </p> <p> comment<br> <textarea name="comment" cols="40" rows="10"></textarea> <br> <label> <input type="submit" name="Submit" value="Sign"> </label> <br> </p> </form> <hr> <?php $userinfo = file("cgi-bin/guestbook.nfo"); echo '<table border="0">'; foreach($userinfo as $val) { //explode that data into a new array: $data = explode("||", $val); echo '<tr><td>'.$data[0].'</td></tr>'; echo '<tr><td>'.$data[1].' Wrote:</td></tr>'; $data[3]=eregi_replace("\*","<br>",$data[3]); echo '<tr><td>'.$data[3].'</td></tr>'; echo '<tr><td>Email:'.$data[2].'<hr></td></tr>'; } echo '</table>'; ?> Session.php <?php class user { var $file_dir = ""; function start($time = 3600) { session_set_cookie_params($time , ''); session_name('afroxav-login'); session_start(); // Reset the expiration time upon page load if (isset($_COOKIE['afroxav-login'])) { setcookie('afroxav-login', $_COOKIE['afroxav-login'], time() + $time, '', 'localhost', 0, 1); } if (!isset($_SESSION['info'])) { $this->data = array('name' => 'Anonymous', 'logged' => false); } else { $this->data = $_SESSION['info']; } } function check_login() { if ($this->data['logged'] !== true) { return false; } else if ($this->data['logged'] === true) { if ($this->data['name'] !== 'Anonymous') { return true; } return false; } return false; } function login($user, $pass) { $logins_raw = @file_get_contents($this->file_dir . 'users.php'); $logins_processed = str_replace('<?php exit; ?>', '', $logins_raw); $logins_array = explode('\n', $logins_processed); foreach ($logins_array as $id => $line) { $logins[$id] = explode('|', $line); } $pass = $this->hash_pass($pass); foreach ($logins as $user_info) { if ($user_info[1] == $user) { if ($user_info[2] == $pass) { $this->update_session($user_info); return true; } } } return false; } function hash_pass($string) { return hash('sha512', $string); } function logout() { $_SESSION['info'] = array('name' => 'Anonymous', 'logged' => false); $this->data = $_SESSION['info']; return true; } function prep_reg_array($name, $pass, $email, $mod = 'false', $admin = 'false') { $id_raw = @file_get_contents($this->file_dir . 'id.php'); $id = str_replace('<?php exit; ?>', '', $id_raw); $id = $id + 1; @file_put_contents($this->file_dir . 'id.php', '<?php exit; ?>' . $id); return array($id, $name, $this->hash_pass($pass), $email, $mod, $admin); } function register($userdata) { $write = file_put_contents($this->file_dir . 'users.php', '\n' . implode('|', $userdata), FILE_APPEND); return ($write !== false) ? true : false; } function update_session($array) { $_SESSION['info'] = array( 'id' => $array[0], 'name' => $array[1], 'pass' => $array[2], 'email' => $array[3], 'mod' => $array[4], 'admin' => $array[5], 'logged' => true ); $this->data = $_SESSION['info']; } }; //html related functions //not related at all with the sessions function html_start($title) { header('Content-type: text/html'); echo "<html>\n"; echo "<head>\n"; echo "<title>\n"; echo $title; echo "</title>\n"; echo "</head>\n"; echo "<body>\n"; echo "<h1>\n"; echo $title; echo "</h1>\n"; } function html_nav() { global $user; echo "<div>\n"; echo "Navigation\n"; echo "<ul>\n"; echo "<li><a href=\"?page=home\">Home</a></li>\n"; if ($user->check_login() == true) { echo "<li><a href=\"?page=logout\">Log Out</a></li>\n"; } else { echo "<li><a href=\"?page=login\">Log In</a></li>\n"; echo "<li><a href=\"?page=register\">Register</a></li>\n"; } echo "</ul>\n"; echo "</div>\n"; } function html_end() { echo "</body>\n"; echo "</html>\n"; } ?> I want to make the news feed on my website easier to maintain. I just created a form that I will use to add the information. The form saves the files that it creates as "entry-date-time.txt" and places it in a folder for the year and a sub folder for the month. Such as "2011\09". I have displayed data from a single flat file before, but I am unsure how to go about displaying the data from multiple files. Can anyone show me an example? I want to be able to paginate the data, displaying a number of updates per page from newest to oldest. I don't have MySQL access on the server or I'd just use that, instead. This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=333509.0 Folks, I have a flat file or CSV, which has the tree structure of the Nesed Categories (All are delimited by either > or tab, it can be set easily). I want a PHP/Mysql code/routine that i can automaticaly create a table in MYsql with Parent Child relationship. Logic is there in my mind, every distinct Node will be an ID which while every child node will have the PID (parent ID) of its Parent. So the below data from flat file (Actual Data can be N Level Deep at least 4 Level): Electronics Electronics > Phones Electronics > Phones > Iphone Electronics > Phones > LG Electronics > Phones > Samsung Electronics > Phones > Samsung > 3G Electronics > Laptops Electronics > Laptops > Dell Electronics > Laptops > Sony Electronics > Laptops > HP Electronics > Laptops > HP > Core 2 Duo Will look like this in Mysql Table Structu Quote http://pastie.org/1592730 This is the Logic i need ot adopt, but i have no clue on how to code it to extract in this table structure and define this paren tchild mapping automatically. Can someone Help me out wiht this? Cheers Natasha T I have a login system that uses a flat file database. The flat file is in a directory outside the public_html. My questions; 1- Is is still possible to hack into that file? Currently I do not encrypt the passwords as I have been told that having the file outside the public_html makes the file unavailable to the public. This allows me the advantage of sending the Username and Password to the user in an email if they forget there password or username. Otherwise- I would have to set up a more complicated method to allow them to change their password to re-gain access to the site. I have an SSL on the site also so I am not worried about packet sniffing. Thanks I am pretty new to php and trying to teach myself. I can't get the values from this form to write to my flat file called orders.txt: browse_index.php <?php include("includes/menu_members.php") ?> <div id="content"> <h1>SHOPPING CART</h1> <a href="browse_index.php">CLICK HERE TO CONTINUE SHOPPING</a> <?php echo ' <table border="0"> <tr> <td><form id="f2" method="post"name="f2"><input type="submit" action="order_summary.php" name="submit2" value="submit order"></td> '; if(isset($_POST['submit'])) { $itemname = $_POST['h1']; //echo $_SESSION['itemname'][$itemname]; unset($_SESSION['itemqty'][$itemname]); unset($_SESSION['itemprice'][$itemname]); unset($_SESSION['itemname'][$itemname]); } echo "<br/><br/>"; echo "<table border='8' bgcolor='#efefef'>"; echo "<tr><th>Name</th><th>Quantity</th><th>Price</th><th>Subtotal</th></tr>"; foreach($_SESSION['itemname'] as $key=>$value) { echo '<tr><td><b>'.$_SESSION['itemname'][$key].'</b></td> <td>'.$_SESSION['itemqty'][$key].'</td> <td>$'.$_SESSION['itemprice'][$key].'</td> <td name="subtotal">$'.($_SESSION['itemqty'][$key] * $_SESSION['itemprice'][$key]).'</td> <td><form id="f1" method="post" name="f1"><input type="submit" name="submit" value = "delete"><input type="hidden" name="h1" value='.$key.'></td></tr>' ; } ?> order_summary.php: <?php session_start (); $date = date ("H:i jS F"); $outputstring = $date."/t" .$_POST['h1']. ":" .$_SESSION['itemqty'][$key]. ":" .$_SESSION['subtotal'][$key]. ":" ."\n"; $fp = fopen("orders.txt","a"); fwrite($fp, $outputstring); fclose($fp); ?> Can someone direct me where I am going wrong??? Hi All Please can someone help me. I have a CSV file with over 3000 lines. Each one contains the following information Country Insurance Name Mandatory or Optional Description and Coverage Group SIPP Cost Per Day Cost Per Week Cost Per Month Deductable I have written the following script to read line by line, compare the country and insurance with the previous and if it is the same, tag certain parts of each line onto the end of the previous. However, I am getting no output from this, and I keep getting an error saying I am using too much memory or my computer hangs. I am fairly new to php so any pointers would be good. Firstly, does my script look like it should do what I want it to do? If so, any clues how to get around the momory issue. If not, what have I done wrong? Cheers guys <?php //open file paths $handle=fopen("insurances.csv","r"); $handle_out=fopen("insuranceoutput.csv","a"); //writes the first line of the csv file into an array to act as a comparrison if($handle){ $line=fgets($handle); $line_array=explode(",",$line); $full_array=$line_array; fclose($handle); } } if($handle) { while (!feof($handle)) { // read one line into array $line=fgets($handle); $line_array=explode(",",$line); fclose($handle); //test to see if country matches previous while ($line_array[0] == $full_array[0]) { //test to see if insurance matches previous while ($line_array[1] == $full_array[1]) { //write array values 4 - 9 to main array $full_array[]=array("$line_array[4]","$line_array[5]","$line_array[6]","$line_array[7]","$line_array[8]","$line_array[9]"); } } //write to new file when new insurance is found foreach($full_array as $output) { fwrite($handle_out, "$output,"); } fwrite($handle_out,"\n"); fclose($handle_out); } // write to new file if new country is found. foreach($full_array as $output) { fwrite($handle_out, "$output,"); } fwrite($handle_out,"\n"); fclose($handle_out); } } ?> I'm looking to order my upload files in a specific order. I believe the default is a random upload order, but I would like to change this based on the file name, which I'm having difficulty with.
The file names would be for example;
'01 smiley' '02 dog' '03 cat'Currently I used a 'Drag & Drop' multiple file upload although this just uploads in any random order to my database table, I'd like to upload it by numeric order as above. Code so far (upload code works, just the order needs work)... $count = count($_FILES['upload']['name']); $in=0; while($in<$count) { //upload here $in++; }I think I need to sort()? before my while loop, but having difficulty getting this correct. How would I be able to sort each file into a correct order. Many thanks. Edited by Veltu, 12 December 2014 - 05:46 AM. I am using SimpleXMLElement to generate an xml file. I am having some difficulty with formating the file. Hoping someone can assist. (not having problem getting the data...just unsure when to use ->addChild, ->addAttribute and anything else) This is the structure of how the file needs to be appear: Code: [Select] <?xml version="1.0"?> <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/" xmlns:jwplayer="http://developer.longtailvideo.com/trac/" > <channel> <title>MRSS Playlist</title> <item> <title>Cardio routine with handweights</title> <media:content url="videos/set2_first_5min.flv" /> <media:thumbnail url="thumbs/set2_first.png" /> <description>side jumps, arm curls, leg squats, arm lifts</description> <jwplayer:duration>25</jwplayer:duration> <jwplayer:start>5</jwplayer:start> </item> </channel> </rss> Thanks as always! DK Hello I need help with making a script. The script shall get the output of a jar file, by reading it from the stream. First it should start up the jar file. (exec I guess?) Then it should start to read from the stream and post it on the site. As a little "bonus", it would be nice if it could input things to the stream! Kind regards Worqy I just wrote a php page that pulls live data from a database and presents it in an XML layout. In Internet Explorer, I can Edit, Select All, then Copy-Paste and save as XML. The resulting XML works fine. In Firefox, I can click File, Save Page As, select Text Files, then name it as an XML. Again, it works fine as XML. So..... how do I skip the Copy/Paste (IE) or Save Page As (Firefox) steps and write the output directly to an XML file? I've played with stdout(), buffers, page capturing utilities (wget, cURL, httrack, etc....), but no luck so far. This creates a pretty intense page due to the amount of data involved (1.3+ MB). Any help is appreciated! I use this code: Code: [Select] <?php $databasehost = "localhost"; $databasename = "export_ajur"; $databasetable = "invoice"; $databaseusername ="root"; $databasepassword = "password"; $fieldseparator = ","; $lineseparator = "\n"; $csvfile = "1.csv"; $addauto = 0; $save = 1; $outputfile = "output.sql"; if(!file_exists($csvfile)) { echo "File not found. Make sure you specified the correct path.\n"; exit; } $file = fopen($csvfile,"r"); if(!$file) { echo "Error opening data file.\n"; exit; } $size = filesize($csvfile); if(!$size) { echo "File is empty.\n"; exit; } $csvcontent = fread($file,$size); fclose($file); $con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error()); @mysql_select_db($databasename) or die(mysql_error()); $lines = 0; $queries = ""; $linearray = array(); foreach(explode($lineseparator,$csvcontent) as $line) { $lines++; $line = trim($line," \t"); $line = str_replace("\r","",$line); $linearray = explode($fieldseparator,$line); $linemysql = implode("','",$linearray); if($addauto) $query = "insert into $databasetable values('$linemysql');"; else $query = "insert into $databasetable values ('$linemysql');"; $queries .= $query . "\n"; @mysql_query($query); } @mysql_close($con); if($save) { if(!is_writable($outputfile)) { echo "File is not writable, check permissions.\n"; } else { $file2 = fopen($outputfile,"w"); if(!$file2) { echo "Error writing to the output file.\n"; } else { fwrite($file2,$queries); fclose($file2); } } } echo "Found a total of $lines records in this csv file.\n"; ?> And th output is: Code: [Select] insert into invoice values ('ID_PURCHASE_INVOICE','DOC_TYPE_NAME','DOC_EXT_CODE','DOC_NUM','DOC_DATE','WOVAT_AMOUNT','VAT_AMOUNT','TOTAL_AMOUNT','CONTRAGENT_NAME','CONTRAGENT_BULSTAT','CONTRAGENT_VATNUMBER','CONTRAGENT_POST_ADDRESS','CONTRAGENT_ZIP','CONTRAGENT_CITY','CONTRAGENT_AREA','CONTRAGENT_STREET','CONTRAGENT_MOL','CONTRAGENT_PHONE','CONTRAGENT_BANK','CONTRAGENT_BANK_CODE','CONTRAGENT_BANK_ACCOUNT','CONTRAGENT_EXT_CODE','CONTRAGENT_EMAIL','PAYMENT_NAME','DOC_MARKER1','DOC_MARKER2','DOC_MARKER3','DOC_MARKER4','DOC_MARKER5','DOC_MARKER6','DOC_MARKER7','DOC_MARKER8','DOC_MARKER9','DOC_MARKER10'); insert into invoice values ('108826','ДАНЪЧНА ФАКТУРА','1','111366','2/15/2012','160.08','32.02','192.1','ПРЕЦИЗ ООД','103565237','BG103565237','ВАРНА ГЕН.КОЛЕВ 38','','','','','','','','','','','','БАНКА','','','','','','','','','',''); insert into invoice values ('108830','ДАНЪЧНА ФАКТУРА','1','1002304974','2/15/2012','872.33','174.46','1046.79','ОМВ БЪЛГАРИЯ ООД','121759222','BG121759222','','','СОФИЯ','','','','','','','','','','БАНКА','','','','','','','','','',''); insert into invoice values (''); I need to remove last line ' insert into invoice values (''); . How to change my code? Hi guys <?php sleep(00); $handle = fopen("http://www.myurl.com/?bla=bla=bla" , "r"); fclose($handle); ?> How do i prevent this from outputing to a file on my server. I only need the url to be accessed to add a new row of data to my DB. Any Ideas? Regards Mark I am trying to make PHP output a file in html and using the following code. Code: [Select] <?php readfile("./1/index.html"); ?> ... but it isn't working. How would I get PHP to output a file as HTML? |