Jump to content

Psycho

Moderators
  • Posts

    12,118
  • Joined

  • Last visited

  • Days Won

    124

Everything posted by Psycho

  1. @kicken's answer is "correct", but I would highly advise against using such a general function. While that function is correctly using a prepared statement and protecting the $sid value, you cannot use prepared variables for table/column names. This leaves open the possibility for that function to open a potential exploit depending on how it is called. A function/method should be secure on its own without having to worry about how it is called. While prevailing logic is to write code once (i.e. don't build duplication functionality) when dealing with data it is typical to have explicit setter/getter functions/methods for scenarios such as this.
  2. To add some clarification, when there are multiple ORDER BY conditions, the query will order by the first condition. Then, if there are records with the same value in that first condition, then it will sort those records by the second condition. And so on through all conditions. I.e. the second (subsequent) condition(s) only apply when two records have the same value for the first (preceding) conditions. As @cyberRobot stated, your query will first sort all records by the project_id. Then, if any records have the same project_id (a scenarios I expect would never occur), then it would sort those records would be sorted by the featured value. I would also add that I assume project_id is an auto-increment primary key field. Using that for sorting by newest/oldest will "probably" work in most instances, but is a poor implementation. There are many scenarios where such a field would not necessarily be in order of when the records were created. I would suggest having a "date_created" field that is auto-populated when new records are created and using that for sorting by newest/oldest
  3. Heck, I'd still go with the original "simple" auto-increment field solution. All that really matters is that the numbers are unique for each raffle. What does it matter if the number are not sequential! E.g. Raffle #1 has four tickets sold with four unique numbers: 1, 4, 7, & 8.
  4. Here is the line you would need to modify if ($_POST['submit'] && $human == ‘wednesday’) {
  5. Then you need to do that first. Your form, as it is, doesn't even have all the data you need. For example, you are outputting the fields associated with a date, but the "groups" of fields have nothing to indicate which date they are with. So, if the user submits you will have no way to know what date to use when inserting/updating the records. You should absolutely work on building a working process before adding the javascript. I foresee many other posts from you trying to work through what should be trivial issues if you just @Barand's code as-is without determining the naming/structure of the fields. Plus, since you are copying only a manager OR chef line (not the block), I think the AJAX call is unnecessary since all the data you need is within the DOM object. First, you need to determine how you will logically "group" fields and ensure each group has the necessary data. E.g. how do you know which name/start/end fields go together. You will also need a hidden field to identify the date in each group of fields. Plus, if you are dealing with the ability to edit existing records as well as add records, you need an identifier to know which groups of fields are associated with existing records. If done quickly without much thought the act of copying a row can become quite complicated. If done with some thought, it makes the job much easier. Below is a working example that does not use AJAX. Note that the "rec_id" field is to be populated with the ID when creating the page for the existing records. Entries added with the "Add" button will have an empty value. So, on the page that receives the form submission, you would use that data to determine whether to perform an UPDATE or INSERT. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $( function() { $(".addRow").on( "click", function() { //alert('test'); //Make reference to the parent row var parentRow = $(this).closest('tr'); //Create a copy of the parent row var newRow = parentRow.clone(); //Remove values in the Cloned Time & ID fields $(newRow).find('input[name^="start_time"]').val(''); $(newRow).find('input[name^="end_time"]').val(''); $(newRow).find('input[name^="rec_id"]').val(''); //Select the name based on parent record and disable $(newRow).find('select[name^="name"]').val($(parentRow).find('select[name^="name"]').val()); $(newRow).find('select[name^="name"]').prop('disabled', true); //Remove the add button $(newRow).find('button').remove(); newRow.insertAfter(parentRow); return false; }) }) </script> </head> <body> <form> <table id='staffOrderTable' class='table table-striped table-bordered mt-3 text-center'> <tr> <th class='table-dark' colspan='3'>Tuesday - 24th December 2019</th> </tr> <tr> <th class='' colspan='3'>Management </th> </tr> <tr> <th class='col-4'>Name</th> <th class='col-4'>Start Time</th> <th class='col-4'>End Time</th> </tr> <tr> <td> <input type='text' name='date[]' value='2019-12-24'> <input type='text' name='rec_id[]' value='21'> <select class='custom-select managerSelect' name="name[]"> <option value='5'>Manager A</option> <option value='9'>Manager B</option> <option value='2'>Manager C</option> </select> </td> <td><input class='form-control' type='' name='start_time[]' value='6:00'></td> <td><input class='form-control' type='' name='end_time[]' value='14:00'></td> <td><button class='addRow'>Add Row</button></td> </tr> <tr> <th colspan='3'>Chefs</th> <tr/> <tr> <th class='col-4'>Name</th> <th class='col-4'>Start Time</th> <th class='col-4'>End Time</th> </tr> <tr> <td> <input type='text' name='date[]' value='2019-12-24'> <input type='text' name='rec_id[]' value='54'> <select class='custom-select chefSelect' name="name[]"> <option value='8'>Chef A</option> <option value='4'>Chef B</option> <option value='7'>Chef C</option> </select> </td> <td><input class='form-control' type='' name='start_time[]' value='7:00'></td> <td><input class='form-control' type='' name='end_time[]' value='12:00'></td> <td><button class='addRow'>Add Row</button></td> </tr> <tr> <th class='table-dark' colspan='3'>Tuesday - 24th December 2019</th> </tr> <tr> <th class='' colspan='3'>Management </th> </tr> <tr> <th class='col-4'>Name</th> <th class='col-4'>Start Time</th> <th class='col-4'>End Time</th> </tr> <tr> <td> <input type='text' name='date[]' value='2019-12-25'> <input type='text' name='rec_id[]' value='33'> <select class='custom-select managerSelect' name="name[]"> <option value='5'>Manager A</option> <option value='9'>Manager B</option> <option value='2'>Manager C</option> </select> </td> <td><input class='form-control' type='' name='start_time[]' value='6:00'></td> <td><input class='form-control' type='' name='end_time[]' value='14:00'></td> <td><button class='addRow'>Add Row</button></td> </tr> <tr> <th colspan='3'>Chefs</th> <tr/> <tr> <th class='col-4'>Name</th> <th class='col-4'>Start Time</th> <th class='col-4'>End Time</th> </tr> <tr> <td> <input type='text' name='date[]' value='2019-12-25'> <input type='text' name='rec_id[]' value='74'> <select class='custom-select chefSelect' name="name[]"> <option value='8'>Chef A</option> <option value='4'>Chef B</option> <option value='7'>Chef C</option> </select> </td> <td><input class='form-control' type='' name='start_time[]' value='8:00'></td> <td><input class='form-control' type='' name='end_time[]' value='16:00'></td> <td><button class='addRow'>Add Row</button></td> </tr> </table> </form> </body> </html>
  6. You don't have to do this with JavaScript - although it would provide a better user experience. In fact, I think it is beneficial to build such functionality w/o JS to start and then add JS. But, I am unclear from your goal as to whether you are wanting to add management and chef rows independently or complete sections with both a management and chef line (or something else). Also, using a framework like JQuery is always a good idea. EDIT: I just noticed none of your input fields have names. Are you intending for the user to submit the form once filled out and do something with that data? I would assume so and in that case the naming of the fields is important if you are going to be dynamically adding fields.
  7. What you are calling duplicates are not, in fact, duplicates. I'm curious what made you think a UNION clause was needed? In the response to @Barand's query you showed a result set of five records each having a different gp_id value In other words, they are unique records. I can see that they contain much of the same data, but they are distinct records. What makes you consider them "duplicates"? I think your problem may stem from a schema problem. I see multiple things in what you are doing that don't make sense. For example, you are joining the user and updates tables using the name of the author? You would typically be joining tables based on IDs rather than arbitrary string values. Is the group_posts table for conversations between multiple individuals and are you adding a new record for each response in that conversation? What determines which records are form the same conversation?
  8. My suggestion was just an example. It will work if implemented correctly. People want to see all the relevant code for a problem. It is incumbent upon the person with the problem to do the basic trouble shooting to determine the area of the code where the problem exists and provide that code. The person should also provide what the code is expected to do and what is IS doing differently than the expectation. I gave a potential explanation of why you would get duplicates if you are simply basing the additional records to get based on an index when ordered by date/time. When you are seeing duplicates - are there other records being added to the system that would be included in the user's feed? If so, that is likely why you are seeing duplicates. Here is an illustrative example: Let's say there are 6 records added from A - I. When you retrieve the first five records in reverse chronological order using LIMIT 0, 5 (which gets five records starting at index 0, i.e. 0 - 4) you will get I-E, because the query will see something like this (number in parenthesis represent the index of the records matching the criteria). Now, let's say a new record is added (J) THEN you attempt to get the next five records using LIMIT 5, 5 (i.e. indexes 5-9). You will get a duplicate of record E, because it will have moved from index 4 to 5. Based on your function totalUpdates() that returns five records based on an arbitrary $load variable to indicate the limit start index. I can't say that IS your problem, but it will be a problem if records are being added in-between the load calls. In any event, I suggest you add some logging to see what is going on. I would start by logging the calls to the totalupdates() function to verify that the $load value is what you expect (0, 5, 10, 15, etc.). I would also log the total number of records that match the conditions of the query (w/o the limit condition). That requires adding a second copy of the query with a count() instead of returning the results, but it would only be used for debugging purposes.
  9. I doubt anyone is going to try to read through and comprehend all of that code to try and deduce why you are having a problem. YOU need to do some debugging to narrow down the problem and then you are likely to get some responses. I'm certainly not going to read through all that and try to figure out what the code is doing in and where your problem may be, but one thing that jumps out at me is the query you are using and the use of LIMIT with a start index. I don't know if you have people actively using the application while you are seeing duplicates, but the use of a start index will not work if new posts are being created. Let's say you grab the first five records (indexes 0-4), then before you grab the next five records, someone adds another record. When you go to get records based on a start index of 5, the record that was index of 4 on your first query will now be an index of 5 and cause a duplicate to be displayed. I would suggest passing the ID or timestamp of the last record that was previously obtained. Then fashion your query something like this SELECT .... FROM ... WHERE ... AND date_created < (SELECT date_created FROM ... WHERE id = [id of last record]) LIMIT 5
  10. As @Barand has stated, without knowing what $update_id1 contains and it's exact structure, it is impossible to know what the problem is, but I have a couple of comments 1. Your original post contained this $update_id1=Array ( [0] => 398 [1] => 397 [2] => 393 [3] => 391 [8] => ); //$i=0; foreach ($update_id1 as $i => $v) { $ex= explode(",", $v); $unique=array_unique($ex); //f$ketch username from update table in db and inject it to the feed query. $imp_id= implode(',', $ids); //$id1=$ids[$i]; // $x=0; // for($x=0;$x<count(unique);$x++){ echo 'ids:- '.$i; print_r($unique[$i]); echo '<br>'; } Assuming there was a "real" array defined, within the foreach() loop the code first does an explode on the value - even though your example values have no commas for the explode. Then you store the unique values in a new variable called $unique. Then you do an implode of an array called $ids - which has never been defined. I think you meant to do an implode of the unique values ??? 2. While this line may work $r["friend_one"] == $_SESSION['uname'] ? $friends[]= $r["friend_two"] : $friends[] = $r["friend_one"]; . . . it is an awkward implementation. This is much more precise and readable. $friends[] = ($r["friend_one"] == $_SESSION['uname']) ? $r["friend_two"] : $r["friend_one"]; But, I'm betting there is a better way to determine the value within your query.
  11. This error is self explanatory When you call the function getimagesize() you are providing the variable $oriented_image. That variable is the result of the function getOrientedImage(). $source_file = $_FILES["fileToUpload"]["tmp_name"]; $oriented_image = getOrientedImage($source_file); You are passing a string value that represents the path to the image. But, the result of that image is an image resource. You need to provide the image path to the image in the function getimagesize(). You should modify the getOrientedImage() function to overwrite the original image with the rotated image. Then you can use the same imapge name/path in the getimagesize() function. For this error The function takes two parameters : the original name of the file and the new name - in that order. You are providing the new name as the first parameter and the new path as the 2nd parameter. How is the function supposed to know "which" file you want to rename? if(rename($new_image, $new_file_path)) { You need to determine the complete new path and name as a single string and pass that as the 2nd parameter. The first parameter needs to be the full path and name to the current file.
  12. readdir() returns all the "items" in a directory - that includes the '.' and '..', because that is how the file system works. As to your second comment, I think you did not understand @requinix's response. From the 1st line of the description in the manual for readdir() It just returns a string value for the name of the entity. Then, if you look at the manual for is_dir() it states
  13. If the value is a negative integer - it should fail. Factorials of negative numbers is not possible (e.g. division by zero) - unless you want to get into abstract complex numbers which would require the use of the gamma function. The only valid values for a factorial are positive integers from zero to ∞. The only exception I can think of to the ctype_digit() test would be if you wanted to allow a plus symbol; in which case you would still need to remove it during the computation.
  14. The OP never stated "where" the value is coming from. If the value is coming from a POST/GET variable it will ALWAYS be a string and always fail the is_int() test - even if the value is something like "5". If the value is specifically cast as an integer then there would be no reason to even test if it is an integer to begin with. So, it would only make sense to test if the value "looks" like an integer when it is an unknown string value that can be a string representation of an integer or some other invalid value. @Barand's test makes more sense.
  15. FWIW, what the task to specifically create a recursive function? If not, you can get a factorial much simpler (of course you'd still want the integer check array_product(range(1, $number));
  16. There is nothing in that code to sort the results in the array. readdir() (as stated in the manual) returns the results " . . . in the order in which they are stored by the filesystem". You could determine the file date and sort by that, but since you are copying them from one device to another, there is a good chance that the file date will be changed in that process. Sometimes the date changes in a copy process and sometimes it does not - depends on the process used. Also complicating things, filetime() will return different values based on the filesystem. As I understand it, in Windows it returns the creation time, whereas in Unix it returns the modification time. So, you could potentially sort using filetime() IF the original file creation times are preserved after they are copied AND filetime() returns the creation date. You should be able to verify if those are both true in your case. If so, get the creation date using filetime() and sort on that. If that is NOT the case, then you could either ensure they are copied in the correct order (i.e. one at a time in the order they were created) or you need to sort using some manner. For example, the named of the files is sequential. So you could sort by file name. But, when you go from IMG_9999.jpg to IMG_10000.jpg it will break that logic as IMG_1... comes before IMG_9... when sorting alpha-numerically. Of course, you could always parse the file names and convert them to have x number of digits, i.e. IMG_9999.jpg converts to IMG_0009999.jpg and IMG_10000.jpg converts to IMG_0010000.jpg. Also, your phone *may* restart that numbering at some point which basically screws all of that up. So, lots of possibilities, but no bullet-proof solution. The *best* solution would be predicated on the questions on how the files are handled in the environment (dates when copied, whether file names change, etc.).
  17. The PHP code you present puts single quotes around the parameter values, but you are stating that the code in the browser has double quotes around the parameter values. If that is the case, then something is changing the content. What you showed as the output for the $ename variable also points to this. I've known browsers to "self correct" bad code with respect to the display (e.g. if closing tags are missing they may assume they are there), but I've never known a browser to change the code (if that is what is doing it). That is going to make debugging much more difficult than it should be,
  18. What he said. There is no way to positively determine if an element is a folder or file by the name. A files doesn't have to have an extension. It's kind of difficult to create a file w/o an extentiosn, but not impossible. But, the function is_dir() [or the converse is_file()] will positively make that distinction.
  19. @Adamhumbug What you have posted is impossible and, if the problem is even remotely as you say it is, has nothing to do with a ' character. You show that you are outputting the content using [ic]echo "<td><a class='btn btn-primary col-sm-12' . . . [/ic] Where the string is defined using double-quotes and the parameters of the tags are in single quotes. But, then you show that output like this: [ic]<a class="btn btn-primary col-sm-12" . . . [/ic] Where the parameters are in double quotes. That is not possible. And it would make HUGE difference in the output based on if the variables have single/double quotes Secondly, you state that the value causing the problem is due to a ' character. That is also not possible. If this [ic]data-active-sheets='".$ename."'>Manage</a></td>";[/ic] Produces this: [ic]data-active-sheets="A new event,Chelsea" s="" event'="">Manage</a>[/ic] Then the value of $ename is A new event,Chelsea" s="" event'=
  20. Not sure why you have all the unnecessary parameters in the function - unless there is some use I am not seeing. This will produce the same output function groupAndExtractByAspect($inputAry, $aspect) { $outputAry = array(); foreach($inputAry as $key => $dataAry) { //Skip if not the selected aspect if($dataAry['aspect'] != $aspect) { continue; } $outputAry[$dataAry['density']] = $dataAry['resolution']; } return $outputAry; } $showArray = groupAndExtractByAspect($arrayVideoSpecs, '16:9'); echo '<pre>'; print_r($showArray); echo '</pre>'; Alternatively, you could just generate a new multi-dimensional array that create the values for ALL aspect ratios function groupAndExtractByAspect($inputAry, $aspect) { $outputAry = array(); foreach($inputAry as $key => $dataAry) { $outputAry[$dataAry['aspect']][$dataAry['density']] = $dataAry['resolution']; } return $outputAry; } This will produce: Array ( [4:3] => Array ( [442368] => 768x576 [307200] => 640x480 ) [16:9] => Array ( [2073600] => 1920x1080 [121600] => 1280x720 ) )
  21. As @gw1500se stated, the DELETE query is malformed as it does not include the "FROM" parameter, but it still won't work with that $conn->query("DELETE email_user WHERE id='$user_id'"); $user_id is never defined!!! Aside from that, there are quite a few problems and poor construction. Here are some tips: 1. Put your DB connection logic in a separate file and include() it on the pages you need it. If you need identical code on multiple scripts, don't use copy/past coding. If you ever need to make a change in your DB connection you would only have to change it one place and not many. 2. Never user "SELECT *". There are performance and security problems with doing that. Always list the fields you want. 3. Don't suppress errors using the '@' symbol. You could have simply used an isset() check for the variable in your script. if(isset($_GET['key']) && $_GET['key']!=""): 4. I would highly suggest not wrapping your error conditions in nested if/else conditions in this manner as it makes it difficult to easily "see" which results go with which error if(!error_condition_1) { if(!error_condition_2) { if(!error_condition_3) { //Success result } else { //error result 3 } //error result 2 } //error result 1 } This is MUCH more readable and maintainable IMO if(error_condition_1) { //error result 1 } elseif(error_condition_2) { //error result 2 } elseif(error_condition_3) { //error result 3 } else { //Success result } 5. You are switching back and forth between object oriented and procedural. Stick with one for consistency $fetch = $conn->query("SELECT * FROM email_user WHERE hash = '$hash'"); //$count = mysqli_num_rows($fetch); $count = $fetch->num_rows; 6. Use prepared statements for your queries. 7. No need to use a SELECT statement before running the DELETE query. A race condition can create problematic results. You can just run the DELETE query and then check the number of affected rows. If 0, then there was no matching record, else if 1 then you can tell the user they were unsubscribed.
  22. First, use glob() to store the results into an array variable. Then you can perform operations on that array BEFORE you use the foreach() loop to generate the output. E.g. //Get the files in the directory $filesAry = glob("{$directory}/*"); //Sort the array in reverse order rsort($filesAry ); //Output the results foreach($filesAry as $file) { //Create the output } If you want to sort by date/size/etc, then where I have rsort() above, I would run a foreach() loop over the file names and create a multi-dimensional array with all the data, then you can use usort() with a custom function to sort however you wish.
  23. 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>"; }
  24. 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
  25. 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.
×
×
  • 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.