Psycho
Moderators-
Posts
12,145 -
Joined
-
Last visited
-
Days Won
127
Everything posted by Psycho
-
You could also just put a space between every character and put the text in a container with a width of 1px. <div style="width:1px">C L A S S</div>
-
Writing IP address to file using file_get_contents($htaccess);
Psycho replied to Danny620's topic in PHP Coding Help
Try this. <?php //Verify proper key passed if (!isset($_GET['key']) || $_GET['key'] != '78J89ke93k93HJ883j003') { echo 'Invalid Key'; exit(); } //Define file to edit $htaccess = '.htaccess'; //read the entire file $contents = file_get_contents($htaccess, false); //Verify that contents were read if(!$contents) { echo "Unable to read {$htaccess} file"; exit(); } //Get current IP of user $ip = $_SERVER['REMOTE_ADDR']; //'allow from 92.27.111.112'; //Check if IP already exists if(strpos($contents, $ip)) { echo "The IP {$ip} already exists in {$htaccess} file"; exit(); } //Add new IP to contents (assumes 'deny from all' exists in file) $contents = str_replace('deny from all', "allow from {$ip}" . PHP_EOL . "deny from all", $contents); //Replace the contents of the file if(!file_put_contents($htaccess, $contents)) { echo "Error updating {$htaccess} file"; exit(); } echo "IP {$ip} added to {$htaccess} file"; ?> Edit: I just realized that this may not work as written. I wrote it with the intent that the script above would be accessible to any IP addresses. If you have the script in the same folder as the htaccess file, then how would the user ever be able to make a change? They would have to access the page from an IP that is not restricted. So, I would suggest hosting this page in another locaiton. -
Writing IP address to file using file_get_contents($htaccess);
Psycho replied to Danny620's topic in PHP Coding Help
Why not keep the IPs in a database. Then when a change is submitted you can just overwrite the existing file. Otherwise, you could end up with duplicates. Otherwise you would have to parse the current file to check for duplicates. Anyway, there is no error handling in your current script. You should start there to check file_exists() (can PHP see the file), that it could open the file, etc. EDIT: I see the problem (or at least one of them). The IF statement is checking the "variable": $_GET('key') I would think that would generate an error since the "function" $_GET() does not exist. -
a little help continuing this script please
Psycho replied to Michael_Baxter's topic in PHP Coding Help
OK, you are creating checkboxes, but there is no form. Your initial post kind of alluded to the fact that you may want the update to occur dynamically when the user clicks the checkbox. That is what budimir was referencing when he mentioned JavaScript. That is certainly achievable, but right now let's focus on doing this the old fashioned way - with a form submission. Once you get that working you can re-purpose the logic and make the action dynamic (i.e. when the suer clicks the checkbox a back end call is made via AJAX to update the database without a traditional form submission). Also, since there will be checkboxes for each record - each checkbox needs to be associated with the record that it should be updating The example code below is not optimal. Ideally you should use the PRG pattern to prevent a refresh from resubmitting the form, but in this instance it shouldn't matter. The code below assumes that the 'win' column contains a 0 or 1. <?php include ('conection.php'); //define $result as $con and run the query $sql $result = $conn->query($sql); //Check if the form was posted if($_SERVER['REQUEST_METHOD']=='POST') { //Update database with posted values //Note only CHECKED checkboxes are sent in the POST data //Get array of IDs sent in the post data $winIDsPostAry = $_POST['win']; //Filter out any IDs that are non-numeric or 0 $winIDsAry = array_filter(array_walk($winIDsPostAry, 'intval')); //Create a comma separated string for the query $winIDsStr = implode(', ', $winIDsAry); //Create query to update all the records based on the checked values $query = "UPDATE table_name SET win = id IN ({$winIDsStr})"; //Run the query } //Variable to hold the output $output = ''; //Check if there were records returned if ($result->num_rows == 0) { $output .= "<tr><td colspan='4'>0 results found</td></tr>\n"; } else { //output the data while($row = $result ->fetch_assoc()) { //Determine current state of win $winChecked = ($row['win']) ? " checked='checked'": ''; //add the results to populate the table $output .="<tr>\n"; $output .="<td>{$row['id']}</td>\n"; $output .="<td>{$row['name']}</td>\n"; $output .="<td>{$row['score']}</td>\n"; $output .="<td><input type='checkbox' name='win[]' value='{$row['id']}' {$winChecked}></td>\n"; $output .="</tr>"; } } $conn->close(); ?> <html> <head> <title> DaTaBaSe CoNeCtIoN TeStInG PaGe </title> <style> body { color: #FF0000; background-color: #000000; } .myTable { border-collapse: collapse;} .myTable td, th { color: #FF0000; border: 5px solid #0000FF;} </style> </head> <body> <form action='' method='post'> <table class="myTable"> <tr><th>ID</th><th>Name</th><th>Score</th><th>Win</th></tr> <?php echo $output; ?> </table> </form> </body> </html> EDIT: I did not test this, so I'm sure there are some errors, but hopefully this will get you pointed in the right direction. -
There could be any number of reasons why - many that have nothing to do about technology, but with organization politics and/or division. For example, you may have different groups responsible for the "desktop" vs. "mobile". Plus, when mobile first became a major factor, responsive design was not at the forefront. It was all about the phone since tablets were still gaining momentum. Thus the goal was to support the desktop and phones - not everything in between. it was quicker to get an adaptive rewrite to production. Also, responsible web design requires a unique skillset for which there was not a huge amount of expertise initially. Once the adaptive web designs were done to meet the immediate need, there was less of a priority to go back and rewrite once again to be responsive. So, the early mobile adopters may be slower to responsive. Lastly, many of the companies you cite have specific mobile applications. Many sites try to push mobile users to install their mobile apps instead of expanding their generic web content to be optimal for small displays.
-
@SamuelLopez: Are there more than just the two statuses? If not, you should change the field to a Boolean. E.g. name the field "passed" and use 1 (TRUE) to indicate passed and 0 (FALSE) to indicate not passed. @Barand, Correct me if I am wrong, but I don't think the IF() statements are needed - just the conditions. A condition will resolve to either TRUE (1) or FALSE (0). So, this should work as well: SELECT projectid as project , SUM(Status_ID=1) as passed , SUM(Status_ID=2) as failed FROM tbltesttransactions GROUP BY projectid
-
Some feedback: There is something wrong with your sign-up form. I think it is expecting an email address as the username, but then it has two other fields to enter an email and verify it. If I enter a value that doesn't look like an email in the username field it gives me errors that the email and username are not available. Huh? It also appears the value must be the same in all three fields. Plus, when there is an error the first password field is being repopulated - you should never repopulate a password field when there are errors. If the email address will be the "username", then you don't need a username field. Just have the email and confirmation fields - but make it known that their email address will be used for their username. I don't know what browser you are testing with, but in Chrome that custom cursor is an eyesore. Lastly, the buttons for Login and Sign Up are not acting like buttons. I can't click on the buttons - I have to click exactly on the text.
-
Step 1: Create an array of values to be compared against. This can be set at the top of the script, in an external file or even in a database. The key takeaway is that this is DATA and should be separated from the LOGIC. Since we don't want to have to worry about string values not comparing because of an errant character in a different case, the values should be create in a specific case (lower or upper): /List of admin urls to test for $admin_urls = array('http://www.golden-wand.com/pages/admin.php', 'http://www.golden-wand.com/pages/admin-test.php'); Step 2: The condition: Comparisons work similar to mathematical order of operations: left to right with items in parenthesis worked inside out. The process is run to return an ultimate TRUE or FALSE response. 1. The first test checks to see if the session 'admin' value is 'loosely' equal to the string value '1' and results in a TRUE or FALSE for that partial comparison. 2. Next, there is an AND operator. If the first result was FALSE then the final result is FALSE and no further comparisons are needed. Since a FALSE AND any other result will be FALSE 3. strtolower() is run against the 'unknown' session value to convert it to all lower case. 4. the in_array() function then compares that lower case value to the array $admin_urls to see if the value is contained in one of the array elements. If it does exist in the array the partial result is TRUE, else it is FALSE 5. The "NOT" operator (!) is applied to the result of the above comparison - effectively switching the results. Therefore, if the value is NOT contained in the array the result will be TRUE - else it will be FALSE 6. THe results of the 'admin' comparison and the NOT in_array() comparison are tested. If both are TRUE, then the final result is TRUE. Else, the final result is FALSE. I hope that helps. If not, put the bong down before you burn any more brain cells.
-
I put the strtolower() specifically because of a different post you made a day or two ago around this same code where you have a condition check where the values being compared had a difference in the case of one letter. You can prevent those problems from ever happening again if you: 1) create the array of values to validate against in all lower case. 2) use the strtolower() on the value being tested However, I did make a mistake because I did not follow #1 above in the example code I provided. As my signature states, I do not always test the code I provide (especially if it would require me to create DB tables and add data) - it is provided as a guide for writing your own code. It should have been //List of admin urls to test for $admin_urls = array('http://www.golden-wand.com/pages/admin.php', 'http://www.golden-wand.com/pages/admin-test.php'); Unless there are legitimate reasons, you should generally not have logic that is dependent upon the 'case' of the letters within strings. By forcing things to upper or lower case you will prevent a lot of potential bugs
-
I gave you a complete, correct answer. But, since you apparently didn't understand it you dismissed it. What you are trying to do (include the URLs in the conditional logic) is a poor implementation. If you ever need to add/edit/remove any of the URLs used for this purpose you would need to modify the logic. Instead, I gave you a solution that allows you to modify the conditions (i.e. the URLs) without ever having to touch the logic. All you would ever need to do is modify the array "$admin_urls" to add/edit/delete any URLs you want used for the conditional check and the logic will work. And simple does not mean less lines of code - it typically means more lines. I can cram a whole bunch of conditions, loops, whatever onto a single line. That makes it more complicated to read, debug, edit. A simple solution is one that removes complexity. Usually it means each line of code has a specific purpose. EDIT: The only flaw I see in what I provided was that I read the logic as wanting to see if the session value was in the list of tested URLs. I now see that you wanted to verify it was not in that list of values. Simple enough change //List of admin urls to test for $admin_urls = array('http://www.golden-wand.com/Pages/admin.php', 'http://www.golden-wand.com/Pages/admin-test.php'); //One simple if() condition if($_SESSION['admin']=='1' && !in_array(strtolower($_SESSION['url']), $admin_urls)) { echo "<input type=\"button\" value=\"Admin Page\" class=\"button hvr-wobble-skew\" onclick=\"location.href='http://www.golden-wand.com/Pages/admin.php'\">\n"; }
-
Absolutely, separate the data from the logic. That way you can change the values being checked without ever having to change the actual code. <?php //List of admin urls - this can be defined elsewhere $admin_urls = array('http://www.golden-wand.com/Pages/admin.php', 'http://www.golden-wand.com/Pages/admin-test.php'); //One simple if() condition if($_SESSION['admin']=='1' && in_array(strtolower($_SESSION['url']), $admin_urls)) { echo "<input type=\"button\" value=\"Admin Page\" class=\"button hvr-wobble-skew\" onclick=\"location.href='http://www.golden-wand.com/Pages/admin.php'\">\n"; } ?>
-
empty cell in data in columns (display record from database)
Psycho replied to sigmahokies's topic in PHP Coding Help
Try this: <?php //Define the number of columns allowed $max_columns = 3; //Query the data $query = "SELECT ID, FirstName, LastName, MonthEx FROM Members ORDER BY LastName"; $result = mysqli_query($Garydb, $query); //Put results into an array $rows = array(); while($rows[] = mysqli_fetch_array($result, MYSQLI_ASSOC)) {} //Determine the number of rows $max_rows = ceil(count($rows) / $max_columns); //Separate data array into chunks for each column $data_chunks = array_chunk($rows, $max_rows); //Generate HTML output (into a variable) $output = ''; //Iterate over the array chunks while not empty while(count($data_chunks[0])) { //Open new row $output .= "<tr>\n"; //Get next record from each chunk foreach($data_chunks as &$chunk) { //Remove the first element off of the current chunk $data = array_shift($chunk); if(empty($data)) { continue; } //Create the $output .= "<td>{$data['FirstName']} {$data['LastName']}</td>"; $output .= "<td><a href='update.php?update={$data['ID']}'>EDIT</a></td>"; $output .= "<td><a href='delete.php?delete={$data['ID']}'>DELETE</a></td>\n";; } //Close the row $output .= "</tr>\n"; } ?> <html> <head></head> <body> <table border='1'> <?php echo $output; ?> </table> </body> </html> -
empty cell in data in columns (display record from database)
Psycho replied to sigmahokies's topic in PHP Coding Help
With all due respect, your grammar and punctuation is atrocious. I am not a grammar nazi, but what you wrote is very difficult to understand. If you want to get free help, the least you can do is write a clear request. I can't tell if you want the data to go top-down/left-right or left-right/top-down. Do you want this 1 2 3 4 5 6 Or this 1 4 2 5 3 6 -
You only need to include a link to a txt file if you are wanting us to run some specific tests on your site. You do not need it to ask a question about some code. You may have a failure on both conditions: if($_SESSION['admin']==='1'){ The three equal signs means it has to match the value and the type - i.e. it has to be a string value of one. A numeric value of 1 will not pass the condition. On the second condition it will never match because "pages" does not equal "Pages"
-
Jacques1 point is that the SELECT statement to check for a duplicate is faulty. Instead, you should just attempt the INSERT. Then, if the INSERT fails due to a duplicate constraint, you can then inform the user that the name is already taken. The current process has a hole in the logic. Granted it is very small, but it leaves the possibility for a race condition where two requests are made at the same time such that both SELECT queries pass, but then both try to do an INSERT with the same value. One will succeed and the other will fail - with no proper error handling. I believe the error code for a unique constraint is 1062. So, you would check for that error code after attempting the INSERT. Also, you should almost always trim() user submitted values. A password would be one example that it would not make sense to do so. You currently have no validation of the user submitted values: e.g. ensuring required fields have values, that the values contain content appropriate for the context, etc. I assume you plan on adding that, but you would need to trim them before doing that. I would also add some logic to setting the variables from the post values to handle if a field is not passed. E.g. $firstname = isset($_POST['FName']) ? trim($_POST['FName']) : false;; Otherwise you will get warnings if a field isn't included.
-
How to retain select box value after submit
Psycho replied to samuel_lopez's topic in PHP Coding Help
I prefer to create a function to generate my select fields. I would also highly suggest you follow a standard of putting your logic (i.e. PHP code) at the top of the document and only output the generated content within the HTML at the bottom of the page. Here is a quick example <?php //Function to create select options function createSelectOptions($optionList, $selectedValue=NULL) { $optionsHTML = ''; foreach($optionList as $value => $label) { $selected = ($value == $selectedValue) ? " selected = 'selected'" : ''; $optionsHTML .= "option value=\"{$value}\"{$selected}>{$label}</option>\n"; } return $optionsHTML; } //Get previously selected value (if passed) $projectSelected = isset($_POST['project']) ? $_POST['project'] : NULL; //Query list of available values $projectList = array(); $query = "Select Proj_ID as value, PROJECT_NAME as label from tblproject"; $result = $mysqli->query($query); while($option = $result->fetch_object()) { $projectList[$option->value] = $option->label; } //Create the options for the project select list $projectOptions = createSelectOptions($projectList, $projectSelected); ?> <html> <head></head> <body> <select name="project" class="required" id="selproject"> <?php echo $projectOptions; ?> </select> </body> </html> -
Also, by default, PDO only emulates prepared statements. You should ensure you are turning off emulation in your connection to the DB. See this post by Jacques1 for an example: http://forums.phpfreaks.com/topic/298661-help-needed-with-signuplogin-page/?do=findComment&comment=1523598
-
How can I get client timezone using PHP/JS
Psycho replied to aHMAD_SQaLli's topic in PHP Coding Help
The timezone offset is basically the timezone. The timezone offset is the difference from the the user's timezone and UTC time. So, you can calculate a time in the user's timezone based on the offset. But, you need to ensure the the times you are storing are in UTC time. Then, when you retrieve the time (from the database) modify it to the user's timezone.- 4 replies
-
- 1
-
- php
- javascript
-
(and 1 more)
Tagged with:
-
Your query is malformed $del = "DELETE * FROM Members WHERE ID = '".$delete."'"; There is no field list for a delete query, e.g. the * Try this: $del = "DELETE FROM Members WHERE ID = '".$delete."'"; Also, your code is full of security risks - particularly with SQL Injection. You should spend some time learning some best practices.
-
JavaScript alerts do not have the ability to add checkboxes or other fields. You can use something like a JQueryUI dialog: https://jqueryui.com/dialog/#modal-form
-
I can't give you any advice as you still have not answered my previous questions. Are the fees a one-time event or will there be recurring fees: monthly, yearly, etc? Are the fees to be paid in their entirety when paid or can they be paid partially?
-
You didn't answer my questions, so why should I take the time to answer yours? I don't see how the joined date can be used to know if a user has paid their fees (even though the field doesn't even state that it is a joined date). That date only tells you, presumably, when they joined. So, what data are you storing to know when a user has paid the fees? Are you reducing the fees field when they make payment? That's a poor way to do it since you would have no history of exactly when they were paid and how much they paid. But, making a HUGE assumption that the fees field is the outstanding fees (which is a terrible process), this query would get you the list of users who have an outstanding fee and their joined date was > 30 days ago. SELECT id, fname, name, fee, `date` FROM users WHERE fees > 0 AND date < CURDATE() - INTERVAL 30 DAY Or, if you want ALL the users to display in a list and show specific notices next to the ones who's fee is pending, you could either add that logic to the output processing OR you could add a dynamic field to the query result. SELECT *, (`date` < CURDATE() - INTERVAL 30 DAY and fees > 0) as fee_due FROM `users` But, if you are doing as I suspect, it is a poor implementation.
-
how to append comment values to respective posts in php
Psycho replied to shan2batman's topic in PHP Coding Help
The problem is not the query. The problem is likely the logic in displaying the output. I expect you have a loop to process all the records in the result set. You need to have logic so the first record in the result set display the post content and the first comment (if it exists). Each subsequent record in the result set should only display the comment. But, there is a problem with the query. It uses a normal JOIN. So, if there are no records in the comments table, the post won't be returned either. This needs to use a LEFT JOIN so all relevant posts will be returned - even if they do not have comments. -
Not enough information to help: Are these one-time fees? If not, you will need to track when fees are paid separately from the joined date. In fact, it should be stored in a separate table so you can maintain a history. Even if the fees are a one-time event, there's nothing in your current table to know if fees have been paid or not. And, unless fees are required to be paid in full at one time, you would still want a separate table to track them. Only if fees are paid once (non renewed) and in full at once, you will need a separate table. And, even if it is all at once and non-recurring, you will need an additional field in the existing table to track when they are paid. So, some database changes will be needed. Then, how are you wanting these reminders to occur? Do you just want a reminder through the UI - either the user sees it when logging in, a management page, etc. Or, do you want a proactive notification such as an email? The former just requires a DB query to get the requisite data and display the appropriate content. But, the latter would require a scheduled even to check for payments that are older than a specified period and initiate an email or emails.
-
It is my understanding that a timestamp is the correct type if the "event" is one that must be normalized based upon a given user's timezone. A datetime is one that would be statis regardless of timezone. For example, if I am recording the date and time that someone is born, you would display the exact same date and time to a user regardless of their locale (a datetime type). Otherwise, my birthday would be a day earlier if I traveled to Europe. Conversely, if I was to record the date and time of when a specific event was to occur, such as the super bowl, I would use a timestamp so it could be displayed as to the correct date and time relative to the user.