Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation since 04/20/2022 in all areas

  1. the error response you are getting has nothing directly to do with checkbox form data. you are getting an error with either the sql query statement or the execution of the sql query, but because the error handling does not display/log the raw error information, you don't have any idea why it is failing. you need to find what the problem is and correct it. just trying a bunch of different things results in a lot of wasted time, with no actual learning occurring. the current code is using the PDO extension, a prepared query with external, unknown, dynamic values, is supplying an array of the inputs to the execute() call, and is using exceptions for errors. this is the best choice for performing database operations and you should continue to use these practices. some changes for the current code - when you make the connection, set emulated prepared queries to false, i.e. you want to run real prepared queries. set the default fetch mode to assoc, so that you don't need to specify it in each fetch statement. i would also name the connection variable $pdo, so that anyone looking at the code can tell what database extension it is using. because you are using exceptions for errors, there's no point in having discrete conditional error handling logic in your code, because it will never get executed upon an error. so, simply remove the if($result)... logic. if duplicate data is not an application error for this insert (and also for an update) query, you would NOT have any exception try/catch code at all, and simply let php catch the exception, where php will use its error related setting to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors.) for what you are currently experimenting with, this is probably the case. if you remove the try/catch code you have now, and assuming that your php is configuration to report and display all php errors, you will now start seeing database statement errors too. if this insert (and also for an update) query could result in duplicate data values and this is an error for your application, you would catch the exception in your code, test if the error number is for a duplicate index error, and setup a message for the user telling them what was wrong with the data they submitted. if the error number is for anything else, re-throw the exception and let php handle it. note: $_POST is always set, even if it is empty, so the current logic testing if(isset($_POST)){ will always true. also, don't copy variables to other variables for nothing, this is just a waste of your time typing all of that. your post method form processing code and form code should - detect if a post method form was submitted. keep the form data as an array variable, then operate on elements in this array variable throughout the rest of the code. trim all the input data at once. by keeping the data in an array variable, you can do this with one single line of code. validate all the inputs, storing validation errors in an array, using the field name as the array index. after the end of all the validation code, if the array holding the errors is empty, use the submitted form data. after using the submitted form date (which could cause user/validation errors in itself), if there are no errors, execute a redirect to the exact same url of the current page to cause a get request for that page. if you want to display a one-time success message, store it in a session variable, then test, display, and clear that session variable at the appropriate location in the html document. to allow the user to go to a different page, provide navigation links. if there are errors at step #6, the code would continue on to display the html document, where you would test and display the contents of the array holding the errors, then display the form, populating the form field values with any existing data. apply htmlentities to any values you output on a web page to help prevent cross site scripting.
    1 point
  2. the php mail function is NOT a mail server. it provides a way for php to interface with the sending mail server at your web hosting, typically though a sendmail binary program on the host system. on your web hosting, there is a mail server that is being used as the sending mail server. since it is unlikely that you are using google cloud web hosting (you probably would have mentioned this) and/or a gmail mail server (this requires smtp authentication, which the php mail() function does not support), the From: mail domain MUST correspond to the domain of your web hosting. you cannot just makeup and put in an @gmail.com email address.
    1 point
  3. Let's see if we can clarify some things about this project. From reading your initial post, and looking at your link, here is my interpretation of what you are asking: It appears that what you want is a shopping cart You have arrived at an html form While this may have started with excel, that is not relevant to what you eventually arrived at, which again is the simple html form and associated javascript Now that you have this form and javascript you want to expand its functionality The drop down lists of the form should be sourced from server side data rather than being static data in the html While not clear, you may desire some interactivity in the form based upon selections in the drop downs. You desire to have server-side processing of an order on your site which includes integration of a payment gateway If these requirements are correct, then my initial response to you is that this is a non-trivial set of requirements. It most certainly can be accomplished using HTML, Javascript and PHP, but regardless of the tech stack involved, this is a significant project. As a point of clarification, HTTP protocol is based on request & response. The client makes a request for a resource (URL). This request can be of a few different types. In the case of a form like the one you mocked up, that request is typically going to be a POST. When the server receives a request, it then returns a response. Typically that response is the HTML that is then assembled by the client/browser. At that point, there is no connection between the client and server. The connection to the server is closed, and interaction with the html page is happening on the client's browser. All javascript in the page is running inside the browser. These basics limit the level of interactivity possible in a web application. "Ajax" was an extension to the javascript standard intended to allow javascript in a fully rendered html page, to be able to make additional requests, without the client having to do another full HTTP request, which in turn would require the browser to have to reinterpret and rebuild the page. Ajax isn't a separate language -- it's just an extension to the built in javascript api that the browser provides. It allows a rendered html page to include javascript code that can make network requests which typically will be for the purpose of getting data from the server. It is nothing more nor less than that. It's also important to understand that traditional pre-ajax web applications were still capable of doing everything that ajax does -- only in a manner where all interaction required a normal HTTP request/response cycle. You can have a form, and when the user changes a drop down value, the form can be submitted and the desired HTML/javascript/css source can be returned based on the modifications made to the form. It's just not as efficient or user friendly as a page that incorporates ajax, and additional javascript code to manipulate the browser's DOM using data that may have been returned from the ajax call(s). Putting the complexity question aside, it would help to break things down into individual parts. For each drop down, what is the source of the data? Is it coming from a database? Then you need a PHP script that returns the drop down data and returns it, preferably in json format. You then need javascript code that can take the json data and recompute the relevant DOM object (in this example, the drop down). You also clearly will need a serverside script that accepts the submitted form, and if everything checks out, saves the order, and then makes the payment gateway request for payment processing. The status of that payment gateway request from the PHP script to the payment gateway then needs to be saved in the order, and a response returned to the client. None of this is actually stated in your question, so I'm extrapolating additional stages and steps that I know exist for any shopping cart/ecommerce application. Again this is a big project, with a lot of complexity that requires a solid foundational understanding of html/javascript with ajax/json/http protocol/PHP network client request. Phpfreaks exists to help people of any level work towards their goals, and aims to help advise and educate. I hope this might give you a better idea of what you will need to accomplish from a technical standpoint, and that this is not a simple project for which a simple solution exists. Because ecommerce is non-trivial, often the best way to get to a solution, is to utilize a commerce platform like Shopify, or a CMS like wordpress with an extension like woocommerce.
    1 point
  4. But if you validate and then redirect, then the page at the end of that redirection must repeat the validation, otherwise someone could send data to it directly, bypassing the validation. The basic pattern for my pages is something like this: if ( form data submitted ) { Validate form data - populate variables and error messages ; if ( form data valid ) perform any required Action ; } Display Form, with values and/or error messages and/or results from the Action. Any "validation" that you do in Javascript on the client is for the Users' convenience only - you must not rely upon it because nothing that comes from the client can be trusted. (For example, do you validate the form value submitted from the HTML "select" list that you sent? You probably should ...) Regards, Phill W.
    1 point
  5. I can try to help you to write the code (I'm not doing your assignment for you). Do you have regular bookable timeslots? What is the structure of "tblappointment"? (and other tables you are using?)
    1 point
  6. If the slots that can be booked are all regular intervals, put a UNIQUE constraint on (specialist, time) so, say, "Anthony, 10:00" can be entered once only. However if "Anthony, 10:01" were also valid then it gets more complicated.
    1 point
  7. I thought you would have realised in your initial code that you had the total_receivables from your array_sum() function call. If in doubt what a function is doing, there is always the manual Getting total expenses would be very similar. Subtracting one from the other is an easy bit.
    1 point
  8. Possibly. How can I know? Syntax is OK.
    1 point
  9. You'll find that serializing data it not used very much these days, largely abandoned in favour of JSON data $data = [ 'count' => 1, 'total' => 5, 'average' => 5 ]; echo "Serialized: " . serialize($data); echo "JSON: " . json_encode($data);; gives Serialized: a:3:{s:5:"count";i:1;s:5:"total";i:5;s:7:"average";i:5;} JSON: {"count":1,"total":5,"average":5}
    1 point
  10. this is nonsense code. it contains lines of code that do nothing. the author didn't even know that a header() statement doesn't stop php code execution.
    1 point
  11. all that did was stop the code from being executed, since the form(s) are post method forms and the submitted data will be in $_POST, not $_GET. if you haven't studied (class, book, online tutorial) any fundamentals of php programing, you won't be able to debug any problems in code, nor will you be able to understand and make use of any replies in help forums. what learning resources are you using to come up with this code?
    1 point
  12. People here LIKE TO READ actual code, not look at hard to makeout pictures. Take the hint. And try and limit the code to what you think is the problem area. We don't need to see all your html or all of your css or even your js if it doesn't pertain.
    1 point
  13. Thanks for the pictures - I'll hang them on my lavatory wall. It's all they are useful for.
    1 point
  14. If you couldn't be bothered to study, even though it was to your advantage, why should I be bothered to help?
    1 point
  15. I assume this is mysqli because insofar as I recall PDO doesn't have a `bind_result` method. Assuming I'm not off-base there, I'd recommend taking the plunge and switching to PDO if it's a possibility in your project - it's a much more fluent and easier to understand interface.
    1 point
  16. If it's coming from the link's querystring you should be using $_GET['did_ivr_disable']
    1 point
  17. Does this do it? Total_qty = array_sum($cart['QUANTITY']);
    1 point
  18. Use the <> button in the toolbar when posting code. I have done it for you - this time.
    1 point
  19. Yea, It's briefly noted in the documentation for the Iterator class. I first noticed this behavior when working with FilterIterator. Seems kind of strange and dumb to me, but oh well.
    1 point
  20. It does explain them. While this is not in the manual, Laravel Middleware is an implementation of the Chain or Responsibility OOP Design Pattern. It is essentially a linked list of classes, each with a handle() method, and the HTTP request gets passed along and the handle() method is run. Once the handle method is complete, the next() method is called which will run the next handler. All the handlers are run, unless one of them interrupts the process rather than calling it's next() method. From the manual: So all the middleware handler classes in the $middleware array are run for every HTTP Request. If you have your own custom middleware you would also want run for every request, the manual page you posted shows you how you write one, which again just has to follow the same rules as any of the other middleware. Obviously there are other types of handlers that should only be applied to certain applications. For example, a Web application will likely have very different requirements than a REST api that is used by a Mobile application has. One very simple example of this difference is that a Web application will probably use cookies, whereas a mobile application will probably use tokens and assume its own local storage and configuration. Another example would be a web app implemented CSRF protection for web forms, where a mobile app won't have that, because it's not utilizing HTML client forms. So this is where Laravel groups up a set of associated Middleware handlers generally applicable to one application type. As you can see the web middleware group comes with the list of handlers you posted. Again you can add and subtract and customize this. This is fairly self explanatory I think. You are just given a convenient tag name for a handler to be used with specific routes to handle things like authentication and permissions. When defining a route, you are able to specify the list of middleware keys for the specific middleware handlers you need to have processed when that route is accessed. There are a few different ways to set up your routes. So there are some additional middleware options that might be of value, relative to how you defined your routes, especially if you are adding routes to a middleware group.
    1 point
  21. you have actually been give the answer - don't put function definitions inside of other function definitions.
    1 point
  22. some other possibilities - it's conditionally defined - inside another function definition that hasn't been called yet or inside some conditional logic that didn't execute it's not within php tags at all it's using a short opening tag that's not enabled it's within a comment the OP needs to post the complete contents (including the opening php tag in the file) of redirect.php in order to either confirm or eliminate the various possibilities as the cause.
    1 point
  23. You should find another tutorial: the code they've convinced you to use is... well, it's silly. It pointlessly uses encryption for something that doesn't need to use encryption. If you want a remember me cookie then all you need is to store a long random token in your database and associate it with the user - preferably in one-to-many form so the user can have multiple tokens for multiple devices. Store it in the browser with the Secure and HttpOnly flags. Then, every time the token is used to log someone in, you generate a new token and replace the old one.
    1 point
  24. I looked at your code, but I don't see a problem. What are the full contents of redirect.php? Is it possible you are including the wrong redirect.php? There could also be some sort of syntax issue. I'm not sure what is going on. Are you possibly using Opcache? There are times that Opcache gets a file stuck in cache, and it doesn't read changes. If you are using opcache, you should either turn it off for development purposes, or learn how to clear the cache. I've seen that cause major confusion plenty of times, where people had code that should work, but doesn't and they can't figure out why. This has nothing to do with your problem but since I looked at your code, I figured I'd refactor it for you. function loginSuccess($username, $password) { global $cn; $sql = "SELECT COUNT(*) as countOf FROM admin WHERE username=:username AND password=:password"; $stmt = $cn->prepare($sql); $stmt->bindValue(":username", $username); $stmt->bindValue(":password", $password); $stmt->execute(); $countOf = $stmt->fetchColumn(); return ($countOf > 0); } I fixed your spelling. The word is spelled "success". Use PHP community standards for naming your functions, methods and variables. The standard is to use camelcase. See https://www.php-fig.org/psr/psr-12/ for this and more standards you should conform your code to Writing code to these standards has many benefits including the avoidance of bugs where you mix up case, as php variables are case sensitive, better readability, and support for tools that can be integrated into the best PHP code editors to maintain standards and reformat your code It's also easier for others to read Don't use underscores, except in special circumstances. Use camelCase to differentiate words. Some people will use an _ as the first character of a name to indicate private/protected variables in OOP, but I'd avoid them entirely. Underscores are used to name certain special PHP method names, like __construct for example. Your query does not need to return anything from the database other than a count of rows that match your criteria. Just use COUNT(*) for that, and this will always return a result that will either be 0 or something > 0 Have your function return a boolean, so it's clear that it's true/false. Ideally you would use return ($countOf == 1) however, I don't know if you guarantee uniqueness for usernames in your database. You should do that, with a Unique constraint on username, as this would insure that it's impossible to insert more than one row in your admin table with the same username. Not preventing the insertion of multiple admin rows with the same username can lead to terrible bugs in your system. If you do have a unique constraint on username in your admin table, then change the code to return ($countOf == 1). This is also semantics, but the name of your function "loginSuccess" isn't a great name. The function, despite your name does not indicate "login success". All it indicates is that you verified the existence of a row. The concept of a "login" is more complicated and typically involves setting up some session variables and regenerating the session, if you are using sessions generically (for unauthenticated users). A better name for this function would be: function canAuthenticate() or isAuthenticated().
    1 point
  25. Can you show us ONE entire block of code that includes the function and the code that calls the function?
    1 point
  26. Why build the json data manually??? $json_data = json_encode($result); AS for the rest of the code, without knowing your db structure and gantt api input requirements there is no way I can suggest a better route.
    1 point
  27. the most likely cause are the short opening <? tags, on lines 1 and 15 in the posted code and everywhere else they are used, being disabled. you can attempt to make this 'work' by enabling them in your php.ini the ideal way to fix this would be to do a search/replace to change all the <? tags, which must be followed by at least one white-space character (which isn't shown on line 15, but then again you didn't follow my instructions for posting the code), but not the <?= tags, into full <?php tags.
    1 point
  28. Don't try to make the string yourself - javascript isn't actually expecting a string; it wants an encoded array or object. Given that, instead of concatenating a string and then finding a way to remove the final comma in order to return said string (let alone escaping and other things you'd need to deal with), make your life easier by building a simple PHP array in your while loop and then json_encode that array when you echo it. In javascript you can then JSON.parse() the returned value and use it.
    1 point
  29. @gizmola and @mac_gyver Thanks a ton for the tips and info. I'm new to PHP and slowly figuring it out. It means a lot when people like yourselves go out of your way to help. Thanks again!
    1 point
  30. The PHP DateTime::diff() method provides a very convenient way of getting the days, hours, minutes and seconds components of a time difference so this script uses an AJAX request on loading to get the time remaining. From then on, it calls a javascript function every second to reduce the time displayed by one second. This greatly reduces network traffic and gives a consistent update performance. Repeatedly using AJAX could sometimes result in delays preventing a regular countdown interval. <?php ################################################################################################################## # # # THIS SECTION HANDLES THE AJAX REQUEST AND EXITS TO SEND RESPONSE (Days,hrs, mins, secs remaining) # # # if (isset($_GET['ajax'])) { if ($_GET['ajax'] == 'countdown') { $remain = ['days' => 0, 'hrs' => 0, 'mins' => 0, 'secs' => 0]; $dt1 = new DateTime( $_GET['target'] ); $dt2 = new DateTime('now'); if ($dt1 > $dt2) { $diff = $dt1->diff($dt2); $remain['days'] = $diff->days; $remain['hrs'] = $diff->h; $remain['mins'] = $diff->i; $remain['secs'] = $diff->s; } exit(json_encode($remain)); } } # # ################################################################################################################### $target = '2022-04-30 23:59:59'; // SET OR GET TARGET TIME HERE $targ = new DateTime($target); $target_time = $targ->format('g:ia'); $target_date = $targ->format('F jS Y'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Countdown</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type='text/javascript'> var inter $().ready( function() { get_time_remaining() // call AJAX request to get remaining time inter = setInterval(countdown, 1000) // set timer to call "countdown()" function every second }) function countdown() { let s = parseInt($("#secs").html()) // get current time remaining let m = parseInt($("#mins").html()) let h = parseInt($("#hrs").html()) let d = parseInt($("#days").html()) if (d==0 && h==0 && m==0 && s==0) { // exit when target time is reached clearInterval(inter) $(".remain").css("background-color", "red") return } s--; // reduce display by 1 second if (s < 0) { s = 59; m-- } if (m < 0) { m = 59 h-- } if (h < 0) { h = 23 d-- } if (d < 0) { d = 0 } $("#days").html(d) // redisplay new values $("#hrs").html(h) $("#mins").html(m) $("#secs").html(s) } function get_time_remaining() { $.get( // make AJAX request "", {"ajax":"countdown", "target":$("#target").val()}, function(resp) { // put response values in display fields $("#days").html( resp.days ) $("#hrs").html( resp.hrs ) $("#mins").html( resp.mins ) $("#secs").html( resp.secs ) }, "JSON" ) } </script> <style type='text/css'> body { font-family: verdana, sans-serif; font-size: 11pt; } header { padding: 8px; text-align: center; width: 600px; margin: 20px auto; background-color: #F0F0F0; } .target { color: #006EFC; font-size: 16pt; } table { border-collapse: collapse; width: 400px; margin: 0 auto; } td, th { padding: 8px; text-align: center; width: 25%; } .remain { font-size: 24pt; color: white; background-color: black; border: 1px solid white; } </style> </head> <body> <header> <p>Countdown to</p> <p class='target'><?=$target_time?> on <?=$target_date?> </p> <!-- make target time available to javascript --> <input type='hidden' id='target' value='<?=$target?>' > <table border='0'> <tr><th>Days</th><th>Hours</th><th>Mins</th><th>Secs</th></tr> <tr> <td class='remain' id='days'>0</td> <td class='remain' id='hrs'>0</td> <td class='remain' id='mins'>0</td> <td class='remain' id='secs'>0</td> </tr> </table> </header> </body> </html>
    1 point
  31. you always need error handling for statements that can fail. you should also insure that you have php's error_reporting set to E_ALL and display_errors set to ON, in the php.ini on your development system, so that php will help you by reporting and displaying all the errors it detects. if you run this code on a live/public server, you would instead set display_errors to OFF and set log_errors to ON. the mail() function returns either a true or a false value. for a false value, php will either display or log the actual error information, so that you will have an indication of the call failing. however, in your code for a false value, you should log your own information consisting of the datetime, the php error that occurred, and the parameter values that were supplied to the mail() call. this will let you debug problems that are occurring due to things like email addresses that cause an error. for a true value, because email can be unreliable, you should actually log or insert rows in a database table with the same information, so that you can check if you are receiving all the emails that are being sent. once you do the above you will probably get errors about an invalid mail header, a missing From: header, and/or errors about relaying restrictions. the mail headers must contain a From: email address. the syntax is From: email address \r\n this email address is NOT the address that was entered in your form. these emails are not being sent from the user's email address (except perhaps during testing that you may have done using an email address that does correspond to your web hosting.) they are being sent from the mail server at your web hosting. the email address in the From: header must correspond to your web hosting. you can put the entered email address into a Reply-to: mail header. the are a number of issues with the posted code. the most immediate problems are - the code is not indented properly, so you cannot see what exactly it is or is not doing. the current code will attempt to sent the email, even if the entered email address is not valid. you should actually store the user/validation errors in an array, using the field name as the array index. then, after the end of all the validation logic, if the array is empty, use the submitted data. this will simplify all the nested conditional logic. to display the errors, at the appropriate location in the html document, you would test if the array is not empty, then either loop over or implode the contents of the array to display the error messages. the $body variable is being reassigned on each pass through the foreach(){} loop. this leaves you with only the last checkbox message as part of the body. since there could be any number of checkbox messages, i recommend that you add each one to an array, inside of the loop, then after the end of the loop, implode them with whatever markup you want between them, then append this to the end of the main message body. don't write out code for each possible value. if you had 10 checkboxes, would writing out all that conditional logic 10X make sense? you should use a data-driven design, where you have a data structure (array or database table) that holds the definition of the data. for the checkboxes, you would have an entry in the defining array for each checkbox. the main array index would be the values (1,2,...) each entry in the main array would be an array with elements for the label, and the mail body text. you would use this defining data structure when dynamically building the checkbox markup, when validating the submitted checkbox values, and when adding the text to the mail body.
    1 point
  32. I'd define it something like this CREATE TABLE `comments` ( `post_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, `datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `email` varchar(50) DEFAULT NULL, `comments` text, `approvedby` varchar(50) DEFAULT NULL, `status` tinyint(4) DEFAULT NULL, PRIMARY KEY (`post_id`) ) then, as stated earlier, datetime and post_id are generated automatically and can be excluded from the INSERT. As @ginerjm said, don't use varchar for dates. They should be DATE, DATETIME or TIMESTAMP and the format should be yyyy-mm-dd. Store them for functionality, not prettiness. Format them as required on output or in the query.
    1 point
  33. You don't want to create a field called 'datetime' as varchar. It s/b a DateTime type. $sql = "INSERT INTO comments (name, datetime, email, comments, approvedby, status, post_id) VALUES(:name, :email, :datetime, :comments, 'Pending', 'OFF', :post_id)"; Looking at your query statement do you see that you have mis-aligned fieldnames and values? You're trying to load an email into a datetime field and the reverse PS - I recommend switching to the array method of assigning the values instead of the tedious bind function as in this: $sql = "INSERT INTO comments(name,datetime,email,comments,approvedby,status,post_id)"; $sql .= "VALUES(:name,:email,:datetime,:comments,'Pending','OFF',:post_id)"; $parms = array( ':name'=>$name, ':datetime'=>$dt, ':email'=>$email, 'comments'=>$comments, ':post_id'=>$postid); if($sucess = $stmt->execute($parms)) {
    1 point
  34. If I were a customer, I wouldn't want to remove an item and then end up paying for it because the programmer couldn't be bothered to recalculate.
    0 points
  35. There was no such thing as computing or software courses when I left school for uni. Back in those days IBM were predicting that, one day, every country would own a computer.
    0 points
This leaderboard is set to New York/GMT-04:00
×
×
  • 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.