PHP - Efficient Way To Add / Remove New Textarea Data
Hello everyone! I've been on a problem a few hours now and I've managed to finally find the solution however I feel it's very inefficient and am looking for a way to do this in a better way. I have a textarea where each line is inserted into MySQL database table "lines" and I have the columns "line_number" and "row". The textarea initial value on page load is simply a list of all lines ordered by line_number in ASC order. If I modify/add/remove entries from the textarea it will remove data changed and add new data accordingly. But I am making a lot of queries to do this and I'm not sure if there is a more efficient way than querying each line in the database to find the new value/modified value. Here's my php script, hopefully this makes sense:
if (isset($_POST['lines'])) { //get lines posted from textarea $lines_posted = $_POST['lines']; //trim all white spaces and remove empty lines as they are not valid for mysql insert $lines = trim($lines_posted); $lines = explode("\n", str_replace("\r", "", trim($lines_posted))); $lines = array_map('trim', $lines_posted); $lines = array_filter($lines_posted); $line_count = count($lines); //output how many valid lines were posted echo "Posted Lines: $line_count<br>"; //loop through all lines posted, query all rows in database and insert if lines row value does not exist for ($i = 0; $i < $line_count; $i++) { if (isset($lines[$i])) { $find_line_in_db = $db->query("SELECT row FROM lines WHERE row=?", $lines[$i]); if ($find_line_in_db->numRows() == 0) { $db->query("INSERT INTO lines (line_number, row) VALUES (?,?)", $i, $lines[$i]); echo 'Added the line: ', htmlspecialchars($lines[$i]), '<br>'; } } } //query all rows in the database and check if posted lines array value is in the [row] column, delete rows changed/not found accordingly $rows = ""; $fetch_all_lines = $db->query("SELECT row FROM lines"); while ($all_lines = $fetch_all_lines->fetchRow()) { if (!in_array($all_lines['row'], $lines)) { $rows = $all_lines['row']; $db->query("DELETE FROM lines WHERE row=?", $all_lines['row']); echo 'Deleted the line: ', htmlspecialchars($lines[$i]), '<br>'; } } }
So to visualize what I'm doing imagine two arrays:
$lines = ["line1", "line2", "line3changed"] //textarea lines posted $db_lines = ["line1", "line2", "line3"] //$db_lines = the current rows in lines db table // line_number | row // 0 | line1 // 1 | line2 // 2 | line3 //outputs //Added the line: line3changed //Deleted the line: line3
So basically what I'm asking is, am I doing this the right way? I would have over 10,000 lines that would be altered every hour in this table and am unsure if I'm doing it the correct way Similar TutorialsWhat's wrong with this code? Code: [Select] <textarea name="description" cols="60" rows="10"><?= $description ?></textarea> The textarea box returns null. I have a form where people have to fill in some fields and send an email. When there is an error the user has to go back to the form with: Code: [Select] if (!isset($_POST['checkbox'])) { $msgToUser = '<br /><br /><font color="#FF0000">You did not add any recipients!<br><a href="javascript: history.go(-1)">Go Back</a></font>'; include_once 'msgToUser.php'; exit(); } I want to save the data that has been filled in the textarea so he doesn't have to type eveything again. I tried several options but the textarea keeps getting blank. Code: [Select] <?php $message = isset($_POST['message']) ? $_POST['message'] : ''; $fhtml = "<p>Welcome <b>'$logOptions_username'</b> write your email here. <a href=\"#\" onclick=\"return false\" onmousedown=\"javascript:toggleViewFlags('country_flags');\">Add Recipients</a> <br> </p><input type=hidden name=post value=yes><p> Subject:<br> <input type=text name=name size=100> </p> <p> Message:<br> <textarea name=message rows=10 cols=75>$message</textarea> </p> <p> <input type=submit name=submit value=\"Send\"> $sendMsg </p> "; echo $fhtml; ?> This code is apparently not working. Marco Hey folks, I thought this would be simple but obviously not. I can get the data to display in the textarea from the text file. That's not an issue. The issue is, updating the text from the textarea and saving it in the file, while keeping the text in the textarea. Basically, I want to create a personal notepad inside the site I am making. Here is the code I am using: <form action="?admintext.txt" method=post> <textarea name="file_content" class="textarea1"><? include "admintext.txt"; ?></textarea><br/> <input type=submit name=submit value=Update> </form> Can anyone help with this? I tried loads of tips I found from Google but none worked. This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=306916.0 I like to use $_REQUEST to get something from either $_POST or $_GET. Annoying though, it also includes values from cookie, like the PHP session id, FCK editor cookies and the google tracking code. Is there anyway to remove cookie values from request, besides looping through cookie and unsetting the values I don't want? I'm having a problem with some php code that allows you to edit a text file. No matter what file it loads, it always adds four horizontal tabs and two spaces to the end of the text. I've attached the code to this post. If anyone can help me with this, it would be greatly appreciated. Cindy Hello, I am puzzled as to how to get this code actually working, I am using some example code, I want the code to remove the data of the logged in users, at the moment it will remove all users registered in the mysql db. <?php # Access session. session_start() ; if ( !isset( $_SESSION[ 'user_id' ] ) ) { require ( 'login_tools.php' ) ; load() ; } # Connect to the database. require ('connect_db.php'); // Attempt delete query execution $sql = "DELETE FROM users WHERE user_id=user_id"; if(mysqli_query($dbc, $sql, $q)){ echo "Records were deleted successfully."; } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($dbc); } # Close database connection. mysqli_close( $dbc ) ; ?> $_session id knows that the user is logged into the control page, but for the code to remove the particular user logged in from the db, what exactly does this need? Thank you. I have a query that gets staff on a particular day then performs a while loop selecting each member that works on that day and the times they work between. I have a for loop in that while loop that lists apointment times for each staff member every 15mins between the times they work, this works fine. I then have in the for loop a while loop that checks for existing appontments in the appointment table and changes the appointment slot for times that are booked to booked. I have found though that the second while loops causes doubling of results when an appointment is found, so I need to work out how to restructure this code so that i dont get the doubling effect of result. you can see the result of the script here http://justrelax.net.au/datetest.php and the code that causes the problem is // convert to US format $input="$month/$day/$year"; // readable date $readDATE="$day/$month/$year"; // convert for mysql date $sqlDATE="$year-$month-$day"; // get day of the week $weekday=date(l, strtotime($input)); echo $weekday."<br/>"; // get working staff from staff table $staffSQL=mysql_query("SELECT * FROM staff WHERE ".$weekday." != 'off' AND onLEAVE='no' AND ACTIVE='yes' ORDER BY staffID ASC"); // return results putenv("TZ=Australia/Adelaide"); while ($staff=mysql_fetch_array($staffSQL)) { $name=$staff['staffNAME']; $avail=$staff[$weekday]; $staffID=$staff['staffID']; list($first, $last)=explode(" ", $name); list($in, $out)=explode("-", $avail); $firstTIME="$sqlDATE $in:00"; $lastTIME="$sqlDATE $out:00"; echo "$first is available between $avail on $weekday<br/>"; $in2=strtotime($firstTIME); $out2=strtotime($lastTIME); $stop=$out2-900; echo $in2." - time start - $firstTIME<br/>"; echo $out2." - time finish - $lastTIME<br/>"; for ($inc=$in2;$inc<=$stop;$inc+=900) { $existSQL=mysql_query("SELECT * FROM appointment WHERE date='$sqlDATE' AND staffID='$staffID'"); if (mysql_num_rows($existSQL)>=1) { while ($appointV=mysql_fetch_array($existSQL)) { $resSTART=$appointV['dateTIME']; $length=$appointV['totalTIME']; $resEND=$resSTART+($length*60); if ($inc>=$resSTART && $inc<=$resEND) { echo "Appointment time is ".date("g.i a", $inc)." <font color='red'><< $first BOOKED</font><br/>"; } else if ($inc<$resSTART || $inc>$resEND) { echo "Appointment time is ".date("g.i a", $inc)." <font color='green'><< $first AVAILABLE</font><br/>"; } } } if (mysql_num_rows($existSQL)==0) { echo "Appointment time is ".date("g.i a", $inc)." <font color='green'><< $first AVAILABLE</font><br/>"; } } } could really use some help on this I have been trying different things for a few days now. Dear All Members here is my table data.. (4 Columns/1row in mysql table)
id order_no order_date miles How to split(miles) single column into (state, miles) two columns and output like following 5 columns /4rows in mysql using php code.
(5 Columns in mysql table) id order_no order_date state miles 310 001 02-15-2020 MI 108.53 310 001 02-15-2020 Oh 194.57 310 001 02-15-2020 PA 182.22
310 001 02-15-2020 WA 238.57 ------------------my php code -----------
<?php
if(isset($_POST["add"]))
$miles = explode("\r\n", $_POST["miles"]);
$query = $dbh->prepare($sql);
$lastInsertId = $dbh->lastInsertId(); if($query->execute()) {
$sql = "update tis_invoice set flag='1' where order_no=:order_no"; $query->execute();
} ----------------- my form code ------------------
<?php -- Can any one help how to correct my code..present nothing inserted on table
Thank You Edited February 8, 2020 by karthicbabuI have a form that generates html code, and displays it in a textarea with submit button. I want to submit button to take the data entered in that textarea1 on page 1, and upload to textarea2 on page 2 How can I do this? I have no idea where to start. Code: [Select] <?php $IPaddress = $_SERVER['REMOTE_ADDR']; if(stristr($IPaddress, "123.456.58.451") || stristr($IPaddress, "123.126.456.10") || stristr($IPaddress, "123.126.456.10")) { echo "<center><b><i>CWB permits you to views this page...</i></b></center></br>"; echo '<center><b><font size="5">'.$IPaddress.'</font></b></center>'; } else { echo "<center><b>CWB DOES NOT PERMIT YOU TO VIEW THIS PAGE</b></center>"; } exit; ?> how do I make it to where I dont have to keep adding on to Code: [Select] if(stristr($IPaddress, "123.456.58.451") || stristr($IPaddress, "123.126.456.10") || stristr($IPaddress, "123.126.456.10")) I have some code which i think is really inefficient especially as there will be more more conditions to be met. I was thinking about using s switch but don't know if this is possible or if it's best leaving as it is. Any ideas? if($parts[($i-1)]=="forum") { //do some code } else if($parts[($i-2)]=="forum") { //do code } else if (($parts[($i-1)]=="list-messages") && (isset($parts[($i+1)]))) { //do code } else { // do some code } this xml_parse_into_struct($iP=xml_parser_create(), curl_exec($ch), $bR, $bJ);xml_parser_free($iP); echo "::: ".strip_tags(str_replace("<br>","\n",$bR[$bJ['MESSAGE'][0]]['value']))."\n"; or... $xml = simplexml_load_string(curl_exec($ch)); foreach($xml->xml as $message){ echo strip_tags($message->message)."\n";} Just want to know which of these two would execute faster and if there was a better way that would be faster than both of these options? Thanks Hello, I'm new to PHP and I have come up with the following code for my navigation but I am sure there has to be an easier and more efficient way to do this. Someone please start me on the right path. Thanks Code: [Select] <?php //Get selected page/sub page if (isset($_GET['page'])) { $sel_page = $_GET['page']; $sel_sub_page = ''; } elseif (isset($_GET['sub_page'])) { $sel_page = ''; $sel_sub_page = $_GET['sub_page']; } else { $sel_page = ''; $sel_sub_page = ''; } ?> Code: [Select] <!--Begin Navigation--> <ul> <?php //run the loop to get the page titles $query = "SELECT * FROM pages ORDER BY position ASC"; $page_set = mysql_query($query); confirm_query($page_set); while($page = mysql_fetch_array($page_set)){ echo '<li><a href="content.php?page=' . urlencode($page['id']) . '">' . $page['page_name'] . '</a></li>'; //run sub page query to see if the ul tag is needed $query = "SELECT * FROM sub_pages WHERE page_id = {$page['id']} ORDER BY position ASC"; $sub_page_set = mysql_query($query); confirm_query($sub_page_set); $sub_page = mysql_fetch_array($sub_page_set); if ($sub_page !=''){ echo '<ul>'; } //run the sub page loop again to display the sub page title $query = "SELECT * FROM sub_pages WHERE page_id = {$page['id']} ORDER BY position ASC"; $sub_page_set = mysql_query($query); confirm_query($sub_page_set); while($sub_page = mysql_fetch_array($sub_page_set)) { echo '<li><a href="content.php?sub_page=' . urlencode($sub_page['id']) . '">' . $sub_page['page_name'] . '</a></li>'; } //run the sub page loop for the last time to see if the end ul tag is needed $query = "SELECT * FROM sub_pages WHERE page_id = {$page['id']} ORDER BY position ASC"; $sub_page_set = mysql_query($query); confirm_query($sub_page_set); $sub_page = mysql_fetch_array($sub_page_set); if ($sub_page !='') { echo '</ul>'; } } ?> </ul> <!--End Navigation--> Hi guys, I'm developing a website which allows people to connect and follow each other's activity (like Twitter, for example). To simplify everything, let's say I only have 2 tables: 1. Followers id | follower_id | id_to_follow ------------------------------------ 2. Activity id | member_id | message | time ----------------------------------------- Let's say John is following Jane and Bob. I want to create a "news" page and display the last 20 messages from Bob and Jane, chronologically. For small numbers, I'd do something like this: Select everything from the Activity table, check for every entry if the member is a friend of John's (in the Followers table) and, if so, display the message, ORDER BY `id` DESC. But, this is very inefficient, I guess, for larger numbers (I can't even think about how many queries would take to do this on a site like Twitter...). Any ideas of how to do the same thing more efficiently? Thank you. Hi all, I've been trying to improve the speed of my file download script and was wondering if anyone could advise me which of the following is more efficient (Don't worry its not the whole script, just one segment), in terms of speed and server load? The way I have the segment currently: //if file exists need to check authorision levels //set access to no $access = NULL; //retrieve current user levels $cpm = $_SESSION['MM_CPMGroup']; $cpmh = $_SESSION['MM_CPMHGroup']; $cm = $_SESSION['MM_CMGroup']; $cj200 = $_SESSION['MM_CJ200Group']; $cj = $_SESSION['MM_CJGroup']; //set file category type & set access if allowed if ($category == 'cpm') { if ($cpm == '1') { $access = 1; if ($subcategory == 'techdata') { $path = "files/techdata/cpm/"; } elseif ($subcategory == 'msds') { $path = "files/techdata/cpm/msds/"; } elseif ($subcategory == 'symbols') { $path = "files/symbols/cpm/"; } else { $path = "files/cpm/"; } } } elseif ($category == 'cpmh') { if ($cpmh == '1') { $access = 1; if ($subcategory == 'techdata') { $path = "files/techdata/cpmh/"; } elseif ($subcategory == 'msds') { $path = "files/techdata/cpmh/msds/"; } elseif ($subcategory == 'symbols') { $path = "files/symbols/cpmh/"; } else { $path = "files/cpmh/"; } } } elseif ($category == 'cm') { if ($cm == '1') { $access = 1; if ($subcategory == 'techdata') { $path = "files/techdata/cm/"; } elseif ($subcategory == 'msds') { $path = "files/techdata/cm/msds/"; } elseif ($subcategory == 'symbols') { $path = "files/symbols/cm/"; } else { $path = "files/cm/"; } } } elseif ($category == 'cj200') { if ($cj200 == '1') { $access = 1; if ($subcategory == 'techdata') { $path = "files/techdata/cj200/"; } elseif ($subcategory == 'msds') { $path = "files/techdata/cj200/msds/"; } elseif ($subcategory == 'symbols') { $path = "files/symbols/cj200/"; } else { $path = "files/cj200/"; } } } elseif ($category == 'cj') { if ($cj == '1') { $access = 1; if ($subcategory == 'techdata') { $path = "files/techdata/cj/"; } elseif ($subcategory == 'msds') { $path = "files/techdata/cj/msds/"; } elseif ($subcategory == 'symbols') { $path = "files/symbols/cj/"; } else { $path = "files/cj/"; } } } if ($access < 1) { // if user access not granted to file category return message if($logging > 0){ $status = "Wrong Permissions"; include('logit.php'); } if (! $_SESSION['PrevUrl']) { //header("Location: ". $loginpage ); exit; } $redirect = $_SESSION['PrevUrl']; header("Location: ". $redirect ); exit; } // if file exists and user access granted continue Obviously the above is a lot of lines of code... So I have rewritten the above to look like: //if file exists need to check authorision levels & retrieve current user levels if ($category == 'cpm' && $_SESSION['MM_CPMGroup'] == '1') { $access = 1; } elseif ($category == 'cpmh' && $cpmh = $_SESSION['MM_CPMHGroup'] == '1') { $access = 1; } elseif ($category == 'cm' && $cm = $_SESSION['MM_CMGroup'] == '1') { $access = 1; } elseif ($category == 'cj200' && $_SESSION['MM_CJ200Group'] == '1') { $access = 1; } elseif ($category == 'cj' && $_SESSION['MM_CJGroup'] == '1') { $access = 1; } else { $access = NULL; } if ($access == NULL) { // if user access not granted to file category return message $status = "Unauthorised"; include('logit.php'); header("Location: ".$_SESSION['PrevUrl']); exit; } // if file exists and user access granted continue switch($subcategory) { case "techdata":$path="files/techdata/".$category."/".$filename; break; case "msds": $path="files/techdata/".$category."/msds/".$filename; break; case "symbols": $path="files/symbols/".$category."/".$filename; break; default: $path="files/".$category."/".$filename; } The second version is a lot shorter, but is it better? And could I shorten the if statement further so its more like: //if file exists need to check authorision levels & retrieve current user levels if (($category == 'cpm' && $_SESSION['MM_CPMGroup'] == '1') || ($category == 'cpmh' && $cpmh = $_SESSION['MM_CPMHGroup'] == '1') || ($category == 'cm' && $cm = $_SESSION['MM_CMGroup'] == '1') || ($category == 'cj200' && $_SESSION['MM_CJ200Group'] == '1') || ($category == 'cj' && $_SESSION['MM_CJGroup'] == '1') { $access = 1; } else { $access = NULL; } if ($access == NULL) { // if user access not granted to file category return message $status = "Unauthorised"; include('logit.php'); header("Location: ".$_SESSION['PrevUrl']); exit; } // if file exists and user access granted continue switch($subcategory) { case "techdata":$path="files/techdata/".$category."/".$filename; break; case "msds": $path="files/techdata/".$category."/msds/".$filename; break; case "symbols": $path="files/symbols/".$category."/".$filename; break; default: $path="files/".$category."/".$filename; } Any advice would be appreciated! Thanks!! Need some feedback on this loop Tables: Table A Table B Loop Select all from A based on criteria a. Insert into table B using row data from table A b. Update record in table A to say that it has gone through loop to prevent future loop Thats three MySQL queries running over and over at the same time, how bad is that for performance, is there another way? Maybe instead of running b each time build an array with the record ids from Table A and after the loop runs to insert into Table B run another query with the IN command to loop through all of the IDs in the array and update? |