-
Posts
5,518 -
Joined
-
Days Won
187
Everything posted by mac_gyver
-
Submit $_POST with dynamically generated fields
mac_gyver replied to bambinou1980's topic in PHP Coding Help
your current code should be using an array for the form field name="...." attributes. this will allow you to process the submitted form data using php array functions. this is even more important if you plan on having an 'add' javascrpt/jquery button that dynamically adds more rows of data. using sequentially numbered field names will mean that you have to find and keep track of the number of fields in the javascript/jquery so that you can number the dynamic ones properly. by using an array for the field name, you don't need to do anything extra in the javascript/jquery for the dynamically added rows of data and all the form fields, the static ones and the dynamically added ones, will all be part of the same submitted data and will all be processed by the php code the same. you are also querying for all the product rows, then querying for all the rows again inside of the loop that's looping over the result from the first query. that is killing your database server with queries. even if your current method will result in a workable solution, once you query for all the rows in your database table, one time, just reuse that result set. the easiest and quickest way of reusing a result set multiple times would be to store all the rows in a php array or use a fetch_all statement if the database library you are using supports it. beyond those, i'm not sure why your code doesn't work, and since you have changed your concept multiple times, i'm not sure any of the previous helpers want to take the time to figure out what you are doing in this iteration of your design. -
yes. you would use ajax to search for the partially entered value. search the web for 'ajax typeahead' or 'ajax autocomplete' to find examples.
-
mysqli_real_escape_string alternative for decimal ?
mac_gyver replied to bambinou1980's topic in PHP Coding Help
if this is for your current project, where you have stated an admin is entering the order information, where you should be validating that the current visitor is logged in as an admin for both the form and the form processing code, why are you concerned about the security of the values (assuming that you are actually testing the current logged in user's permissions in the form processing code)? anyway, a way of avoiding the need to validate the prices at all, would be to submit and store just the price number that was selected - 1,2,3, not the actual price, which if you don't trust your admin with, shouldn't be passed through the form (someone could change 100.00 to 1.00 for their friends.) if on the other hand, you are only submitting the price number, the only tampering with the price could be to select the wrong one among the choices for that product. which begs the question, of what happened to your concept of having a customer type that determines the price the customer gets for each product? if you are accepting the actual price from external data, and just anyone can submit to your form processing code, and you don't care is someone supplies they own price (form data can be manipulated to be anything, not just what you output when you produced the form), you would want to treat the number as a decimal, not a float. casting/storing it as a float will introduce floating point conversion errors. also, using just is_numeric(), without other validation, will allow a hexadecimal number to be entered, which somewhere between php and mysql sadly has (unknown of this is still the case) converts to the encoded string and allows sql injection in the query statement. i would also recommend prepared queries to provide security against sql injection for your external data as it works regardless of the data type and the value that was submitted. -
passing array to PDO bindParam giving me error
mac_gyver replied to venkatpvc's topic in PHP Coding Help
the place-holders in prepared queries are for values only (numbers, string data, dates.) they cannot be used to supply identifiers (database, table, column names) or sql syntax. if you are getting any of the information being used to create the table from external input, you will need to validate the information in php code and form and run a non-prepared query. things like database, table, and column names, because they are not used in the query as strings cannot be protected against sql injection by using any string escape functions. if all the information is being using to create the table is produced solely in your code, you would just form an run a non-prepared query. -
i suspect you are referring to these - all of these state that the form/form fields would/should be dynamically produced/created. the point of a web server-side scripting language, like php, is to dynamically produce web pages, so that the web page can be flexible and dynamic in what is does, but it also eliminates the need for the person creating the web page to write out block after block of repetitive html markup or repeat the same content on multiple pages. php is not just for processing form data. it is used to produce anything that makes up a web page - html, css, javascript, and media files. in this thread, you have written out 20-30 sets of form fields, twice. once without name attributes, then a second time with. and there are a ton of missing and inconsistent markup/labels in those sets of form fields that at some point you will need to fix. you have also written out nearly 30 php echo statements. DRY - Don't Repeat Yourself. this means that you should not repeat what you do. let the computer generate the multiple sets of repetitive/same meaning form fields and let the computer process all the submitted form data by looping over it. using php, you can write one set of form fields (i.e. a template of what you want), then use a loop in your code to produce as many fields as you want. by having the the card quantity and card name form fields defined only once, it will now be easy to fix any errors or make any changes in those form fields. you only have to do it once, not 20-30 times. and as i also stated, the number of fields you produce can come from the following, dynamically, at runtime - as also stated, by using an array for the form field name (see the link i provided), the form data will be submitted to php as an array. you can write a simple loop to process all the data, no matter how many form fields there are.
-
the data from a post method form will be in $_POST variables, with that exact capitalization and with the under-score, which is what Ch0cu3r first gave an example of in reply #12 in this thread. this is not the same as $_post. php variables are case-sensitive, which you would have known if you had studied the prerequisite basics of the php language. the capitalization we are typing when it comes to the actual php code elements we are showing you is not there for emphasis, it's there because it is required. programming is an exact science. every letter in every line of code matters and in this case, the letter-case of those letters matter.
-
you have to tell us what 'it is not working' means. we don't have the ability to run your code on your server with your data and we are also not sitting right next to you and don't know what you saw that leads you to believe that something didn't work. unless your code contains an obvious problem, we cannot tell you why it doesn't work just by looking at your code, and we are not going to look through multiple files unless you narrow down where to look at first.
-
what you are using for the forum's [/nobbc] bbcode tags isn't working, as you can see since your posted code isn't contained within a color-highlighted box -<?php// your php code here...echo "hello world";?> i suspect that your closing bbcode tags isn't [nobbc][/code] ?
-
just because you saw, found, or bought something on the Internet doesn't mean it's the correct way to write code. there's a ton of crap code to be found on the web that was written by people that never learned the actual reason for doing things and are more concerned with click revenue and things they can get you to buy on their site than the quality of the code they are posting/selling.
-
the reason your code currently isn't working is because you are not echoing the $result->id in the various form name= .... attributes
-
actually, your title of this thread is about php, but what you are having a problem doing is programming. these are two different things. php is a programming language. putting programming language statements together so that they accomplishing something, is programming. php is a fairly intuitive programming language. you can generally look at code written in php and deduce/infer what that code is doing, provided that people have used meaningful names for things like variables, form fields, database tables/columns, ... and have not used any short-cuts that magically create or alter values without explicit code or lists of data doing the creating or altering of the values. programming, i.e. actually putting code together that accomplishes a stated goal, requires definition, definition, and more definition. in order to produce program logic that does something, you must first define what you are trying to accomplish/what the goal is, then what inputs you have available (even if the input is just the request to run the code), define what processing you are going to do based on the inputs, and define what result or output you are going to produce from those inputs. programming also requires that you are familiar enough with the syntax, punctuation, and spelling of the language you are using so that you can write meaningful sentences/lines of code using that language. for your current thread - http://forums.phpfreaks.com/topic/297755-improper-form-working-in-php/ what you are trying to accomplish is to provide a form for entering a hostname/domain name, then display the dns records for that hostname/domain name. this is actually two separate goals/processes on one physical page, two logical pages in one. displaying the form for entering the data is one goal/process. displaying the result, after the form has been submitted, is a second goal/process. for the form, what inputs do you have, what processing will there be for each of those inputs, and what result/output will you produce. inputs - along with just the request to run the code, you may (optionally) have validation errors and the previously entered form field data. processing for each of those three inputs - (unconditionally) produce a form, (optionally) format validation errors, and (optionally) get previously entered form field data. output/result - display any validation errors, display the form that you produced, and repopulate the form field(s) with any previously submitted form data. so, for your form, what would applying this process this look like - // form // inputs - request to run the code, (optionally) validation errors, (optionally) previously entered form field data. // processing - (unconditionally) produce form, (optionally) format validation errors, (optionally) get previously entered form field data. // output/result - display any validation errors, display form, repopulate form field(s) with any previous form data. // processing - // get any previously entered form field data. $url_value = isset($_GET['url']) ? $_GET['url'] : ''; // produce form $form_output = "<form action='". htmlspecialchars($_SERVER['PHP_SELF']) . "' method='GET'> Enter URL: <input type='text' name='url' value='$url_value'> Submit: <input type='submit' name='submit'> </form>"; // format any error messages - this example assumes that you have an array of messages in $errors (so that you can handle any number of errors, not just one.) $error_output = ''; if(!empty($errors)){ $error_output .= "The following errors occurred:<br>"; foreach($errors as $error){ $error_output .= "$error<br>"; } } // output/result - if(!empty($error_output)){ echo "<span class='error'> * $error_output</span>"; } echo $form_output; for the form processing code, you would do the same. define what inputs you have, what processing you are going to do on each of those inputs, and what output/result you are going to produce from those inputs.
-
Submit $_POST with dynamically generated fields
mac_gyver replied to bambinou1980's topic in PHP Coding Help
yes you can. between all the threads you have started for this, you have been given the parts you need, though some of the advice has been off topic because you have shown things like using a select/option menu where nothing is being selected. start off with the basics and define what you are trying to do or produce before writing any code for it. until you can create a form that submits the data you want, there's no point in all of the other markup you have in your code. see this basic example - <form method="post" action="index.php"> <?php // Query for all the products $query_field2 = "SELECT * FROM products ORDER BY name"; $result_field2 = mysqli_query($connection, $query_field2) or die (mysqli_error($connection)); // you were missing the connection link in the mysqli_error() statement while($row_field2 = mysqli_fetch_array($result_field2)){ $id = $row_field2['id']; // i guessed this was id, even though you stated your columns were product_id (and product_name) in one of the threads $name = htmlspecialchars($row_field2['name']); $price1 = htmlspecialchars($row_field2['price1']); // these should be decimal numbers only and be under your control, so no need to apply htmlspecialchars $price2 = htmlspecialchars($row_field2['price2']); $price3 = htmlspecialchars($row_field2['price3']); echo $name; echo "<input type='radio' name='price[$id]' value='$price1' checked>€ $price1"; // pre-check/select the first price if($price2 != null){ echo "<input type='radio' name='price[$id]' value='$price2'>€ $price2"; } if($price3 != null){ echo "<input type='radio' name='price[$id]' value='$price3'>€ $price3"; } echo "<label> Qty "; echo "<input name='quantity[$id]' type='text' size='4'></label><br>\n"; } ?> <button type="submit" name="submit" >Create Order</button> </form> -
@purge08, we are not trying to give you a hard time. however, this thing called programming requires that you learn what every character in every line of code means, so that you will know what it does, so you will know if it even belongs in your code or where it belongs in your code to accomplish a goal. to do this, you cannot simply follow along with things you have seen. you must really learn what they mean. until you learn and understand how to write a simple form and php code to process that form, you are not ready to do this for your data. forget about writing out 30 different sets of form/php code. that's just a waste of your time at this point (and as i wrote above, you should be letting the computer do the repetitive work of creating the form fields and processing the form data, rather than you writing out all this code.)
-
if you paid anything for this script, it should have been written with proper error checking and error handling logic in it, because well written code is self troubleshooting. the code should be telling you why it is failing. all the database statements - connection/query/prepare/execute should have error checking/handling logic. until you add some error handling that tests the result of the query and echoes/logs the $conn->error property when the query fails, you will not know why the query is failing. it could be that the database connection isn't selecting the correct/a database, or that the database table or column names don't exist or are incorrect for that database. in addition to what has already been mentioned, there are a number of other shortcomings with this code. it's not protecting against sql injection in most of the queries. it's not hashing the user passwords. the code referencing the signup variables isn't part of any of the singnup form processing code. there's a race-condition in the singup code between the select query and the insert query that would let multiple visitors try to use the same username.
-
unlinking a file suddenly stopped working. Any ideas why?
mac_gyver replied to sonnieboy's topic in PHP Coding Help
your query is matching no rows. where is $strId coming from and what does echoing/dumping its value show? your code should test if the query found any rows before trying to use the data from the query. -
that statement is testing if $_REQUEST is logically true or not, which is effectively testing if it is empty or not. it is always set, but if it is empty/there are no array indexes present, that's a false value. if it is not empty/there are array indexes present, that's a true value. the overall php $sql string statement is within double-quotes and the php variables will be parsed. the single-quotes within the php string are part of the sql syntax, not the php string syntax. @StreamersUnited, the error message you are getting, which is very common and if you had researched the web for it, means that the query failed due to an error. you must ALWAYS test if a query even ran before you can try to use the result from the query. $results will be a false value if the query failed due to an error and you can echo/log the $conn->error property to find out what sort of error occurred. $results will be a result object/true value if the query ran without any errors. lastly, your code should only make one database connection. you need an exit;/die; statement after your header() redirect to prevent the rest of the code from running. and, if you are expecting post data from a form, use $_POST, not $_REQUEST. $_REQUEST combines $_GET, $_POST, $_COOKIE (default order is GPC) data and if you are in a habit of using $_REQUEST you will likely at some point write some code that adds a same name variable between those three different sources and end up with code that doesn't do what you expect. using $_REQUEST just makes more work when writing code, because you and all the programmers working on a larger project need to keep straight all the possible same name $_GET, $_POST, $_COOKIE and $_REQUEST variables.
-
SELECT statement, Multiple WHERE, with requirements
mac_gyver replied to BuildMyWeb's topic in MySQL Help
a UNION query built from the x number of SELECT queries would result in the fewest round-trip communications/queries ran. -
Restrict field values to either 1 or 0 in PHP
mac_gyver replied to VanityCrush's topic in PHP Coding Help
no. that looks the same for the empty test. your current logic only reports that at least one of the required fields was left empty. not which one(s). your code also prevents the rest of the validation tests from running if there are any empty fields. there could be problems with the non-empty fields, but the user won't see those errors until they fill in the empty fields. this will result in an unhappy user, because he may have to submit the form extra times, when he could have corrected all the errors at once. -
Restrict field values to either 1 or 0 in PHP
mac_gyver replied to VanityCrush's topic in PHP Coding Help
that's not what testing if $_POST is empty or not does. testing if $_POST is empty or not detects if the form was submitted. it's testing if any of the named form fields are present, even if they are empty, in the $_POST array. $_POST will be empty if no form was submitted or a form was submitted and the total size of the form data exceed the max_post_size setting. -
Restrict field values to either 1 or 0 in PHP
mac_gyver replied to VanityCrush's topic in PHP Coding Help
this bit of code has several problems - if (empty($_POST) === false) { $required_fields = array('usernamne', 'password', 'password_again', 'first_name', 'active', 'email'); foreach ($_POST as $key => $value) { if (empty($value) && in_array($key, $required_fields) === true) { $errors[] = 'Fields marked with * are mandatory'; break 1; } } 1) you should not blindly loop through the $_POST data. a hacker can submit 100's or 1000's of values. you should instead loop through the definition of your fields and test the corresponding $_POST data. also, unchecked checkboxes and unselected radio button groups are not set in the $_POST data, so your current logic won't detect if a required checkbox/radio button choice hasn't be selected. 2) a zero is considered to be empty(), which is probably why your zero case wasn't working. 3) by breaking out of the loop upon the first empty value, you are only reporting a general error. you should specifically produce an error for each required field that was empty. this will help the visitor know what he left empty (yes, they need to be specifically told), and it will help with programming errors/typo's by reporting exactly which fields the code thinks was left empty. 4) this programming style is a killer - empty($_POST) === false. the empty() function is designed to return a boolean value that you directly use in your program logic. by adding another comparison operator to it, you are building up a forest of unnecessary code. -
the error means an array element is being referenced that doesn't exist. adding isset() to test if something exists before trying to referenced it is only valid if what is being referenced is optional, i.e. it may or may not be present. this would be the case when testing if a page got requested and a form may or may not have been submitted, a form element may or may not exist (checkboxes, radio buttons), a get parameter in the url may or may not be present, or code didn't find any matching row in a database table and the code didn't take the added step of preventing any follow on code that's dependent on that data from running. for data that the code requires to be present, you would not use isset() to prevent the error. you would find out why the expected data isn't present by tracing back in the code to find out where it is being produced at and find out why it isn't being produced. adding isset() in this case would just be hiding problems. for the missing $product['key'], i would expect that the key element is required for this code to work at all. if some of the other $product[...] elements are present, but not the ['key'], you would need to find out why. one possible cause would be a difference in the index name from where the value is being produced and where it is being used. it might be ['id'] or ['product_id'] rather than ['key']. for the missing $product['recurring'], that one sounds like it could be optional. but it depends on where and how it is being stored/produced to determine if using isset() to test if it exists before referencing it would be appropriate. if the line of code for it in what you posted is the way the original code is, it would be a safe guess that it is missing an isset() around the $product['recurring'] in that line. sadly, problems like this in code you find posted on the web are due to the person writing the code not really knowing the reason behind what they are doing and are developing code with php's error reporting not fully turned on and/or not fully testing the code they have posted.
- 1 reply
-
- 1
-
-
here's a thread/post showing how you would run an UPDATE query to toggle a value and retrieve a value from that row at the same time - http://forums.phpfreaks.com/topic/296803-get-id-after-update/?hl=%2Blast_insert_id&do=findComment&comment=1513845 the user_id in that thread would instead be your column holding the previously randomized numbers.
-
your stated method actually has a race condition where multiple concurrent instances could produce and try to insert the same number. you can do this using one INSERT query, which avoids the race condition. see the following example - http://forums.phpfreaks.com/topic/297377-going-from-sessions-only-to-remember-me/?do=findComment&comment=1517023 by only running one query, your code should be at least twice as efficient. i would think that 45 seconds for 1000 requests probably means that your current code has some additional inefficients and/or your database table doesn't have an index (the method in the code i linked to above requires an index.) does what you are using these values for require a random number or could it be an incrementing number? also, how many total numbers will there be, because another way of doing this would be to generate all the possible numbers, randomize them, then store them in a database table. you can just query for the next unused value. to avoid the race condition, you would actually run an UPDATE query to toggle a 'used' bit in an available row. then, if the UPDATE query was successful, you know that the row you just toggled contains your random number. you can get the number from that row by using the msyql LAST_INSERT_ID(expr) function in the query, then retrieve the number by fetching the last inserted id value.
-
this is the first prepared query in your code - $stmt = $DB_con->prepare(" ... "); this is the second one, where the error is at - $stmt->$DB_con->prepare($query); look at what is different in those, right after the $stmt variable.