Jump to content

Psycho

Moderators
  • Posts

    12,146
  • Joined

  • Last visited

  • Days Won

    127

Everything posted by Psycho

  1. You're saying this produced no results? $globFiles = glob('*'); echo "<pre>" . print_r($globFiles, 1) . "</pre>"; I find that hard to believe. If you were only trying the code from the manual then, yes, I could see that not producing any results because you many not have ant "txt" files in the directory being scanned. Yes it does. And '*' is a reference because the path can be relative from the current working directory. Using '*' should return all the files in the current working directory (i.e. the directory in which the script is executed from). That is why I find it hard to believe that the test code I asked you to try earlier is producing no results. Just to be sure I did not make a mistake, I just ran that code again and it returned all the contents of the directory where I ran the script as expected. Is it returning an empty array or an error? Try this test script and paste the results here: $pattern = '*'; $globFiles = glob($pattern); if($globFiles===false) { echo "glob('{$pattern}') returned an error"; } else { echo "Results of glob('{$pattern}'): <pre>" . print_r($globFiles, 1) . "</pre>"; }
  2. No you don't want to take the time to actually learn anything and just want us to provide solutions. If you had simply done a quick test using glob() I'm confident you would have already had a solution and moved on. Instead, we've wasted quite bit of time in this thread and you are probably further from a solution because you are getting lost in assumptions and trial & error attempts. That must be really frustrating for you. I've already resigned myself that I am not going to give you the solution. You have to earn it. You were right that the part you need to change was within those four lines you posted earlier. But, you can't just replace using the glob() function and expected it to work. If you had just a basic understanding of what those four lines do and what glob() does it is a very simple solution. This will be my final attempt to help you unless you can demonstrate that you are at least putting in some (worthwhile) effort. Here is what you have $directoryList = opendir($directory); while($file = readdir($directoryList)) { if ($file != '.' && $file != '..') { $path = $directory . '/' . $file; If you were to put comments in your code you may have figured it out already. Since you didn't let's review what that code does: 1. The first line creates a "handle" to the directory (think of it like making a connection to a database). So, the variable $directoryList is misnamed because it isn't a list. 2. Here you have a while list that will continue as long as a new record can be assigned to $file from the readdir() function. That function returns each record name found in the file handler created above 3. The if() statement ensures that the default filesystem objects of the current and parent directories are not included in the processing 4. This defines (I assume) the fill path to the file. So, what does glob() do? It returns an array of files based on an expression. So, obviously your looping logic needs to change since you wouldn't use a while() loop to iterate over an array. Typically you want a foreach() loop, correct? A foreach() loop will return the value of each element in the array. But, how do you get the correct values in the array? Well, you could just throw random data into the glob() function and scratch your head when things don't work. Or, you could take the two line test script I provided and modify the pattern to verify you are getting the right values before you try using it in a foreach() loop of your current logic. FYI: glob() does not return '.' and '..', so the if() condition will be unnecessary. Good luck
  3. So, you didn't follow my advise to start with a simple test script to see what glob() is returning and then go from there? Instead, you're back still trying to shoehorn it into your current code without understanding what it is doing. It seems you don't even understand what your current code is doing. You need to stop the trial and error approach to coding and actually learn what the functions do. You're being lazy in a way that is causing you more work.
  4. Yeah, that's a mystery isn't it. It's not like it is explained in the manual on the first sentence of the description for the readdir() function, right? Nope, you have to read all the way to the second sentence . You probably created those first three files such that they happened to be created in alphabetical order. The fact that it is right there plain as day in the manual for that function would lead someone to believe you never took the time to do even a cursory look at the manual. I had no idea of how readdir() determined the order in which it returned files, and it took me all of 5 seconds to find out without any special skills/knowledge required to do so. It leaves one wondering what level of effort was put into understanding the glob() function before just randomly trying things without even understanding what the problem is "I have tried renaming the $path, and nesting the glob() in every area of my script." Did you have a reason to believe the path was wrong or that glob() should go somewhere else in the script? When using a function for the first time, if I have any problems I will almost always create a test script. I will start with an example from the manual or a tutorial, verify it works and then figure out how it needs to be modified for my use. I have a very good idea of what your problem is, but I'm reticent to give you the solution because you are wasting our time and yours with how you are currently approaching the problem. And, I'm certain you will be back time and again with 'simple' problems that end up taking significant time to resolve. You need to learn how to problem solve. Start with this code and see what the results are. Then start making (small) changes until it is returning the results you want. E.g. I'd start by changing it to get to the intended directory. Then I would change it to only return the files I was interested in. If you want further help from me, please provide details on what you tried up till you got stuck. $globFiles = glob('*'); echo "<pre>" . print_r($globFiles, 1) . "</pre>";
  5. Why would you think that? As previously stated in this thread: The manually explicitly states this as well. It doesn't state a path/directory name - it states a pattern. If you look at any of the examples either in the manual or the ones linked to by others, you would see that it takes more than just the path to the directory. Heck, @cyberRobot asked you to provide the value of the variable $directory so we could help, but you refused and are simply wanting us to do it for you. readdir() is designed to return all the contents of a directory - so it only needs a pointer to the directory. glob() is designed to return a filtered list of a directory's contents and therefore needs something more than just the path to the directory. Regular expressions (i.e. the pattern) is one of the more difficult areas of programming (IMO), so it would be understandable if you were to ask about how to write the expression. But, instead you just put what you "think" it should be and don't respond to direct questions. I think you are taking the responses as people not being helpful. What I see are people that are trying to get you to think deliberately and analytically in order to find answers for yourself. Or to at least get a sense of the problem so you can ask the right questions. I for one am more likely to help someone who can demonstrate through their questions/responses that they've done some research into their problem rather than just throwing code at the wall to see what will stick. Having said all that (which will probably be forgotten by the next post), I will throw you a bone. The '*' character is a 'character class' that matches anything. The link @cyberRobot posted had this example: $files = glob("/path/to/directory/*.txt"); Which will " . . . find all the files in the directory /path/to/directory with a .txt file extension" because the '*' would match any number of characters after the path name and before the '.txt'. So, what would happen if you removed the '.txt' from that pattern? It would match anything that comes after the directory path (i.e. any files/folders). However, since you are looking for images, why not use the later example on that page which was specifically built to only return images?
  6. Even session data can be "hacked". Everything can be "hacked" it is just a matter of how difficult it is. The amount of effort and safeguards you put in place should be directly proportional to the "value" or "risk" associated with the data being secured. Unless you are dealing with financial or sensitive PII data, I think using a session value as @mac_gyver stated is perfectly acceptable. Although you should at least read the manual regarding sessions to take the basic precautions.
  7. None of what you described requires the code to be in the same page or not. For small projects, it's fine. But, it is significantly easier to manage code when you have separate files based on separate purposes.
  8. Put the code in your post as text (using the code tags) not as an image. As to your problem. this is NOT doing what you think it is if($Name_Tag = 15) Read this: Comparison Operators
  9. On your gallery page, you have a process to get an array of images which you should ensure has a numerically based index (0, 1, 2, ...). First, you need to take that logic and put it in a separate file that you will include() in your gallery page. You need to do this because you will need to include the same logic on the "enlarged version" script so you always get the exact same array. Never "copy/paste" such logic between multiple pages - especially when those multiple pages are dependent upon the data being the same. Then, on your gallery page, make each image a link to open the image in the "enlarged version" page. That link would look something like this showfull.php?id=3 Lastly, your enlarged version page could look something like this. <?php //Include script to generate the image array include('getImageArray.php'); //Get the passed image id $imageId = isset($_GET['id']) ? int($_GET['id']) : 0; //Check if the image exists if(!array_key_exists($imageId, $images) { //Error handling when the selected image does not exist $output = "Unable to retireve image"; } else { //Detemine if there will be a "prev" button (assumed array is always zero-based $prevId = $imageId-1; $prevLink = (array_key_exists($prevId, $images) ? "<a href='showfull.php?id={$prevId}'>PREV</a>" : ''; //Detemine if there will be a "next" button $nextId = $imageId+1; $nextLink = (array_key_exists($nextId, $images) ? "<a href='showfull.php?id={$nextId}'>NEXT</a>" : ''; //Create the output $output = "SOME CONTENT TO SHOW FULL-SIZE IMAGE<img src='base_path/{$images[$imageId]}' /><br>"; $output .= "{$prevLink} | {$nextLink}"; }
  10. Have you inspected the HTML output to see if the text is there, but maybe is not within proper HTML tags making it 'hidden'? Your code is hard to follow for a number of reasons. But, my guess, is that there is a problem with the structure of the output. So, a couple of suggestions: 1. When checking for multiple error conditions, do not do this if(NOT error_condition_1) { if(NOT error_condition_2) { //Success handling } else { //Error condition 2 handling } } else { //Error condition 1 handling } Instead, structure it so the error condition handling is adjacent tot he error condition check. Plus, try not to have a lot of nested if/else conditions. It makes the code much more readable. if(error_condition_1) { //Error condition 1 handling } elseif (error_condition_2) { //Error condition 2 handling } else { //Success handling } 2. use prepared queries. NEVER use user submitted data directly in a query 3. You aren't checking to see that the user provided the top_text or that you are even getting the value. I.e. if the field name was different between the form and the processing page it would insert an empty string. I'm assuming the problem is here and the value you think is being passed isn't referenced correctly and not getting set in the DB <?php // Include the database configuration file include 'database/dbConfig.php'; $statusMsg = ''; // File upload path $targetDir = "uploads/"; $fileName = isset($_FILES["file"]["name"]) ? basename($_FILES["file"]["name"]) : false; $top_text = filter_input(INPUT_POST, 'top_text'); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); //Create Prepared statement $stmt = $pdo->prepare("INSERT into images (file_name, top_text, uploaded_on) VALUES (?, ?, NOW())"); // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf'); //Check if there was an upload if($fileName && $fileName!=''){ $statusMsg = 'Please select a file to upload.'; } //Verify top_text is valid elseif (!$top_text || $top_text=='') { $statusMsg = 'Please provide the text.'; } //Verify valid file type elseif(!in_array($fileType, $allowTypes)) { $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.'; } //Attempt to upload file elseif (!move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) { $statusMsg = "Sorry, there was an error uploading your file."; } //Attempt the insert query elseif(!$stmt->execute([$fileName, $top_text]);) { $statusMsg = "The file {$fileName} has been uploaded successfully."; } else { //Insert succeeded $statusMsg = "File upload failed, please try again."; } // Display status message echo $statusMsg; ?> 4. The 2nd block of code is hard to read because of the breaking in and out from PP/HTML repeatedly. Also, there is a TON of style properties in there. You should use a style sheet with classes. The complexity in the structure makes it impossible to see structure errors. After cleaning it up, I see that the closing LI tag for the default slide it outside the else container block for that slider. In other words, that closing LI tag is always outputting to the page - even when the default slider is not used. I don't see that this would cause your issue, but it just shows that such simple problems are hidden in that morass of code. There may be other errors that I can't "see" because of all the style properties, but here is a more readable re-write of that section <!-- Revolution slider --> <section id="slider"> <div class="tp-banner-container "> <div class="tp-banner rev-banner-fullscreen"> <ul> <!-- SLIDES --> <?php // Include the database configuration file include 'database/dbConfig.php'; // Get images from the database $query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC"); if($query->num_rows = 0) { ?> <!-- DEFAULT SLIDE --> <li data-index="rs-140" data-transition="slideup" data-slotamount="default" data-easein="default" data-easeout="default" data-masterspeed="default" data-thumb="" data-rotate="0" data-saveperformance="off" data-title="1/2" data-description=""> <!-- MAIN IMAGE --> <img src="images/slide/slide-5-bg.jpg" style='background-color:#f4f4f4' alt="" width="482" height="800" data-bgposition="center center" data-bgfit="cover" data-bgrepeat="no-repeat" class="rev-slidebg" data-no-retina> <!-- LAYERS --> <!-- LAYERS 1.2 --> <div class="tp-caption tp-resizeme" id="slide-1-layer-2" data-x="['left','left','left','left']" data-hoffset="['102','102','67','40']" data-y="['top','top','top','top']" data-voffset="['150','150','60','60']" data-fontsize="['18','18','14','14']" data-width="['345','345','345','259']" data-height="none" data-whitespace="normal" data-transform_idle="o:1;" data-transform_in="y:50%;z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;opacity:0;s:900;e:Power4.easeInOut;" data-transform_out="x:-50%;opacity:0;s:800;e:Power2.easeInOut;s:300;e:Power2.easeInOut;" data-start="500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; min-width: 345px; max-width: 345px; white-space: normal; color: #3e3e3e; font-family: 'Montserrat'; letter-spacing: 7px;"> New Arrival </div> </li> <!-- /END DEFAULT SLIDE --> <?php } else { while($row = $query->fetch_assoc()){ ?> <!-- DYNAMIC SLIDES --> <li data-index="rs-140" data-transition="slideup" data-slotamount="default" data-easein="default" data-easeout="default" data-masterspeed="default" data-thumb="" data-rotate="0" data-saveperformance="off" data-title="1/2" data-description=""> <!-- MAIN IMAGE --> <img src="uploads/<?php echo $row["file_name"]; ?>" alt="" style='background-color:#f4f4f4' alt="" width="482" height="800" data-bgposition="center center" data-bgfit="cover" data-bgrepeat="no-repeat" class="rev-slidebg" data-no-retina> <!-- LAYERS --> <!-- LAYERS 1.2 --> <div class="tp-caption tp-resizeme" id="slide-1-layer-2" data-x="['left','left','left','left']" data-hoffset="['102','102','67','40']" data-y="['top','top','top','top']" data-voffset="['150','150','60','60']" data-fontsize="['18','18','14','14']" data-width="['345','345','345','259']" data-height="none" data-whitespace="normal" data-transform_idle="o:1;" data-transform_in="y:50%;z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;opacity:0;s:900;e:Power4.easeInOut;" data-transform_out="x:-50%;opacity:0;s:800;e:Power2.easeInOut;s:300;e:Power2.easeInOut;" data-start="500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; min-width: 345px; max-width: 345px; white-space: normal; color: #3e3e3e; font-family: 'Montserrat'; letter-spacing: 7px;"> <?php echo $row['top_text']; ?> </div> </li> <!-- /END DYNAMIC SLIDE --> <?php } } ?> </ul> </div> <!-- /tp-banner --> </div> <!-- /tp-banner-container --> </section> <!-- /#Revolution slider -->
  11. To add to @maxxd's response. When a user requests a PHP page from a web server, the web server will first execute any php code in the page. The results after the php code is execute is then sent to the user/browser. If you are having problems in the page rendered in the browser, there is something off in the output (HTML, Javascript, etc.) sent to the browser. It can get confusing when you are using a programming language (PHP) to dynamically create other code (JavaScript) or Markup (HTML).
  12. It's pretty frustrating when someone asks for help and then they change the requirements. It would also be helpful if you provided REAL content instead of something with gibberish. <?php $text = "start 00000000000000000 REMOVE ON FIRST PASS end start 11111111111111111111 XXXXXXX keyword XXXXXXXXXXX end start oidfgoj 11111111111111111111 keyword REMOVE ON 2ND PASS end start abcd keyword efg 2222222222222222222 REMOVE ON 2ND PASS abcd keyword abcd end SOME OTHER TEXT WILL NOT BE REPLACED start 0000000000000000000 REMOVE ON FIRST PASS end start keyword oidfgoj 33333333333333333333333 abcd REMOVE ON 2ND PASS abcd keyword fdsfs keyword pwefkoewfk end"; function replaceTextBlocks($input, $startDelimiter, $endDelimite, $keyword='keyword', $withKeyword=false) { if($keyword!='') { $keyword = "{$keyword}.*?"; } //$pattern = "#^{$startDelimiter}.*?{$keyword}{$endDelimite}#ms"; if(!$withKeyword) { //Remove blocks w/o the keyword $pattern = "#^{$startDelimiter}((?!{$keyword}).)*{$endDelimite}[\n\r]*#ms"; } else { //Remove blocks with the keyword $pattern = "#^{$startDelimiter}.*?{$keyword}.*?{$endDelimite}[\n\r]*#ms"; } //echo $pattern; $newText = preg_replace($pattern, '', $input); return $newText; } echo "Original text: <pre>{$text}</pre><br>\n"; $text = replaceTextBlocks($text, 'start', 'end', 'keyword'); echo "First Pass: <pre>{$text}</pre><br>\n"; $text = replaceTextBlocks($text, 'start', 'end', 'keyword', true); echo "Second Pass: <pre>{$text}</pre><br>\n"; ?>
  13. Pleas explain what you expect that code to do and then describe what it is doing (or not doing) that is contrary to your expectations. Are there errors? FYI: there is nothing in that code that ever calls that function. So, kinda hard to say it isn't working, when it is not used.
  14. Do you understand WHY that last attempt worked and the previous ones failed? If not, you are going to repeat the same errors in the future.
  15. This may work for you. Here is a function that returns the "textblocks" that begin/end with a delimiter string OR (if a keyword is provided, then it only returns "textblocks" that also contain that keyword. As I made the regular expressions programatical, it may be difficult to see how they are constructed. The two formats would look like this: #^smaple.*?smaple#ms and #^smaple.*?keyword.*?smaple#ms <?php $text = "smaple woiefjeowijji oj oiewjfoewijfoiwejfiojewf keyword owiejfioejoij oiewjfioewjf smaple smaple ojioewj fijo oieiojewf keyword owiejfioejoij oiewjfioewjf smaple smaple woiefjeowijji fijo oiewjfoewijfoiwejf owiejfioejoij oiewjfioewjf smaple"; function findTextBlocks($input, $delimiter, $keyword='') { if($keyword!='') { $keyword = "{$keyword}.*?"; } $pattern = "#^{$delimiter}.*?{$keyword}{$delimiter}#ms"; echo $pattern; preg_match_all($pattern, $input, $matches); return $matches; } $textBlocks = findTextBlocks($text, 'smaple'); echo "<pre>".print_r($textBlocks, true)."</pre>"; $textBlocksWithKeyword = findTextBlocks($text, 'smaple', 'keyword'); echo "<pre>".print_r($textBlocksWithKeyword, true)."</pre>"; ?> Output #1 Output #2
  16. I'm not sure I follow what you are exactly trying to find. I see you gave some example input, it would have been helpful to see what you expect to be returned. Specifically, I'm not sure what you mean by "textblock". I *think* you mean where a line starts with 'sample' followed by however many lines until you find a line that ends with 'sample'. However, note that the word "sample" never appears in your text block. There is a word spelled "smaple" - I have no idea what that is. How you word #1 and #2 is confusing as well. Are you saying you want to find the first textblock which starts with "sample" and ends with "sample" and then find the NEXT textblock the same way, but the second one contains the keyword? Or does #2 mean the keyword is supposed to be in the first textblock?
  17. You can turn on error reporting in your script by putting this at the top of the page error_reporting(E_ALL); https://www.php.net/manual/en/function.error-reporting.php
  18. Short fuse? I've taken the time to respond multiple times providing the same information which you ignore because you've got some preconceived notions in your head that you can't get rid of. Think of it this way, someone is taking time out of their day to try and help someone for no reason other than goodwill - there is no compensation for their time. Yet, the person they are trying to help ignores/disregards the help being provided such that the person providing the help invests even more time and energy helping that person. So, who is the "nutter" in this scenario? The person that is attempting to help or the person that won't take the time to try and understand the help being provided? You are "terrible" at this because you are not taking the time to understand the process. Instead you seem to be throwing things at the wall to see what will stick. Let's try one more time: Your requirement is to delete a record three days after the user performs some event (which I assume is a logout). Is this correct? 1) You first need to perform an action when the user selects the option to logout. As stated many times, you would want to set a datetime/timestamp value for the record. STOP HERE. Is there something about that statement that you do not 100% understand? Do you understand why the record would need to be updated and why we would use a datetime/timestamp value for that update? If you are not 100% clear, ask a question about that. You've previously provided info that when this action takes place the user_id is available in the session data. So, we would accomplish the above action like so: //Create a prepared statement with placeholder for the user_id of the record to be updated $stmt = $dbc->prepare("UPDATE users SET logout_datetime = NOW() WHERE user_id = ? "); //Bind the user_id value to the prepared query and execute it $stmt->bind_param('i', $_SESSION['user_id']); $stmt->execute(); STOP HERE. Do you understand all of the code above? If not, ask a question about what you don't understand or look at the manual for any function you don't understand. 2) Now that users will have a datetime/timestamp value set when they log out, there needs to be a separate process that will delete the records after three days. To accomplish this, you would create a separate script which will need to be executed on a regular basis (e.g. daily). You will need to check your host options o how to do this. Typically these will be called CRON jobs. You basically set up a scheduled task to run a script at a predetermined interval. STOP HERE. Do you understand what was just stated? If not ask a specific question. If you don't know how to create a CRON job, you need to go into your hosting options, check help and/or contact support. Once you know how to create a CRON job, you just need to create the script that will run every day (or whatever time interval you choose). Since we have a datetime/timestamp of when users have logged out, a single query can be executed to delete all records where that value is > 3 days (as has been provided previously) $query = "DELETE FROM users WHERE logout_datetime < (DATE(NOW()) - INTERVAL 3 DAY)"; //No user_id $stmt = $pdo->query($query) STOP HERE. Do you understand what that query is doing and why user_id is not needed? This is my last attempt. I hope you will READ the above information and attempt to comprehend it. If you have any questions that show that you have put some energy into trying to trying to figure this out instead of just haphazardly writing new code, I will try to answer. Otherwise, I which you all the best in your endeavors.
  19. I'm trying really hard now not to start using foul language. You are doing exactly what I said before. You aren't reading what is posted - as in looking at it critically and trying to comprehend what is being provided. Instead you seem to be fixated on some erroneous logic and are trying to fit the responses into that. Do you understand that what you want to accomplish has two separate processes (as I've explained multiple times)? If you have a question about what I posted ask a specific question about it instead of coming up with some nonsense question.
  20. I think you are misunderstanding something - why is there a placeholder for id in the delete query? Go back and read my last post and pay attention to the very explicit details I posted for steps #1 and #2. Then go back to the post I made before that where I provided example queries for #2 and neither included a user_id. I think the problem is that you have an incorrect assumption in your head and every new piece of data you are trying to align it with that assumption. You need to read the responses and not assume. It really isn't that difficult. I will try one more time to explain this. 1. When a user selects an option to logout you will run a process to set a logout time for that specific user. In this case you will get their user id from the session and run an UPDATE query similar to what Barand provided using the user_id to determine which records to apply the update to: $stmt = $dbc->prepare("UPDATE users SET logout_datetime = NOW() WHERE user_id = ? "); // prepare query with placeholder (?) for id value $stmt->bind_param('i', $_SESSION['user_id']); $stmt->execute() 2. Run a scheduled task to delete the records of ALL USERS where the logout_datetime is more than 3 days in the past. It will only use the logout_datetime field to determine which records to delete (i.e. no user_id). Also, there is no need to use a prepared statement since this does not use any input variables. $query = "DELETE FROM users WHERE logout_datetime < (DATE(NOW()) - INTERVAL 3 DAY)"; //No user_id $stmt = $pdo->query($query)
  21. As I understand your requirements, there appears to be some process that is initiated by the user that initiates the code you are currently working on. I assume it is a logout process, but you have not explicitly stated. Right now, the code is deleting the record, but you later stated . So, there needs to be TWO separate events: One to set the timer and one to delete the records. 1) Modify your existing code for the event so it sets the datetime/timestamp value for the user initiated action - this will occur for each user individually. 2) Create a process that runs daily (or whatever interval you decide) which will delete the records associated with all users where the applicable time period has elapsed. This is a single query that executes for all applicable records at once. Do NOT name your field datetime. That is a field type in MySQL and is a "reserved word". You would have to take special steps to prevent errors in your query if you have a field named using a reserved word. Give it a name that is representative of what it is: expirationDate, logoutDate, etc.
  22. @tryingphp you need to slow down. If you don't understand something, figure it out first or ask a question. It appears you are just copy/pasting code without understanding what it does and then throwing random edit at it. I don't see that you even acknowledged the original problem which @Barand and @ginerjm both stated. Your original query was simply deleting every record where the value in the user_id field was equal to itself. You wanted to delete those records where the user_id was equal to $_SESSION['user_id']! Your original query would look like this $sql = "DELETE FROM users WHERE user_id = $_SESSION['user_id']"; But, don't use that - it is unsafe. You should use prepared queries such as Barand provided (do some research, way too much info to explain in a forum post). I only provided it in that fashion because it is easier to visualize what was wrong. Then, Barand provides a different, more efficient solution and you try to integrate it into your current solution. Let me break it down for you: 1. Create a new field in the DB - I would suggest a timestamp or datetime. I assume this is a for a logout function, so the field could be logout_datetime. If not, name it something appropriate for the function being performed. 2. When the process is initiated, perform an update query (using the session value = user_id) and set the value in that field to either A) the current datetiem using NOW() or B) to the datetime three days in the future. I would use option A (explained below) 3. Have a scheduled task that runs each day/hour/whatever which will delete all the records based on the datetime value in the field above. If you go with option A, then this delete function would need to delete all records where the value is < today-3 days. Something like this: DELETE FROM users WHERE logout_datetime < (DATE(NOW()) - INTERVAL 3 DAY) If you go with option B, the logout function would run an update query similar to the above, but the interval would be +3 and the delete query would look something like this: DELETE FROM users WHERE logout_datetime < NOW() In either case, Do not use a query based on the values being equal. If the process was to ever not run one day you would have records that would exist indefinitely. So, you want to delete all records that are 3 or more days old. The reason I would go with option A is that if you ever needed to change the logic on the time period on which to delete, you could change it in the DELETE query and it will apply to all existing records. Otherwise, if you put the 3 day period as part of the update query, any changes would only apply to new records.
  23. I think you are greatly over-complicating the building of the Label for the select options. If you need different data for the value and the label, the approach I provided gives you more flexibility to explicitly set those two values. As per my signature: In any case, when I run the code I provided it works without error (assuming values are given for $offset & $total_records_per_page, which were assumed set somewhere in your code). I'm guessing you modified the code I provided or didn't fully implement it. Based on the error, I would say you updated the foreach() code, but did not update the array with the new structure.
  24. There are many ways. How I would do it would depend on factors that would require me knowing more about how the application is used, which I'm not going to invest time into. So, I'll give one solution. Change the array to be multi-dimensional such as shown below. If you haven't already caught on, the data for this array which defines the sorting parameters (key, label, fields and direction [ASC/DESC]) could be moved to the DB. $sortValues = array( 'newest' => array( 'label' => 'Newest', 'sortSql' => 'projects.date DESC' ), 'oldest' => array( 'label' => 'Oldest', 'sortSql' => 'projects.date ASC' ), 'lowest-price' => array( 'label' => 'Low to High', 'sortSql' => 'projects.price ASC' ), 'highest-price' => array( 'label' => 'High to Low', 'sortSql' => 'projects.price DESCC' ) ); //Create select options $sortByOptions = ''; foreach($sortValues as $sortKey => $sortData) { $selected = (isset($_GET['sort_by']) && $_GET['sort_by']==$sortKey) ? 'selected="selected"' : ''; $sortByOptions .= "<option value=\"{$sortKey}\" {$selected}>{$sortData['label']}</option><br>\n"; } //echo $sortByOptions within the <select> field //Determining the sort logic to use in query if(isset($_GET['sort_by']) && isset($sortValues[$_GET['sort_by']])) { $sortSql = $sortValues[$_GET['sort_by']]['sortSql']; } else { //Default if no user selection or selectio is invalid $sortSql = $sortValues['newest']['sortSql']; } //Use $sortSql in query after the ORDER BY clause $query = "SELECT images.image_id, currency.currency_name, users.username, users.user_id, projects.* FROM projects LEFT JOIN images ON projects.project_id = images.project_id LEFT JOIN currency ON projects.currency_id = currency.currency_id LEFT JOIN users ON projects.user_id = users.user_id WHERE projects.category_id = :category_id AND projects.publish = :publish ORDER BY {$sortSql} LIMIT $offset, $total_records_per_page";
  25. That's better, but you are hard-coding the list of select options and then use a series of hard-coded if/else statements that are dependent upon those hard coded values. This makes it difficult for maintaining your code. Create one source of truth for your sorting options, then use that source of truth to both create the select options and generate the SQL code for sorting. Here is a down an dirty example where the sorting properties are in an array of valid values. You could have more complex logic by utilizing a switch statement (I would not use a bunch of if/else statements) <?php $sortValues = array( 'Newest' => 'projects.project_id DESC', 'Oldest' => 'projects.project_id ASC', 'Lowest Price' => 'projects.max_budget ASC', 'Highest Price' => 'projects.max_budget DESCC', ) //Create select options $sortByOptions = ''; foreach(array_keys($sortValues) as $sortLabel) { $selected = (isset($_GET['sort_by']) && $_GET['sort_by']==$sortLabel) ? 'selected="selected"' : ''; $sortByOptions .= "<option value=\"{$sortLabel}\" {$selected}>{$sortLabel}</option><br>\n"; } //echo $sortByOptions within the <select> field //Determining the sort logic to use in query if(isset($_GET['sort_by']) && isset($sortValues[$_GET['sort_by']])) { $sortSql = $sortValues[$_GET['sort_by']]; } else { //Default if no user selection or selectio is invalid $sortSql = $sortValues['Newest']; } //Use $sortSql in query after the ORDER BY clause
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.