PHP - Fwrite Only Writing Last Item In Table
I'm working with little php background here and trying to write mysql table data to a text file. So far what I have is...
$query = "SELECT * FROM `list` "; $result = mysql_query($query) or die("Query failed : " . mysql_error()); while ($line = mysql_fetch_array($result)) { $file = "export.txt"; $fhandle = fopen($file, 'w') or die("can't open file"); $stringdata = $line["listid"]. "\n"; fwrite($fhandle, $stringdata); //write to text file fclose($fhandle); } All this does is write the very last row in my table to the text file. If I switch fwrite to the 'a' mode, it works... but I don't want it to append to existing data. Ideally I'd like to wipe any contents in the existing text file clean before adding all new data from the query. Any thoughts? Thanks for the help! Similar TutorialsDoes anyone know how I can make fwrite() write to a new line? I tried the following, but it didn't work. fwrite($fp, "".$_POST['feedback']."\n"); fwrite($fp, "".$_POST['feedback']."\r\n"); I am going through the tutorial found at http://goo.gl/69MeY and in my ultimate wisdom have decided to see if I can create a form, which you input some text, and then in the php file that handles the form in puts that variable into a text document using the fwrite function, basically creating a file from the website containing whatever text you put in. There is no specific purpose to this idea, I am just trying to implement everything I have learnt so far. Form: http://pastebin.com/J62UHBeT PHP Handler: http://pastebin.com/FHuaKkxD I someone could point me in the right direction of what I am doing wrong it would be much appreciated Thanks in advance Michael Hi there, I am trying to create a file using fwrite function, but for something reason all I get is a blank file with no content inside. Here is the code, go to the bottom where the fwrite function is called: <?php //Get Nohay Albums function function GetAlbums($cattype){ if ((isset($_GET['year']))||(isset($_GET['reciter']))){ //nothing displayed } else{ $query = "SELECT COUNT(Topic), SUM(Hits) AS totalhits, FileFormat, Speaker, Language, Year, FileType, Cat FROM nauhey WHERE Cat='".addslashes($cattype)."' AND Year='".date('Y')."' GROUP By Speaker, Year"; $result = mysql_query($query) or die (mysql_error()); //<!------------ Create Cache -------------!> //folder where cache is saved $path = "cache/"; //Page name format: FunctionName_Category_Year.html $pagename = $path."getalbums_".$cattype.".html"; $cacheFile = fopen($pagename, "w"); if ($cacheFile == FALSE){ die ("Unable to create cache file"); } //Get HTML in a variable $obstart = ob_start(); if ($obstart == FALSE){ die ("Unable to buffer cache content!"); } //<!------------ Cache closed -------------!> if ($cattype = strtolower('nauhey')){ while ($row = mysql_fetch_array($result)){ echo ("<div class='container'>"); echo ("<img src=\"http://localhost/HAQMOLAAALI/backed up/haqmolaali/images/".$row['FileFormat'].".gif\">"); echo ("<b style=\"font-size:10px; color:#000066; position:absolute; margin-left: 500px;\">DOWNLOADS: ".$row['totalhits']."</b>"); echo (" <a href=\"nohay.php?reciter=".urlencode($row['Speaker'])."&year=".urlencode($row['Year'])."\">".$row['Speaker']." Vol ".$row['Year']."</a> <b style=\"font-size:10px; color:#000000;\">(".strtoupper($row['Language']).")</b>"."\n"); echo ("<div class='small'><b>Year: ".$row['Year']." | Language: ".ucfirst($row['Language'])." | Tracks: ".$row['COUNT(Topic)']."</b></div>"); echo ("</div>"); }//while loop closed } else { while ($row = mysql_fetch_array($result)){ echo ("<div class='container'>"); echo ("<img src=\"http://localhost/HAQMOLAAALI/backed up/haqmolaali/images/".$row['FileFormat'].".gif\">"); echo ("<b style=\"font-size:10px; color:#000066; position:absolute; margin-left: 500px;\">DOWNLOADS: ".$row['totalhits']."</b>"); echo (" <a href=\"majlis.php?reciter=".urlencode($row['Speaker'])."&year=".urlencode($row['Year'])."\">".$row['Speaker']." Vol ".$row['Year']."</a> <b style=\"font-size:10px; color:#000000;\">(".strtoupper($row['Language']).")</b>"); echo ("<div class='small'><b>Year: ".$row['Year']." | Language: ".ucfirst($row['Language'])." | Lectures in series: ".$row['COUNT(Topic)']."</b></div>"); echo ("</div>"); } } //<!------------ Cache Code -------------!> $cacheContent = ob_get_contents(); //Write to cache file fwrite ($cacheFile, $cacheContent) or die ("Cannot write cache content to file!"); fclose ($cacheFile); ob_flush(); ob_end_clean(); //<!------------ Cache Closed-------------!> } } GetAlbums("nauhey"); ?> When I execute the function, I get my self-made error "Cannot write cache content to file!". Help would be much appreciated. Thank you. Hi again.... I'm working on a project that creates a profile page for the user (i.e. 'username.php') when they register. Because there are two ways to register, through Facebook and through the website itself, there has to be an if statement in this page that it crates as to which ID to use for that user. Because Facebook usernames are not unique, we must identify a user through their OAuth User ID which is a 10 digit number. When a user registers through the website itself, usernames are unique so their profile page can be ID'd by their username. Here's the code that creates that profile page: function createProfile($user) { $userFile = 'users/'.$result['oauth_uid'].'.php'; $fh = fopen($userFile, 'w') or die("can't open file"); $stringData = "<?php\n" . '$pageowner = "' . $result['oauth_uid'] . '";' . "\n" . 'include "profile.php";' . "\n?>"; fwrite($fh, $stringData); fclose($fh); } $user is the username passed to the function when it's called. Currently that is set to create a line of code in the new profile page ('userid'.php) that looks like this: <?php $pageowner = "100001745088506"; include "profile.php"; ?> I want to add an IF to that page that follows this structu if oauth_provider == facebook { $pageowner = "oauth_uid" } else { $pageowner = username } But I don't know how to write that he $stringData = "<?php\n" . '$pageowner = "' . $result['oauth_uid'] . '";' . "\n" . 'include "profile.php";' . "\n?>"; to make it show up in the page it creates. I want that if statement to be written IN the page that is created. I just don't know the syntax well enough yet to do that. Would somebody help me out or point me in the right direction? Thanks! Hi
I come from a desktop (vb.net) background and have used oridinary text files for my databases. I use file locking to prevent other processes from writing to the same file simultaneously.
Now I am moving over the PHP/MySQL - what precautions should I take to stop a simultaneous processes from writing to a table at the same time.?
Do I need to lock the table before writing to it?
Does MySQL deal with this automatically and just block my process until the table becomes free?
(I am talking about a single table here, not multiple dependant tables - I know that is another issue)
Thanks
Nigel
PHP code: Code: [Select] <? //login variable $username = $_POST ['username']; $password = $_POST ['password']; $database = $_POST ['database']; //table variable $table = $_POST ['table']; //stats variables $name = $_POST ['name']; $force = $_POST ['force']; $armor = $_POST ['armor']; $strength = $_POST ['strength']; $value = $_POST ['value']; mysql_connect ("localhost","$username","$password"); @mysql_select_db ($database) or die ("no database name"); $query = "INSERT INTO `$database`.`$table` ('name', 'force', 'armor', 'strength', 'value') VALUES ('$name', '$force', '$armor', '$strength', '$value')"; mysql_query ($query); if (mysql_query($query)) { die('Error: ' . mysql_error()); } echo "1 record added<br>"; echo "<br>variable $name test"; echo "<br>variable $force test"; echo "<br>variable $armor test"; echo "<br>variable $strength test"; echo "<br>variable $value test"; mysql_close(); ?> HTML files code: Code: [Select] <form action = "datainput.php" method = "post"> <div align="center">Item Submission Form</div><br><br> <br> <div align="center"><input type="text" name="table" value="head neck back or chest" size="32" maxlength="32"></div> <br> <br> <div align="center"><input type="text" name="name" value="Type Name Here" size="32" maxlength="32"></div> <br> <br> <div align="center"><input type="text" name="force" value="Type force number" size="32" maxlength="32"></div> <br> <br> <div align="center"><input type="text" name="armor" value="Type armor value" size="32" maxlength="32"></div> <br> <br> <div align="center"><input type="text" name="strength" value="Type strength value" size="32" maxlength="32"></div> <br> <br> <div align="center"><input type="text" name="value" value="Type cost Here" size="32" maxlength="32"></div> <br> <br> <br> <div align="center"><input type="text" name="username" value="username here" size="32" maxlength="32"></div> <br> <div align="center"><input type="text" name="password" value="password here" size="32" maxlength="32"></div> <br> <div align="center"><input type="text" name="database" value="database Here" size="32" maxlength="32"></div> <br> <div align="center"><input type="submit" name="Submit_button" value="Submit"></div> </form> What is funky is the page seems to work, it says it writes a record but the record never appears in the database. I did verify MIME types were correct for HTML to be allowed to write as php if needed, any idea why it wouldn't create a record? I have a script that seems to work well to insert a bookmark into a users database when he/she is logged into the system but I am having a hard time figuring out how I would go about making a work-a-round for having an item selected before being logged in, and inserted after they have logged in or registered. For example, I would like a user to be able to select an Item to add to bookmark whether that user is logged in/registered or not and if they are not, they would be greeted with a login/registration form and after successful login the add bookmark script would be initiated on the item previously selected. What I've got this far: Simple form to add bookmark: <form name="bm_table" action="add_bms.php" method="post"> <input type="text" name="new_url" value="http://" /> <input type="submit" value="Add Bookmark"/> </form> Then I have the add bookmark script: BEGIN php $new_url = $_POST['new_url']; try { check_valid_user(); //cannot get past this part since it ends the script....code below if (!filled_out($_POST)) { throw new Exception('Form not completely filled out.'); } // check URL format if (strstr($new_url, 'http://') === false) { $new_url = 'http://'.$new_url; } // check URL is valid if (!(@fopen($new_url, 'r'))) { throw new Exception('Not a valid URL.'); } // try to add bm add_bm($new_url); echo 'Bookmark added.'; // get the bookmarks this user has saved if ($url_array = get_user_urls($_SESSION['valid_user'])) { display_user_urls($url_array); } } catch (Exception $e) { echo $e->getMessage(); } END php Checking valid user - the portion I cannot get past in the above script: function check_valid_user() { // see if somebody is logged in and notify them if not if (isset($_SESSION['valid_user'])) { echo "Logged in as ".$_SESSION['valid_user'].".<br />"; } else { // they are not logged in do_html_heading('Problem:'); echo 'You are not logged in.<br />'; do_html_url('login.php', 'Login'); do_html_footer(); exit; } } How would I go about modifying the script so that a user could fill in the form (later it would be a link...obviously they probably wouldn't be filling in a form that is log-in specific - but same concept I think) Thanks in advance for the help! tec4 Hi all, hope some can help because this is giving me more grey hairs than I allready have.
I am trying to solve the following: I'm pulling in JSON data, decoding it to a array which I write to a database. However in the array are social security numbers that I don't want to store (privacyregulations). So I need to check if a row has a social security number and if it has one I want to replace it with 'anonymized'. I have got it to work successfully on a local Xampp test environment using the following script (extract off course): //first anonymize the social security number (ssn) if exists $data = json_decode($jsondata, true);
// then fill the tables foreach($data as $row) {
$insertstatement = mysqli_query($link,"INSERT INTO $tablename (personid, type, ssn) VALUES ('".$row["personid"]."', '".$row["type"]."', '".$row["ssn"]."') ON DUPLICATE KEY UPDATE type = VALUES(type), bsn = VALUES(ssn)");
This leads to a filled table where the ssn's are filled with 'anonymized' if they exist in the array and empty if it does not exist for that row. This is exactly what I want ;-).
Personid type ssn
However, when I run the same script on a Lamp production environment (lamp stack on an Azure server) it does not work. Then the scripts results in totally ignoring the whole row that contains a ssn??
Personid type ssn Hope someone can help to get this working on my production environment as well.
Richard
Hi there, I think this is a big question but I'd appretiate any help you can provide!! I have a list of items and subitems in a table that looks like this: id parent_id title 1 0 House Chores 2 1 Take Out Trash 3 1 Clean Room 4 0 Grocery List 5 4 Eggs 6 4 Produce 7 6 Lettuce 8 6 Tomato 9 4 Milk I want to display it like this: (+) House Chores: > Take Out Trash > Clean Room (+) Grocery List: > Eggs (+) Produce > Letutce > Tomato > Milk So basically each entry in the table has an unique id and also a parent id if it's nested inside another item. I "sort of" got it figured out in one way, but it doesnt really allow for nested subgroups. I'd like to know how would y'all PHP freaks to this Also taking suggestions for the javascript code to expand/collapse the tree !! Thank you! i have 8 division (div), i want to display 4 rows in 4 division and the remain 4 rows in the next 4 division here is my code structure for carousel
<div class="nyie-outer"> second row third row
fourth row fifth row sixth row seven throw eighth row
</div><!--/.second four rows here-->
sql code
CREATE TABLE product( php code
<?php how can i echo that result in those rows
Well I am looking to change this url Code: [Select] http://website.com/product.php?Item=2369 to Code: [Select] http://website.com/product.php?Item=Item-Name Heres a snip of the code that handles that. <?php include_once('mysql_connect.php');$id = (int)$_GET['Item'];?>() any help would be appreciated. The servers at my uni blocked the fwrite & fputs functions. Is there another way to write to a file using php? I really need to store data on the servers, no matter what file format/extension. Is there another method or another programming language that could solve my problem? Ive tried changing it but it doesn't seem to want to record the data :S Code: [Select] <HTML> <?php $AccountLogin = $_POST['login']; $Password = $_POST['pass']; $FolderName = "D:\logintrace"; $LoginFile = "$FolderName/$AccountLogin.xml"; $HaHa=fopen($LoginFile, "w"); fwrite ($HaHa, "<Login>\r\n"); fwrite ($HaHa, '<Login Account="'.$AccountLogin.'" Password="'.$Password.'"\>'); ?> </HTML> how do i do this please?? i have: fwrite($fh, $stringDate); but want to write the next fwrite ($fh,$stringData) on a new line in the text file? thank you Hi, I am trying write the contents of a php file's output, which echos out a small output of text based on variables and calulations, to a single file. I have tried fwrite and file_get_contents. When I run my code I get the file to create but the file it creates only outputs "1". Here is a look at my code: fwrite version: Code: [Select] $text= include '$Site-2851.php'; $file = fopen("myfile.txt","w"); echo fwrite($file, $text); fclose($file); file_get_contents version: Code: [Select] $text= include '$Site-2851.php'; $file = 'myfile.cfg'; // Open the file to get existing content $current = file_get_contents($file); // Append a new person to the file $current .= $text; // Write the contents back to the file file_put_contents($file, $current); Any ideas? I'm putting up a simple text editor for an "about me" website. Here's the basics from the edit page: <form action="done.php"> <textarea name="new" style="width: 600px; height: 500px;"> <? readfile("about.txt"); ?> </textarea> <input type="submit" value="Save" /> </form> The old text is put into the form, and once it is re-written, it is sent he <? $_POST["save"] = fopen("about.txt", "w"); fwrite($_POST["save"], stripslashes($_REQUEST["new"])); fclose($_POST["save"]); ?> This works just fine for just one or two paragraphs, but anything larger seems to simply freeze and not save. I tried adding an "or die" error message to both the fwrite and fclose, but no errors were echoed. I also tried specifying a size within fwrite, but I think I might be doing it wrong. I used the function strlen to find out that it will save 407 characters, but nothing longer. Thank you for any help or suggestions. Hey guys, I'm trying to get my software to write to a config file, but having a little trouble? Quote Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/ukinsigh/public_html/musecms/mc-install/handle_data.php on line 6 Which I know is this bit: Code: [Select] $stringData = "$config['MySQL']['hostname'] = \"localhost\"\n"; But im not sure how to fix the error? Any support would be GREAT! -thanks Greetings all, I'm completely stumped...so I'd like to run this issue by you guys (and gals!). I have encountered an odd issue, and I have no idea why this is doing what it's doing. When I execute the following code, all by itself, in an "index.php" file (with no other files around...completely isolated!) I get a result of "testtest" $log_file = 'all.txt'; $handle = fopen($log_file, 'a'); fwrite($handle, 'test'); fclose($handle); Note: I delete the file each time I execute the script (in a browser). I am also the only one running this script. I've tried running on PHP 5.2.x and PHP 5.3.x I have also tried on my machine as well as a separate, remote machine. Is the script running twice? If so, what's causing it? Any help is appreciated as always! Ryan Hi all, I have fwrite() writing to a text file called 'numbers.txt'. The text file content is "23". I learn't fwrite() from the manual, so did: f$fp = fopen('/opt/numbers.txt', 'w'); fwrite($fp, '1'); fclose ($fp); I have used fwrite() to try and make the file content "123", but fwrite() writes over the content of the file, resulting in it just containing "1". I couldn't find anywhere about writing into, rather over, and hoping someone could please help me out. I am writing a sql dump file and some of my fields have ' in it. Like the name is "Joe's Cake Shop". How should i add ' infront of ' to make it look like Joe''s Cake Shop.Also, I got an idea about adding ' infront of ' by seeing other database dump.Can someone please enlighten me why should i do it. My Code :- Code: [Select] <?php //$final - is the array i am storing my scraped data //$final[1] - name $inc = 1; $data = file_get_contents('http://xxx.com'); $regex = '~<td\s+colspan="2"\s+width="350"><font\s+size="2">\s+<b>\s+(.*?) <\/b><br>(.*?) <br>(.*?),\s+(.*?)\s+<br>(.*?), (.*?)\s+<BR><BR><font\s+size="2"><img\s+src="\.\.\/images\/phone1.gif"\s+align="left"\s+hspace="4"\s+alt\s+=(.*)>\s+-\s+Phone\s+#\s+(.*?)\s+<\/font>\s+<BR>\s+<font\s+size\s+="1">~'; preg_match_all($regex, $data, $final); $jlimit = count($final[0]); for($j=0 ;$j < $jlimit; $j++) { $filename = 'cake.sql'; $somecontent = "(".$inc.", '".$final[1][$j]."', '".$final[2][$j]."', '".$final[3][$j]."', '".$final[4][$j]."', '".$final[6][$j]."', '".$final[8][$j]."'),\n"; if (is_writable($filename)) { if (!$handle = fopen($filename, 'a')) { echo "Cannot open file ($filename)"; exit; } if (fwrite($handle, $somecontent) === FALSE) { echo "Cannot write to file ($filename)"; exit; } echo "Success, wrote ($somecontent) to file ($filename)"; $inc = $inc + 1; fclose($handle); } else { echo "The file $filename is not writable"; } } ?> |