Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
I think you misunderstand what date('I') is. It does not state whether daylight savings time is "turned on" or not on the server. It returns whether the timestamp passed to the date() function is within the the dates for daylight savings (When no timestamp is passed it uses the current timestamp). This year, daylight savings in US/Canada goes from March 13, 2016 to Nov 6, 2016. Any timestamp passed to date() within those two dates will return true for the "I" parameter for those timezones where it applies. You cannot "turn that off" any more than you can turn off Christmas from being on Dec. 25th. What are you, specifically, trying to accomplish and/or what problem are you experiencing that the daylight savings is causing?
-
Pagination, results between Prev and Next button
Psycho replied to Giovanni's topic in PHP Coding Help
An easier way is to set a page link offest. E.g. the pages in the pagination list will be +/- 5 pages from the current page. That means if you are on either end of the total pages one side will be less than the offset. There are quite a few problems and inefficiencies with your code. Here is a quick rewrite - have not tested so there may be some minor errors. Read the comments to understand what is happening. There are a lot of other improvements I would make to this, but did not want to invest the time. <?php //------ Configuration variables -------- $recordsPerPage = 10; //Define the records per page $pageLinkOffset = 5; //Offset for displayed pages //--------------------------------------- //Connect to DB require_once('./include/connect.php'); //Get the total number of records and pages $query = "SELECT COUNT(*) as record_count FROM member"; $result = mysqli_query($link, $query); $row = mysqli_fetch_assoc($result); $totalRecords = $row['record_count']; $totalPages = ceil($totalRecords / $recordsPerPage); //Get the requested page $page = isset($_REQUEST["page"]) ? intval($_REQUEST["page"]) : 1; //If requested page is not within the range of available pages, set to page 1 if($page<1 || $page>$totalPages) { $page = 1; } //set limit start value and run query to get records $limitStart = ($page-1) * $recordsPerPage; $query = "SELECT date, id1, id2, id3, id4, id5, id6, id7 FROM member LIMIT {$limitStart}, {$recordsPerPage}"; $result = mysqli_query($link, $query); //Create the output $output = ""; $output .= "<center>(You are on Page <b>{$page}</b> of <b>{$totalPages}</b>)</center>\n"; $output .= "<center>Currently there are <b>{$totalRecords}</b> entry's in the Database</center>"; //Iterate through the results to create the output while($row = mysqli_fetch_assoc($result)) { //Do something with $row to create output for each record $output .= ""; } //Create pagination links $paginationLinks = ""; //Ouput variable //Define start/end pages to show in links based on // offset and current page $pageLinkStart = max($page-$pageLinkOffset, 1); $pageLinkEnd = min($page+$pageLinkOffset, $totalPages); //Make the root url for action attribute safe $pageURL = htmlentities($_SERVER['PHP_SELF']); //Create prev page link if($page > 1) { $prevPage = ($page-1); $paginationLinks .= "<a href='{$pageURL}?page={$prevPage}' class='button'><b> << Prev</b></a> \n"; } //Create links for pages for($pageNo = $pageLinkStart; $pageNo <= $pageLinkEnd; $pageNo++) { if($page == $pageNo) { $paginationLinks .= "<span class=active_page>[{$pageNo}]</span> \n"; } else { $paginationLinks .= "<a href='{$pageURL}?page={$pageNo}'></a> \n"; } } //Create next page link if($page < $totalPages) { $nextPage = ($page+1); $paginationLinks .= "<a href= '{$pageURL}?page={$nextPage}' class='button'><b>Next >></b></a> \n"; } mysqli_close($link); ?> <html> <body> <?php echo $output; ?> <br><br> <?php echo $paginationLinks; ?> </body> </html> -
My regex validation for mobile phone numbers failing
Psycho replied to terungwa's topic in Regex Help
I was already working on this when Jacques1 replied. A couple notes: 1. The function should simply return the Boolean True/False. The code that calls the function should determine the output. 2. Rather than putting the area codes in the regex patter directly, I would suggest defining them as an array and dynamically creating that part of the RegEx. It will make it much easier to maintain the code. 3. For something like this,you should create a unit test that allows you to pass a lot of different values so you don't have to manually test individual values. function check_number($number) { $areaCodes = array('704','702','803','806','703','706','813', '816', '810','814','903','802','708','808','812','701', '902','809', '817','818','909','908','805','705','815','807','811','905'); $areaCodeRegEx = implode('|', $areaCodes); $pattern = "/\\A(?:\\+?234|0)?(?:{$areaCodeRegEx})\\d{7}\\z/"; return preg_match($pattern, $number); } $testNumbers = array( '1234567' => false, //No area code '8021234567' => true, //Area code + 7 digits '802123456' => false, //Area code + 6 digits '80212345678' => false, //Area code + 8 digits '+2348161234567' => true, //Optional +code + area + 7 digits '+234816123456' => false, //Optional code + area + 6 digits '+23481612345678' => false, //Optional code + area + 8 digits '2347048134704' => true //Optional +code + area + 7 digits ); foreach($testNumbers as $number => $expected) { echo "Number: {$number}"; echo ", Expected: "; echo ($expected) ? "Valid" : "Invalid"; $actual = check_number($number); echo ", Actual: " . (($actual) ? "Valid" : "Invalid"); echo ", Result: "; if ($actual==$expected) { echo "<span style='color:green;'>Pass</span><br>\n"; } else { echo "<span style='color:red;'>Fail</span><br>\n"; } } Output -
Is it considered bad practice to pass SQL script?
Psycho replied to NotionCommotion's topic in PHP Coding Help
I don't see a specific problem with passing the string value in that example. But, as it is written, there are two public methods that take a value parameter and both call the protected method to prepare the query and apply the value when executing. Personally, I don't like that approach because the protected function will only work if there is one, and only one, value to be applied to the query. At the very least, I would have the public methods pass the value (or values) as an array. That way, the otherMethod() function will work with queries with one or multiple values. -
Again, not enough information to make that assertion. The data needed for the parent could be vastly different than the children.
-
I agree with you in theory. However, without knowing the purpose of this application it is impossible to know if the relationship needs to go deeper than just the parent-child relationship. It could be an application where the user (parent) enters their data and their children's records. So, a person's child would create their own account for adding their children's records. However, I'm guessing this is for a class assignment. If so, I would hope the instructor is actually having them use two tables with the express intent of then adding more 'complexity' in order to illustrate the need for a single table. With programming I think it is better to let students make these types of mistakes and then show them the proper way to do it. Otherwise, they never really appreciate why they should be doing it that way.
-
Just a side note. Using GLOBAL is a bad practice. In this case, it is not even needed. A function should return a value. So, the combineXML() function should look something like this function combineXML($file) { $xml = simplexml_load_file($file); $fileXML = ''; foreach($xml as $element) { $fileXML .= $element->asXML(); } return $fileXML; } Then, in the code cyberRobot posted, change this $xmlstr .= '<prop_detail>'; combineXML($file); $xmlstr .= '</prop_detail>'; To this: $xmlstr .= '<prop_detail>'; $xmlstr .= combineXML($file); $xmlstr .= '</prop_detail>';
-
Forum rule #10 My assumption is that the accounts cannot be deleted as they are tied to forum posts/replies. I would suggest changing your account information as you see fit - such as changing the email address to some random value.
-
To answer your question: you would need to write VBA code and create a Macro in Excel. Here is a forum post of a similar question with some answers provided. http://stackoverflow.com/questions/158633/how-can-i-send-an-http-post-request-to-a-server-from-excel-using-vba
-
Moving this topic since it is not a PHP question. The question is about using Excel to POST data to a URL. Moving to the "Other Libraries and Frameworks" forum - didn't see anything more appropriate.
-
Using several of the recommendations above and some of my ideas on improving <?php $responseMessage = ''; if(isset($_POST['date']) ) { //Get list of ALL submitted dates with valid value $insertValues = array(); foreach($_POST['date'] as $date => $value) { if($value=='A' or $value=='B') { $insertValues[] = "('{$date}', '{$value}')"; } } //Run a a single query to inset all submitted values // *** The query should be a prepared statement to guard against SQL injection $sql = "INSERT INTO weeks (Date, Week) VALUES " . implode(',', $insertValues); if (mysqli_query($link, $sql)) { $responseMessage = "New record created successfully"; } else { // *** For debugging only. Should not display actual errors to user $responseMessage = "SQL: " . $sql . "<br>Error: " . mysqli_error($link); } } // *** Should run query to get already saved values from the database // *** and use those values in the loop below to set any already saved values //Create the form fields for each date $formFields = ''; $weeksOut = 52; for($weekNo=1; $weekNo<=$weeksOut; $weekNo++) { $date = date("Y-m-d", strtotime('Last Monday +'.$weekNo.' week')); $formFields .= "<p>What is this week?: {$date}\n"; $formFields .= "<input type='radio' name='date[{$date}]' value='A'>A</input>\n"; $formFields .= "<input type='radio' name='date[{$date}]' value='B'>B</input></p>\n"; } ?> <html> <body> <?php echo $responseMessage; ?> <br> <form action="test.php" method="post"> <?php echo $formFields; ?> <button type="submit">Submit</button> </form> </body> </html>
-
Is a single JSON MySQL retrieval faster than individual rows?
Psycho replied to DeX's topic in MySQL Help
It won't. At least not in any perceptible way. -
There's no way to help you with what you have posted. All you have provided is some code to create the form. There is nothing in that code that has logic to show/hide anything that I can see. I have no idea if you have PHP or JavaScript code to do the show/hide functionality.
-
They are not 'sub-functions', they are methods within a class. And the variables defined for the class (such as $id) are properties. One of the benefits/reasons for having properties is so that you do not need to pass them between methods because they can be directly accessed via $this. And, passing $this from one method to another could only cause problems that I can see. So, remove $id from the parameter list for the updateValue() method and reference it via $this->id. But, if you have any reason to call updateValue() and pass arbitrary id values, then you could make it an optional parameter. If no value passed used $this->id, else use the passed value.
-
That would be a fun project. @OP: One easy solution would be to make the width of the background color slightly larger than the width returned from imagettfbbox() and "center" the text within it. Some values would still be slightly off, but with the slightly larger background would make it unnoticeable.
-
There's another solution as well. Not that it will solve your current problem since the above solution is valid. As the other two stated, that problem is likely in your data. Anyway, the other solution is to use the IN operator. This is useful when attempting to find matching values against the same field WHERE `access` IN (1, 2, 3) That assumes the field has actual numbers and not text stored as number. If the latter, then the values should be included in quotes as you've been doing. WHERE `access` IN ('1', '2', '3') Or, if the field is numbers (as it should be) and the values represent increasing (or decreasing) levels of access, it would seem the values would always be 1, 2, 3, . . . and increasing value. In that case you could use a simple less than (or less than and equal) operator WHERE `access` <= 3
-
First, STOP using the mysql_ functions. They are no longer supported in current versions of PHP. Instead use the mysqli_ functions or, better yet, PDO for database operations. Second, learn how to use prepared statements instead of trying to manipulate the data before running the query using things such as mysql_real_escape_string(). Prepared statements will prevent SQL Injection if done properly.
-
looping results from query and limit amount per row
Psycho replied to jacko_162's topic in PHP Coding Help
This is unnecessary // complete a partial row $count = count($chunk); if($count < $items_per_row) { echo str_repeat("<td> </td>\n", $items_per_row - $count); } All you need is this // complete a partial row echo str_repeat("<td> </td>\n", $items_per_row - count($chunk)); If the chunk contains 5 items (or the same number as $items_per_row, the multiplier will be 0 and no empty cells will be output. -
I'm not sure, but you are using the SELECT statement to populate a temporary table. I don't think it is going to return the data. I would think you would then need to run a second query against that temporary table to retrieve the data.
-
How/What is the correct way to create a function for MS SQL Queries.
Psycho replied to kat35601's topic in PHP Coding Help
Yes, you do have a target. You are creating it with a more complicated logic using datediff() and getdate(). I just gave a high level example, if you wanted records for the current month it would look like WHERE DATEPART(yyyy, tdate) = DATEPART(yyyy, getdate()) AND DATEPART(mm, tdate) = DATEPART(mm, getdate()) But, per your original request you asked So, I provided how I would do it. You never asked about getting totals for the periods. If you want totals for particular periods you would use GROUP BY using similar logic to what I provided. As stated before, the ISO_WEEK will work if your weeks align with the start/end of ISO_WEEK. Else, you are going to have to create some logic to appropriately group the weeks as you want them. -
How/What is the correct way to create a function for MS SQL Queries.
Psycho replied to kat35601's topic in PHP Coding Help
For records in a particular month, I would use something like YEAR(datefield) = targetYear AND MONTH(datefield) = targetMonth For records within a particular week, you can do something similar if your weeks are aligned with ISO_WEEKS -
When using UNION, the queries MUST have the same number of fields and the same field types (in the same order). The two queries you are trying to UNION fail just from the first fields. The first field in the first query is a team name, but the first field in the second query is a count. And, from what I deduce you should not be using UNION. It is used to combine records from multiple queries where each record is independent. I think you mean to use a JOIN. But, it appears you are trying to calculate data and store in another table. That is a bad practice. Just get the calculated data from the source tables when you need the data.
-
What I would suggest is to go through code a line at a time. For each line see what function(s) are used and/or the data. Look up the functions in the manual and understand what is happening on that line of code. Then go to the next line. Sometimes you will have to "go back" to previous code to understand the current line you are on. I think it really helps to learn logic that way (assuming the code has good logic). However, if you have someone that has a line of code that does 10 different things, it can be hard to decipher into something meaningful