PHP - Line Duplication
Hello there,
I'm looking for a PHP method to duplicate a line, for example if I wanted to duplicate this line: mail($to,$subject,$message,$headers); How could I specify a value of how many are displayed instead of doing this to send it 3 times: mail($to,$subject,$message,$headers); mail($to,$subject,$message,$headers); mail($to,$subject,$message,$headers); Many thanks Similar TutorialsHi
I am reading in data from a csv file
if (($handle = fopen("data.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { echo "User Name: $data[0]"; echo "Booking IDs: $data[1]"; } echo "<hr>";The problem is some of the usernames are duplicated so get outputted the same user name 20 times but with different IDs, obviously but I am unsure how to group them together. I can't seem to figure out how to write if the next username is the same as current then just add another ID not go through the entire loop. Any ideas? Thanks As part of an image gallery I am trying to INSERT data into a table to make accessible the relevant info of individual images - the problem I have encountered is that each query seems to be being inserted twice, and I can't figure out why. The code = Code: [Select] <?php /*============================================== Connect to MySQL and select the correct database ==============================================*/ mysql_connect("localhost", "uname", "pwd") or die(mysql_error()); echo "Connected to MySQL<br />"; mysql_select_db("gallery_db") or die(mysql_error()); echo "Connected to Database gallery_db.<br />"; /*============================================= Include the files needed to undertake this task =============================================*/ include("functions.php"); /*========================= Set up arrays and variables =========================*/ $store = array(); $exif = array(); $folder = "./images/"; $insrt = 'INSERT INTO images VALUES (img_id, '; $file_name = ''; $file_location =''; $copyright =''; $caption = ''; $file_date = ''; $file_time = ''; $camera = ''; $speed = ''; $fNo = ''; $ISO = ''; /*================================= Open folder and read relevant files =================================*/ if ($handle = opendir('./images')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $file_name = $file; //>>> File Name <<< $file_location = $folder . $file; //>>> File Location <<< $exif = exif_read_data($file_location, 'EXIF'); //>>> Read exif data <<< /*============================================================== Check if the 'Copyright' info existe in the exif data, and if it doesn't set the $copyright variable to the relevant value. ==============================================================*/ if (array_key_exists('Copyright', $exif)) { $copyright = $exif['Copyright']; } else { $copyright = "copy name"; } $caption = $exif['COMMENT'][0]; //>>> Get the Caption <<< //>>> Re-format DateTime into separate date and time var's $file_date & $file_time <<< $temp = substr($exif['DateTime'], 0, 10); $file_date = substr($temp, 8, 2) . substr($temp, 4, 4) . substr($temp, 0, 4); $file_time = substr($exif['DateTime'], 11, 8); //>>> Set the rest of the variables <<< $camera = $exif['Model']; //>>> Get the camera make and model <<< $speed = $exif['ExposureTime']; //>>> Get the shutter speed <<< $fNo = $exif['COMPUTED']['ApertureFNumber']; //>>> Get the f No. <<< $ISO = $exif['ISOSpeedRatings']; //>>> Get the ISO rating <<< //>>> Fill the $store[] array with the relevant bits for each seperate query <<< $store[] = $insrt . "'" . $file_name . "', " . "'" . $file_location . "', " . "'" . $copyright . "', " . "'" . $caption . "', " . "'" . $file_date . "', " . "'" . $file_time . "', " . "'" . $camera . "', " . "'" . $speed . "', " . "'" . $fNo . "', " . "'" . $ISO . "')"; } } closedir($handle); } /*============================================================================= Get individual queries from $store[] and INSERT INTO images the relevant VALUES =============================================================================*/ $num_queries = count($store); //>>> Check the number of queries in the array $store $loop = 0; //>>> Starting point for query No. bearing in mind that array keys are numbered from zero while ($loop <= $num_queries - 1) { $query = $store[$loop]; if (!mysql_query($query)){ die('Error: ' . mysql_error()); } mysql_query($query); $loop++; } ?> I know it's not pretty, but that can be attended to once working properly. I am quite sure that it will be a very simple solution, probably so simple that I haven't even thought of it. I've recently had a problem with my admin site where PHP sessions, which are stored in a MySQL database, are duplicating and causing the page to return to the login screen. Usually the site works fine in Firefox, but stops working in IE and Safari. This problem suddenly appeared over night with no change to the files. Due to the amount of code, I'm reluctant to post it all, but does anyone have a suggestion on why this could be happening and how to solve it? <?php // Daniel URL duplicator. // Input links list. $linksList = "links.txt"; // How many times to duplicate the url? $manyTimes = 1000; // Read in the list. for ($x = 0; $x <= $manyTimes; $x++) { $handle = fopen($linksList, "r"); $line = fgets($handle); echo $line; fclose($handle); } ?>Hey Guys, I'm stuck on this simple bit of code lol what I'm trying to do is load in a list of urls: site1.com site2.com site3.com etc For each site that is read, I'm trying to duplicate it X times, above would print to screen the same url 1000 times, then move onto the next print it 1000 times etc until the list is done (or how ever many times I select) I can't think of the best way to do it! any help would be appreciated guys! Graham Hi everyone, I don't know whether this is a PHP or MySql problem, but I think it is the former. The following code queries the database correctly, (and before you ask, there are no duplicate database entries), but the output duplicates every row. e.g., hammer (jpg image) hammer hammer (jpg image) hammer saw (jpg image) saw saw (jpg image) saw screwdriver (jpg image) screwdriver screwdriver (jpg image) screwdriver and so on. I cannot see why the code causes the row to repeat. Code: [Select] <?php session_start(); if (isset($_SESSION['id'])) { // Put stored session variables into local php variable $id = $_SESSION['id']; $userId = $_SESSION['userId']; $userGroup = $_SESSION['userGroup']; $managerId = $_SESSION['managerId']; } include_once("demo_conn.php"); $sql = mysql_query("SELECT * FROM users WHERE id='$id'"); while($row = mysql_fetch_array($sql)) { // Get member data into a session variable $egroup = $row["egroup"]; session_register('egroup'); $_SESSION['egroup'] = $egroup; } $query = mysql_query("SELECT topics.url_big, topics.url_small, topics.title, topics.$egroup, quiz.passState, quiz.userDate FROM topics INNER JOIN quiz ON (topics.managerId = quiz.managerId) WHERE topics.$egroup = 1 ORDER BY title ASC"); while ($row1 = mysql_fetch_array($query)) { echo "<a href='../../wood/wood_tool_images/{$row1['url_big']}' target='_blank'><img src='../../wood/wood_tool_images/{$row1['url_small']}' /><br />\n"; echo "{$row1['title']} <br />\n"; } ?> Hi I have this simple code $one = rand(1,9); $two = rand(1,9); $three = rand(1,9); but I need to change it so that they are all unique and the same number is not used more than once can anyone help? thanks Please help and amend the code Save without repetition required $read[0] I hope that my example is clear to you I apologize for bothering you. I am not good in English <?php $fileLocation = getenv("DOCUMENT_ROOT") . "/rt.txt"; $file = fopen($fileLocation,"a"); $n1 = $_POST['n1']; $n2 = $_POST['n2']; for($i = 0; $i < count($file); $i++){ $read = explode("|", $file[$i]); if($n1 == $read[0]){ echo 'Repetition'; } else { fwrite($file,$n1.'|'.$n2."\r\n"); }
what im trying to do is take a youtube embed code find the URL code for that video and remove all other parts of the code keeping only the URL of the video after i get the URL by it self then replace the http://www.youtube.com/ part of the URL with http://i2.ytimg.com/vi/ to do this i know that i need something like this to get the URL of the video http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+) but how to only return just the URL is something idk how to do then use str_replace http://www.youtube.com/(?:v|cp)/" with http://i2.ytimg.com/vi/ so in the end im asking if anyone know how to remove all other codes i dont want and only keep the URL this may have to be done using "regex" im not sure as i dont know to much about regex and what it can do but does sound like it would help lol Dear All Good Day, i am new to PHP (a beautiful server side scripting language). i want to send a mail with line by line message i tried with different types like by placing the things in table and using <br /> but the thing is the tags are also visible in the message of the mail. Here is my code: $message1 = "Name :". $_REQUEST['name']."<br />"; $message1 .= "Surname :". $_REQUEST['surname']."<br />"; $message1 .= "Cellphone :". $_REQUEST['mobileno']."<br />"; $message1 .= "Telephone :". $_REQUEST['landno']."<br />"; $message1 .= "Fax :". $_REQUEST['fax']."<br />"; $message1 .= "Company :". $_REQUEST['company']."<br />"; $message1 .= "Email :". $_REQUEST['email']."<br />"; $message1 .= "Country :". $_REQUEST['country']."<br />"; $message1 .= "Enquity :". $_REQUEST['enquiry']."<br />"; $message1 .= "Date&Time :". $date."<br />"; For this code if try to print/echo it it is working fine it is displaying line by line, but using this variable ($message1) in the mail these <br /> are also visible. Can any one guide me to resolve(to remove these tags from the message part) this issue. Thanks in Advance. :confused: Hi. I want a simple textbox, that when submited, will replace very every new line, with the <br> tag. What will happen, when it submits, it will take the contents of a textbox, add the <br> tag where a new line is suposed to be, and save the string to a MySQL Database. I think this is the easiest way of allowing a user to edit what appears on a website when logged in, but if there is a easier way, then please tell me. What I am trying to do, is a login page, and once logged in, you enter new text into the textbox, click submit, and on the website homepage, the main text will change to what was submitted. But if there is a new line, I think the only way in HTML to make one is to put a <br> tag, so I want the PHP to but that tag wherever there is a new line. Sorry if I am confusing, I am not that advanced at PHP, but I would be very happy if you could supply me with the correct code. Time is running out... If you do not understand me, please tell me -- PHPLeader (not) i have to read a single line from a csv, its a really big file and i only need one column.
i need the response to be a string ,i made a search and found the following code but i dont have any idea how to get a single line from a single string per run .
<?php $row = 1; //open the file if (($handle = fopen("file.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { $num = count($data); echo "<p> $num fields in line $row: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br />\n"; } } fclose($handle); } ?> Edited by bores_escalovsk, 16 May 2014 - 06:38 PM. I have a script that reads a .gz file into an array and prints the name of each record but will not work on larger files. Is there a way to read 1 line at a time? Here is the code I have so far. Code: [Select] <?php if ($handle = opendir('.')) { print "<ol>"; while (false !== ($file = readdir($handle))) { if($file != '..' && $file!="." && $file!="start_update.php" && $file!="sharons_dbinfo.inc.php" && $file!="root.php" && $file!="read_directory.php" && $file!="read_dir.php" && $file!="new_category.php" && $file!="index.php" && $file!="file_count.php" && $file!="dir_loop2.php" && $file!="dir_loop1.php" && $file!=".htaccess" && $file!="Answer.txt" && $file!="Crucial_Technology-Crucial_US_Product_Catalog_Data_Feed.txt"){ $filename = $file; $go = filesize($filename); if($go >= 1){ $filename2 = explode("-", $filename); $filename2 = $filename2[0]; echo str_replace("_"," ",$filename2) . ' | Filesize is: ' . filesize($filename) . ' bytes<br>'; $gz = gzopen($filename, 'r'); $lines = gzfile($filename,10000); foreach ($lines as $line) { $line2 = explode(",", $line); $line2 = str_replace("," , "-" , $line2); echo "<li>".str_replace("," , "-" , $line2[4])."</li><br>"; } } } } closedir($handle); } ?> </ol> How to get this echo line to display as one line? No matter what I have done it displays as two lines. I even tried <nobr></nobr> Teachers Name: John Jones $userid = mysql_real_escape_string($_GET['user_id']); $sql = "select * from users where `id`='$userid' "; $rs = mysql_query($sql); while($row = mysql_fetch_array($rs)) { echo "<h3>Teachers Name: </h3>" . $row["first_name"] . " " . $row["last_name"] ; } Thanks for your help. I'm so sorry to ask such a "newbee question," but believe me I have been on Google for the better part of the week trying to find an answer.
I'll start with the brief question.
Then I'll give an example to show what I mean.
Then, I'll give the BESTEST "pseudo-code" I could come up with (to PROVE that I've really given it my best).
Question:
How do I make PHP loop through a big file, make the changes line by line, and to save the resultant file.
Example: I have a 100mb text file ("animals.txt") with 500,000 lines. If any lines have the word "cat" in it, I want to add "Be careful with cats!" to the end of the line:
From this:
A fish and his tank.
A cat and his toy.
A bird and her cage.
A frog and his lilly.
A cat and her friend.
To this:
A fish and his tank.
A cat and his toy. Be careful with cats!
A bird and her cage.
A frog and his lilly.
A cat and her friend. Be careful with cats!
The best "pseudo-code" I can come up with is:
<?php
$data = file_get_contents("animals.txt");
$lines = explode(PHP_EOL,$data); I want my application will send a email after 10 minutes of sending another email. In my application A user completes registration with payment Application sends the user a payment confirmation emailNow I want to send another email 10 minutes After payment confirmation email with welcome tipsBelow is the function where for user setup .
public function finishUserSetup($Sub){ if($Sub == 0){ $subscription = SubscriptionPlans::where('identifier', '=', "Monthly")->first(); $expiry = date('Y-m-d', strtotime('+' . $subscription->months . ' months')); $sub_period = "monthly"; } else{ $subscription = SubscriptionPlans::where('identifier', '=', "Annually")->first(); $expiry = date('Y-m-d', strtotime('+' . $subscription->months . ' months')); $sub_period = "annually"; } $this->expiry_date = $expiry; $this->user_type = "SUB"; $this->subscription_period = $sub_period; $this->update(); $replaceArray = array( 'fullname' => $this->forename . " " . $this->surname, 'subscriptionName' => $subscription->name, ); EmailTemplate::findAndSendTemplate("paymentconfirm", $this->email, $this->forename . " " . $this->surname, $replaceArray); } In the above function the last line of code is the one which sends a payment confirmation email to the user which is EmailTemplate::findAndSendTemplate("paymentconfirm", $this->email, $this->forename . " " . $this->surname, $replaceArray); I want to execute the following line of code 10 minutes after the above one
EmailTemplate::findAndSendTemplate("WelcomeTips", $this->email, $this->forename . " " . $this->surname, $replaceArray);
How to do that. that is running the last line of code 10 minutes after gday all! just starting to learn php but having a liitle problem with \n forcing a line break. in my situation it simply doesnt. looking at this what have i done wrong? Code: [Select] echo "<div class=\"imgcontainer\"><a href='$row[filename]' rel='shadowbox[thingo]'><img class= 'thumbnail' img src='$row[filename]'/></a><div class=\"thetext\">Artwork: $row[name]\nArtist:$row[artist]</div></div> "; Thanks I tried to do this: explode(" ",$cp['size'])[0] and it isn't working obviously. The reason I want it in one line is its in the middle of a big string and I'd like to keep all the code in one area. Is their a right way to do that other than setting it to a variable first? Hello, When I try to PHP my files I get this error: Cannot use object of type Project as array, in "filepath.php" line 112. Here are the first 2 texts (112,113): $this["Started CPSM, version 0.04, Login Server communication mode: " . LOGIN_MODE . "\n"]; register_shutdown_function(array($this, "shutdownHandler")); Please help, Thanks. hello, anybody able to take a quick look and see why i have an error on both line 16 and 52? Code: [Select] <?php include 'config.php'; include 'style.php'; include 'auth5.php'; $randeid=rand(121047, 997893); if(isset($_GET["delete"])) { $did=$_GET["delete"]; $query11= mysql_query("delete FROM tools where id =$did")or die(mysql_error()); } $groups = mysql_query("SELECT * FROM tools ORDER BY group"); $groups1=""; while($row1 = mysql_fetch_array($groups)) { $groupnames=$row1['group']; $groups1.="<OPTION VALUE=\"$groupnames\">".$groupnames.'</option>'; } ?> <form method="POST"> <p align="center">Search For: <select size="1" name="tool"><?php echo "$groups1"; ?></select> <input type="submit" value="Search" name="search"></p> </form> <?php if(isset($_POST['search'])) { $tool=$_POST['tool']; echo "<table border='1' style='border-collapse: collapse' bordercolorlight='#000000' bordercolordark='#000000' width='98%' align='center'>"; echo "<tr><td width='100%' colspan='4' align='center'><b>Tool List</b></td></tr>"; echo "<tr> <th align='center'>Tool</th> <th align='center'>Barcode</th> <th></th> <th></th> </tr>"; $result = mysql_query("SELECT * FROM tools WHERE group LIKE '%$tool%' ORDER BY tool"); while($row = mysql_fetch_array($result)) { $id=$row['id']; $tool=$row['tool']; $barcode=$row['barcode']; $location=$row['location']; echo "<tr>"; echo "<td align='center'>" . $tool . "</td>"; echo "<td align='center'><img src='barcode.php?format=jpeg&quality=100&width=150&height=75&barcode=" . $barcode . "'></td>"; echo "<td align='center'>Print</td>"; echo "<td align='center'><a href='searchtool.php?delete=" . $id . "'>Delete</a></td>"; echo "</tr>"; } echo "</table>"; } include 'close.php'; ?> I'm having trouble trying to figure out what's causing the unexpected $end error message on line 119...here's the code I have so far: Code: [Select] <!--"StAuth10065: I certify that this material is my original work. No other person's work has been used without due acknowledgement. I have not made my work available to anyone else."--> <? if ($_SERVER['REQUEST_METHOD'] == 'GET' and elseof($_GET) == 0){ $_GET['rows'] = 7; ?> <html> <head> <style> body {background-color:salmon} table { border: 1px solid black; margin-right: auto; margin-left: auto;} table tr.odd, span.odd {background-color:#99CC99} table tr.even, span.even {background-color:#CCFFCC} table td {padding:5; } table td.five {background-color:#990000; color:#FFFFFF } div#form { margin-right: auto; margin-left: auto; width: 300px; text-align:center; background-color: #CCCCCC;} div#container {border: 5px ridge #990000; margin: auto auto; width: 600px; background-color:white;text-align: center} h1 {color: #CCCCCC;} a {color:#006} a:hover {text-decoration:none} </style> </head> <body> <?= '<pre>'.print_r($_POST,true).'</pre>' ?> <div id="container"> <h1>Modified Table Generator</h1> <p ><a href="<?= $_SERVER['PHP_SELF'] ?>">Generate Table using default values.</a></p> <p ><a href="<?= $_SERVER['PHP_SELF'] ?>?rows=<?= $_POST['rows'] ?>cols=10&highlight=5"> Generate Table with GET: table.php?rows=<?= $_POST['rows'] ?>&cols=10&highlight=5 </a></p> <div style=";"> <div id="form"> <form name="form1" method="post" action="table.php "> rows <select name="rows"> <option value="5" >5</option> <option value="6" >6</option> <option value="7" <? if ($_POST['rows'] == 7) echo 'selected' ?> 7 </option> <option value="8" >8</option> <option value="9" <?= ($_POST['rows'] == 9)?'selected':'notselected' ?> 9</option> <option value="10" selected>10</option> </select> cols <select name="cols"> <option value="5" >5</option> <option value="6" >6</option> <option value="7" >7</option> <option value="8" >8</option> <option value="9" >9</option> <option value="10" selected>10</option> </select> highlight <select name="highlight"> <option value="5" selected >5</option> <option value="6" >6</option> <option value="7" >7</option> <option value="8" >8</option> <option value="9" >9</option> <option value="10" >10</option> </select> <br><input type="submit" name="Submit" value="Generate Table with Post using these values"> </form> </div> </div> <body> <?php $randomnumber = rand(0,100); if ($randomnumber % 2 == 0) { $rowclass = "class=even"; $alternatingrowclass = "class=odd"; echo "<center>First number is an <span $rowclass> even</span> number</center>"; } else { $rowclass = "class=odd"; $alternatingrowclass = "class=even"; echo "<center>First number is an <span $rowclass> odd</span> number</center>"; } echo "<table>"; for ($row = 1; $row <= 10; $row ++) { if ($row %2 == 1) echo "<tr $rowclass>\n"; else echo "<tr $alternatingrowclass>\n"; for ($col = 1; $col <= 10; $col ++) { $columnclass = ($col == 5 || $col == 10) ? "class=five" : ""; echo "<td $columnclass>$randomnumber</td>\n"; $randomnumber++; } } echo "</tr>\n"; echo "</table>\n"; ?> </p> </body> </html> It seems to happen on the last line and I'm not sure why. |