-
Posts
5,450 -
Joined
-
Days Won
175
Everything posted by mac_gyver
-
if you are setting custom session and session-cookie settings, you must set the same settings before EVERY session_start() statement. otherwise, you are creating/resuming different sessions.
-
^^^ yes, that's correct. the session_start() statement updates the last accessed time of the session data file, that prevents the garbage collection from deleting that particular session data file, when garbage collection actually runs (it runs randomly based on the two probability values.) even if the session data file is older than the session.gc_maxlifetime value, if it hasn't been deleted yet by the garbage collection, if you execute a session_start() it will update the last accessed time of the session data file and the session will still exist (the garbage collection probability calculation runs as part of the session_start(), but after the session data file has been read.) again, what sort of symptom or error are you getting that leads you to believe that the session is not refreshed. and what about the php error settings i asked/suggested and are there are any errors occurring at the session_start() statement?
-
what sort of symptom or error are you getting that leads you to believe that the last accessed time of the session data isn't being updated. also, do you have php's error_reporting/display_errors/log_errors turned full on so that any session_start() error with the refreshSession.php file would be displayed/logged?
-
Select rows and order by a text field as if it's numeric
mac_gyver replied to Strahan's topic in MySQL Help
if you use episode * 1 in your ORDER BY term, it should treat the values as numbers. also, CAST(episode as UNSIGNED) should work as well. -
there's a ton of curl examples to be found by searching the web. the following basic example should work for you (provided that the curl extension is enabled) - $url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=CB13HR&destinations=CB23JX&mode=driving&language=en-EN&sensor=false"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = json_decode(curl_exec($ch), true); echo '<pre>'; print_r($result);
- 16 replies
-
- php
- sort array
-
(and 1 more)
Tagged with:
-
further to my reply above, if your previous code did have a $result['rows'] in the json decoded data, but it doesn't now, your file_get_contents() is likely failing. you should never use the @ error suppressor in any code. do you get any php errors from the code after you remove the @ in front of the file_get_contents() statement?
- 16 replies
-
- php
- sort array
-
(and 1 more)
Tagged with:
-
edit: there is no $result['rows'] in your json decoded data. i recommend using the code/method you were given in this thread.
- 16 replies
-
- php
- sort array
-
(and 1 more)
Tagged with:
-
PHP Email Sends to Recipient Multiple Times
mac_gyver replied to dachshund's topic in PHP Coding Help
if you used that exact code and only got one set of data in the log file, but two emails, the problem isn't in the code you are showing us in this thread. you either have some other code involved, that you haven't shown us, such as javascript/ajax in your form that's submitting to some other php code that also sends an email or an included file on the php side that is also contains a mail() statement, you could even have a header() redirect in the php code that you don't have an exit; statement after and some mail() code later in the file that's sending the second email, or the problem is something to do with your mail server, such as an auto-reply, email forwarding, or some logging function that's causing a duplicate to be sent to the same email address that you are using in the php code. are the two emails completely identical? for the line you showed in reply #7, is the blocked out email address(s) in it the same or different from what you are using in the php code? we get that you don't want to show actual information, but tell us specifically, for each of those two blocked out pieces, how they did or did not relate to the to: and from: addresses that are being used in the php code. -
the following is from the sample code i posted - if(empty($errors)){ // if no errors at this point, continue with validation // all your form field validation code would go here, using elements in the $data array (a trimmed copy of the $_POST data) } the only thing you should be adding is 'your form field validation code". this is the code that's testing if the submitted form data is empty or not, if it has the correct format, and any value range checking. all the lines of code you have shown in post #10, beyond the original array_map(), and the first half of post #12 are not needed. the code you posted in the second half of post #12 is how you would reference the now trimmed data that's in the $data variable. my suggestion that you can define the information about the form fields in an array and then loop over this defining array to build the form and process the form data is going to be way over your head at this point. just change your validation logic to use elements in the $data array - $data['name'], $data['description'], ...
-
i'm pretty sure that all of your form field names are not arrays (though the radio buttons should be) so, just consider $data = array_map('trim',$_POST); for now. that line of code assigns the result of the array_map() function to the $data variable. the array_map() function applies the php trim() function to all elements of the $_POST array, which is an array consisting of the submitted form data. $data will be a copy of the submitted form data, that's been trimmed. to reference those trimmed values in your code, you would use things like - $data['name']. ultimately, your code would dynamically reference the values in $data, rather than you writing out a bunch of lines of code for each of them. the point of operating on the data as an array, using php's array functions (array_map, foreach, ...), is so that you don't have to write out lines of code for each and every form field. if you have 20 form fields, the one line $data = array_map('trim',$_POST); trims all the values at once, rather than you witting out $some_variable = trim($_POST['some_filed']) 20 times. besides using $data as the source data for your validation logic and source data for the database queries, you would also use it to repopulate the form field values/radio button selections should you redisplay the form if any validation errors are detected.
-
htmlentities() would be used on the CONTENT being put into the html markup, that you want to be rendered literally as typed, and also making any javascript/css/html markup in the content, inert. if your $_GET['html']/$html IS the html markup for the page, no, you would not pass it through htmlentities(). i'm hoping that you have some security in place to prevent just anyone from submitting whatever they want to your code?
-
all text, textarea, password, hidden, select/option, and usually submit, form fields will be set if the form has been submitted. you would use an isset() statement to detect if a form has been submitted, like in your first thread on this site. note: zeros are considered to be empty(), so, someone entering a '0' will pass the empty() test, if the string length is what you are actually looking for, either test the value against an empty string '' or test the strlen() of the value. for your stated logic test - empty is okay or if not empty, three or more characters is okay. or conversely/complementary, the error is if not empty and less than three characters - $len = strlen($_POST['office']); // i'm going to assume that you have trimmed all the submitted data, so that spaces, tabs, and new-lines have been removed before/after any actual value if($len != 0 && $len < 3){ // error condition } another way to state this error condition would be if the length is greater than zero and less than 3 - if($len > 0 && $len < 3){ here's a hint that will simplify your error logic. use an array $errors (to initialize it - $errors = array(); ) and just set elements in the array for each error message ($errors[] ='"Office" field cannot contain less than three characters';). to test if there are any errors, just test if the array is empty(). if the array is empty, there are no errors. if it is not empty, there are errors. to display the error messages, just loop over the array or you can simply implode() it.
-
PHP Email Sends to Recipient Multiple Times
mac_gyver replied to dachshund's topic in PHP Coding Help
example code to log information about the request - $log_file = 'log.txt'; $date = new DateTime(); list(,$us) = explode('.',microtime(true)); // unfortunately the 'u' format specifier returns zero for me, so use microtime() to get the fractional seconds $dt = $date->format('Y-m-d H:i:s') . ".$us"; $log_this = "$dt\n"; $log_this .= "Usr: {$_SESSION['user_id']}\n"; $log_this .= "Rm: {$_SERVER['REQUEST_METHOD']}\n"; $log_this .= "Get: " . print_r($_GET,true); $log_this .= "Post: " . print_r($_POST,true); $log_this .= "Ip: {$_SERVER['REMOTE_ADDR']}\n\n"; file_put_contents($log_file, $log_this,FILE_APPEND); add any other debugging information you may need, such as the entire $_SESSION array, $_SERVER['HTTP_USER_AGENT'], ... -
PHP Email Sends to Recipient Multiple Times
mac_gyver replied to dachshund's topic in PHP Coding Help
sadly, browsers can request a page twice, for various reasons. you should log information each time the code runs (using file_put_contents() with the FILE_APPEND flag) so that you will know who (if you have a login system, log the user id), what (log the $_GET, $_POST, and $_SERVER['REQUEST_METHOD']), when (log the date, time, and microtime), and where (log the $_SERVER['REMOTE_ADDR']) information about the request. if the duplicate requests are close together (less than one second), they are likely being caused by the browser, in which case you don't have control over the cause of the problem. if only one of the duplicate requests contains the expected data, you will need to detect and use only the correct request. -
your post above shows - Posted Today, 08:02 AM for me. i also tried a different browser and the result is the same, 20 minutes behind. my profile settings for time zone is correct. i'll set my time zone to something else, then back to see if it corrects the issue. just more ipb crap. edit: changed my time zone to central and back to mountain and even tried the variations of the DST check-boxes, the hour changed as expected, but the minutes are behind. guessing something in the back-end settings under my username have 'adjusted' the timezone by 20 minutes.
-
the time being shown for posts and the Time Now: being shown at the bottom of pages is currently 19-20 minutes behind real time. in my time zone, it's currently 7:37 am. the time at the bottom of the page is 7:18 am.
-
if the error message, which you didn't post, states that there's output on line 1 of your file, but you don't have anything in your file before the <?php tag that's on line 1, your files have likely been saved by your programming editor with the BOM (Byte Order Mark) characters as part of the file. save you file without the BOM characters. there's usually a character encoding setting in your programming editor to do this.
-
here's the answers to your questions - my comment was about the mismatches between the queries, as i was coming across them in the code. the user id is defined in your users table (according to the sub-query you show in your original code). when you insert the row in the userProfile table, you need to have a column for the user_id, that gets the value from $_SESSION['user_id']. this is how the row in the userProfie table gets (should be) associated to the user's row in the users table (i didn't ask, but why two tables and not just have everything in the users table?) for the update query (you actually don't need to do this, you can just insert the extension of the image, since you WILL know the filename part from the id. but, if you do want to do the update, the id of the row just inserted in the userProfile table is the auto-increment id that was just assigned when that query ran. it's not the user_id. after you add a user_id column to the userProfile table, you could update the row using WHERE user_id = $_SESSION['user_id'], but that's not what you have now in the code. that referred to things like - if ((trim($contactNo)) == "") { in one place, and if(strlen(trim($contactNo)) != { a few lines later. in a DRY (Don't Repeat Yourself) mode, you wouldn't trim the value each place you test it and in fact since the value being inserted is not trimmed, you can end up with searches not being able to find stored values since the values can contain non-printing characters stored before/after them. trim (all) the values just once, so that every place you reference or use any of them will be the same value. there's no query statement that these things go with. you already executed the INSERT statement. they are some kind of copy/paste fail. the defining array would be for all the form fields, even the submit button and any hidden fields..., though you can limit it to just the fields that will be submitting data value that will get used by the code. it's better to have one page (though you can break it up and have the form processing code in an included file and the form in an included file. having one page means that the form and the form processing code is in the same program scope, so that redisplaying the values already entered in the form fields, should there be a validation error, is easy.
-
as far as a user that already has a profile landing on this page, the same code can be used to edit an existing profile, by retrieving the existing data (see the get method/display code @line 57 in the following.) example code that addresses or shows how it would look for the item#1 list - <?php session_start(); // access security - must be logged in to access this page if(!isset($_SESSION['user_id'])){ // either redirect to somewhere else or output a message header('location:your_login_page_for_example'); exit; // prevent the rest of the code from running } $addProfileForm = htmlentities($_SERVER['PHP_SELF']); // form action try{ // start of database dependent code require('Connections/database.php'); // assuming that both the get method/display code (form) and form processing need a database connection // post method form processing if ($_SERVER['REQUEST_METHOD'] == 'POST') { $errors = array(); // array to hold errors $data = array_map('trim',$_POST); // copy and trim all post data (if the form has any arrays, you need to use a function like array_walk_recursive() instead of array_map()) // if you have multiple-forms, you would conditionally run the correct section of form processing code by testing for a form field or a field value that uniquely identifies which form was submitted // addprofileform form processing code - //check if there is an existing record in DB $query = "SELECT COUNT(*) FROM userProfile WHERE user_id = {$_SESSION['user_id']}"; $stmt = $database->query($query); $number_of_rows = $stmt->fetchColumn(); if ($number_of_rows > 0) { $errors[] = "There is an existing record. You cannot insert another profile! Either update the old one, or delete to insert again."; } if(empty($errors)){ // if no errors at this point, continue with validation // all your form field validation code would go here, using elements in the $data array (a trimmed copy of the $_POST data) } // done with validation, if no errors, use the data - if(empty($errors)){ // your code to insert the data and move the uploaded file would go here... } // if no errors at this point, redirect to the exact same url of this page to prevent the browser from resubmitting the data by causing a get request for the page if(empty($errors)){ $host = $_SERVER['HTTP_HOST']; $uri = $_SERVER['REQUEST_URI']; header("Location: http://$host$uri"); exit; } // if there were errors in any of the above form processing code, continue on this page, displaying any errors, redisplay form, (re)populate the form fields with data... } // end of post method form processing // get method/display code (if any) - get/produce data that's needed to display the page // to edit existing data, if the $data array is empty at this point, retrieve any existing data from the database table } catch(PDOException $e){ // end of database dependent code, handle any errors $status = empty($query) ? 'Connection failed':" Query failed: $query"; // application message trigger_error("$status, Error: {$e->getMessage()}, File: {$e->getFile()}, Line: {$e->getLine()}"); // user message $errors[] = 'Sorry, this page is not working at this time.'; } // done with the database, destroy any pdostatment resource and close connection $stmt = null; $database = null; // the html document that uses any data from the above code starts here - ?>i'll get back to you on any questions you posted in your reply above, that don't seem to be addressed by this example code.
-
there are two main problems with the php code - 1) it has logic problems and code that isn't using the correct variables/values/database fields. 2) it is repetitive, resulting in a wall of code that makes it hard to even understand what the code is actually doing. your code tells us a story, the story of what you are trying to accomplish. if we cannot deduce from reading your code what it is actually doing, we cannot help with it. for item #1 - 1) the form processing code requires that the current visitor be logged in. therefore, the php code should not do anything unless there is a logged in visitor. the form page also requires that the current visitor be logged in and should not display the form unless there is a logged in visitor. 2) the php code that you posted is there to process the form submission. therefore, it should be inside of a conditional statement testing if the form was submitted. the code to test if a record already exists should be inside of the form processing conditional statement. 3) the userProfile table should use the user_id, not the username to associate the data in it with the user. this will simplify the SELECT query. then, just use $_SESSION['user_id'] to find if there is already a row in the userProfile table. 4) the SELECT query does not contain any bound input parameter, so, there no point in using a prepared query. 5) since there's no :id placeholder in the SELECT query, either the bindvalue() or the execute() statement are throwing errors for the current code. have you set the PDO error handling to use exceptions? you would be getting an uncaught exception to alert you to problems with the database statements (and you can then add try/catch logic in your code to handle database errors all in one place.) using exceptions will mean that you don't need to have conditional logic around every database statement (btw - the one place you are testing if a database statement failed, the first prepare(), the error message indicates that the there was an error executing the query. the prepare() statement doesn't execute the query, only prepares it.) 6) you are setting the $username variable to a 1. even if your SELECT query was using a bound input parameter/value correctly, it is an id and the variable you are using should be named to match what is being used and the value should come from the correct place, $_SESSION['user_id'], not a fixed value in your code. 7) your insert query for the userProfile table, doesn't contain a username field, so either your SELECT query is wrong or your INSERT query is wrong. the UPDATE query for the picName is also trying to use WHERE id = $_SESSION['user_id']. the id won't be the user's id. the id will actually be the $newID value. $statement->fetchColumn() fetches the first column from the SELECT query. however, your query is not selecting a value that indicates how many rows the query matched, so the logic using the fetchColumn() value doesn't mean anything. for this to work, you would need to SELECT COUNT(*) in the query. this is one of the reasons why your code is ignoring the select query. you are also testing if the value is > 1. the test should be if it is > 0 to find if there already a row in the database table. 9) you should trim() all the form data at once, so that you don't have to keep repeating statements in the code using the values. 10) you shouldn't exit; after any of the errors have been detected. you want the code to finish so that it can display the error messages. 11) $errors[] = ("some message!"); the () are not needed and in fact cause php to do extra work (evaluating an expression) and add clutter to the code. 12) you have some statements starting at line 610 that don't have a query they belong with. why are those lines in your code? 13) for the header() statements on lines 625 and 627, there is no $returnURL variable in the code, so there's no place for those redirects to go to and if you were redirecting to somewhere, how would you be able to print the errors that in the $errors array? 14) i didn't specifically look for any problems in the all the radio button code. see the next item - for item #2 (while this sounds like advanced programming, after you do it once, you can reuse it and it will simplify all the form/form-processing code that you write) - when you have code (including html for form fields) that gets repeated over and over, where the only thing that changes are the values that get operated on, you need to use a different programming technique. instead of writing out all the possible lines of code yourself, you need to let php dynamically process data or dynamically produce html content. when you have a form and form processing code, you can create an array that defines everything about the form fields and the validation you want for each field. then, to produce the form or validate the form data, you just loop over the array that defines everything to tell just one instance of the code what to do. some of the things you need to define in the array to produce the form are - 1) field type - text, radio, ... 2) field name (using the field name, which must be unique anyway, as the array index/key is helpful) 3) a display legend in the case of checkbox/radio buttons, you can use an array within the array to define the information for each set of checkbox/radio buttons. some of the things you need to define in the array to process the form data are validation rules, such as required - i.e. not empty, format functions/parameters - i.e. the filter_var() function, with the FILTER_VALIDATE_EMAIL parameter for the email field or the strlen function and a minimum/maximum value for fields that must meet a certain length, and error message text for each validation rule.
-
and as someone already mentioned, your code isn't using, nor does it need, the $variable = $row[index_name]; ...assignment statements. the time you spent putting those in, and now in changing them, isn't accomplishing anything, because your code isn't using those assigned variables and the only way you wouldn't know this is if you aren't looking at what you are doing. at this point, i don't think you are even looking at your code, just throwing random things against the wall to see if any of it sticks, and then dumping it on help forum(s) to get someone to put the code together the correct way for you. that's not you doing or learning programming. that's randomly trying things and almost never results in code that works.
-
Need a fast way to save a snapshot of MySQL table using PHP
mac_gyver replied to DeX's topic in MySQL Help
if your bom/cart is memory/session based, to display it with pricing, you would extract all the productId's (since these are array keys now, you can use array_keys() to do this all at once.) you would then implode the array of productId's to make a comma separated list that will get used in ONE database query, using an IN(...) term in the WHERE clause, to retrieve all the prices for those productId's, and store the result in an array, using the productId as the array key. as you loop over the contents of the bom/cart to display it, you would use the productId to get the price from the array you just made from the single query. if your bom/cart is database table based, you would just join the bom/cart with the pricing table, then just retrieve and display the results. -
if you mean the three dates near the end of your form, that you are using the same variable to populate, because there's only one date field being selected in your query? i would say the problem is because you are not selecting three different dates in your query.
-
your form code is not using the variables that you assigned values to in the loop. in fact, why are you looping to retrieve one row. if you eliminate the loop, just fetch the row from the database, and forget about all the assignment statements, your code will work, because the form code is using the $row[...] variables that the fetch statement would populate. if you are not getting any php errors, i seem to recall that php changed at some point so that accessing an associative array index on a null/false value doesn't throw undefined index error messages.
-
Need a fast way to save a snapshot of MySQL table using PHP
mac_gyver replied to DeX's topic in MySQL Help
no.