-
Posts
5,450 -
Joined
-
Days Won
175
Everything posted by mac_gyver
-
you cannot mix statements from the different database extensions. your database connection and query are using mysql_ statements. your error reporting is using mysqli_error(). if you were using mysql_error(), you would be getting the actual error information. next, the php mysql_ extension is obsolete and has been removed from php, for a little over a year. you need to be actively converting your code to use the php PDO extension, so that it doesn't stop entirely working should your web host up date the php version.
-
How to add role in this code using if statement ?
mac_gyver replied to AdeelZaighum's topic in PHP Coding Help
aside from fixing the problems in this code, you wouldn't add any role based logic to this code. the purpose of the is code is to authenticate who the user is, that has nothing to do with the user's role and what they can do on a web site. you should also store the user_id value in the session variable, not the mysqli string escaped name that was entered in the form. you would add code to the 'protected' pages to retrieve the current user's role on each page request. and why would you do it this way? so that any change to the role value will take affect without requiring the user to log out and log back in. -
Checking if a checkbox is checked inside a foreach loop
mac_gyver replied to NiallAA's topic in PHP Coding Help
since only checked checkboxes are submitted, there will be no guaranteed relationship between the submitted opp_id[] and opp_played[] values. upon each un-checked checkbox, the id you are getting from the opp_id[] data will be OFF from the checkbox it is for. you could sequentially number both the opp_id[...] and opp_played[...] using code, but there's no need for the hidden opp_id field at all. read on. perhaps you should use a pair of radio buttons for each player instead? this will submit a value for each player, so that you don't have to deal with checked to un-checked checkboxes that won't be in the submitted data. the checkboxes (or radio buttons) need to contain the player id values, as the array index. -
your table_edit_ajax.php code isn't outputting anything back in response to the ajax request, nor does it have any query error checking logic in it, nor does your ajax code do anything with any returned data from the .php code. you MUST have error checking/handling logic in your code, so that your code does something expected when there is an error. your ajax code has a success handler, but it doesn't have an error handler. if the server doesn't respond, shouldn't your ajax code do something? next, all your ajax success handler does is put the two existing values back into the <span></span> elements. shouldn't your php code return a value to the ajax code and your ajax code use that value to tell the user if the operation was successful or not? lastly, the php mysql_ extension is obsolete and has been removed from the latest php version for more than a year. you need to switch your code to use the php PDO extension instead and use prepared queries to supply data values to the sql query statement. this will actually simplify your code since you will no longer need to call the ...escape_string() functions for every pieced of data.
-
other than a typo you have in the 3rd id under case 3, your code 'works' for me. do you actually have any content with ids - additionalguest1, 2, 3 on your page? is the javascript syntax and html markup on your page error free? errors would stop code execution. errors would show up in the developer console in your browser. next, why are you defining and/or assigning values to the radio, attendValue, and numAdditional variables above each function definition. those lines serve no purpose in the posted code.
-
i think the wording of your problem is perhaps causing unnecessary work in solving it. are you trying to use a default image when you have no image defined in your database table, i.e. if $row['url_img'] is empty, use no_img.jpg as the image? if so, you would just put a conditional test in the php code that's producing the output.
-
i would look at row 55982 in your test_db table and see what length the name is (or just run a query to get the maximum length of the data in that column) and make the length of the whisky_name column longer than you expect the names to ever be.
-
have you researched what the html would be to cause a option to be selected? if you haven't, that would be your first step, because if you don't know what html you are trying to produce, there's no way you can write the code to do it. there's hint in the bold part of my question to you in this paragraph. next, after you know what html you are trying to produce, the easiest way of producing it is to dynamically produce the list of <option ...>...</option> choices and the easiest way of doing that is to have the choices defined in a data structure (database table or an array), then simply loop over that defining data and produce the list of option choices. this will reduce the line of code that causes the the option to be selected to a single line, rather than to repeat it for ever possible option in every select menu. rather than to expect the user to know what the customer numbers/names are and use the error-prone method of having them type the value in a form field, you should query your table that defines the customer numbers/names and produce a select/option menu to allow the customer number to be picked.
-
have been looking at the code more, and here is a point that will simplify the posted code even more. inserting a row in the requisicoes (requisitions) table, with the datas, atividade, id_ano (date, activity, school year), is an administrative operation. this must exist before a user can even try to pick a room and time for a date/activity/school year. therefore, the insert query for the requisicoes (requisitions) table doesn't belong in this code. the form that the user picks the room and time on would also submit the correct id for the row in the requisicoes (requisitions) table that he/she is trying to sign up for.
-
the code you posted is expecting a comma delimited list (which could be a single value) in the main $id_bloco parameter. explode() breaks a delimited list into an array. however, your other uses of $id_bloco, when you call ->getDisponibilidadeSala($data, $id_bloco, $id_sala) and ->getDisponibilidadeDocente(($data, $id_bloco, $id_utilizador), appear like they expect only a single value. your current program logic, of first testing if the data exists before deciding to insert new data, would need to call these two methods inside the foreach(){} loop, not call them once before the start of the loop. another problem with the current foreach(){} loop is you are repeatedly executing the prepared insert query, which doesn't use the $id value, inside the loop and also running whatever insert query the ->insertRequisicaoByLastId() call executes. i'm pretty sure this is not what you intended. so, your program logic is confused about what is in $id_bloco and won't work when it is anything more than a single value. you need to make a list what input data you have available, with the data type or format (is the main $id_bloco parameter just one value, a comma delimited list, or an array), then define what processing you are going to do based on the input data. this will help make sure that the code you write is using the data properly and only contains code that you need. somewhat related to first defining what the input data is, your function should not get the school year ($id_ano) internally. all the data that your function needs should be supplied as call-time parameters. this will make your function general purpose and it will work for any set of data values. the current code will only work with the school year value that ->getAnoEscolar() returns. as to detecting if the insert query returned a unique index error, i gave an outline of the method, that you would need to use. however, it turns out that the overall code will need to be more complicated then what you have now, since you have two insert queries, one for the requisicoes (requisitions) table, and whatever insert query the ->insertRequisicaoByLastId() call executes. you would first need to determine when and if you need to execute the insert query for the requisicoes (requisitions) table or get the id for an existing row in the requisicoes (requisitions) table (actually you may be able to use an INSERT on DUPLICATE KEY UPDATE query, where the UPDATE part actually sets up the correct id value for the ->lastInsertId() method to access), to use in the rest of the code.
-
this should (greatly) reduce the amount of code the OP has, to a single query, executed in a loop, which will make it easier to see where any problems are at, i.e. being able to see the forest for the trees. in general, you should NOT try to select data to test if it already exists, to decide if you should insert it. just try to insert the data, and with the appropriate composite unique index defined for your table, detect if the insert query returned a unique index error. to detect the unique index error (the error number is 1062) you would have a try/catch block around just the execution of the insert query and check the error number in the catch block. since you can insert multiple rows, you should set up an array to hold the returned status from all the queries that get executed inside the loop. your current code is checking the last result after the end of the loop and returning just that one piece of status information. also, i am wondering why you must explode a comma separated list back to an array of data, when your form should be submitting an array of data in the first place. shouldn't you just pass the submitted array of data to the function?
-
How can an index be set and undefined at the same time?
mac_gyver replied to NotionCommotion's topic in PHP Coding Help
the error is because you are concatenating the string 'count: ' with the isset() expression, which will always be true. you need to put () around the trinary statement so that it is evaluated as an expression that then gets concatenated with that string. -
the easiest way of producing this type of output is to index the data using the category value when you retrieve the data, by fetching the data into a multi-dimensional array, using the category value as the main array index, and storing each row of data in a sub-array under that index value. then just loop over the main array, which will give you the category and a sub-array of the rows for that category. then just loop over the sub-array to produce the output. after you execute the query - $data = array(); foreach($result->result() as $row) { $data[$row['CatTitle']][] = $row; } // to produce the output - foreach($data as $CatTitle=>$sub_array) { // use $CatTitle here to produce the category heading foreach($sub_array as $row) { // use the elements in $row to produce the output for each product under the category } }
-
the OP does have a spelling mistake, but it's in the variable name being used to hold the message body. if you had php's error reporting set to E_ALL and display_errors set to ON, php would help you by reporting and displaying all the errors it detects. next, I'm surprised you are receiving any emails. the 5th parameter of the mail() function is not in the format of 'From: email', if it's used to supply the sending email address, the format is '-femail' and these emails are NOT being sent from the email address that someone entered in a form on your web site and using it as the From: email header is not correct. the line building the email header - $headers .= 'From:'.$name.' <'.$email.'>' . "\r\n"; should not be using the submitted email address. you can put the submitted email address as a Reply-to: $email email header, after validating that the value in $email is only and exactly one properly formatted email address.
-
Need example of inserting form data into a Mysql db
mac_gyver replied to elentz's topic in PHP Coding Help
you need to define the 'work flow' (steps) and data for each step before you write any code. without knowing what you are ultimately trying to achieve and WHY, it's not possible to advise you based on the content in this thread. just went back and looked at this thread - https://forums.phpfreaks.com/topic/302608-large-number-of-fields-to-upload/ it would appear you are creating 'auto' provisioning files for a phone network, where the mac address is used to identify which configuration file to use for any phone. your phones db table is apparently a list of the mac addresses of the available phones? your templates db table, i would guess is a list of some typical button layouts/template file names? the extensions db table is apparently a list of extension numbers and predefined passwords? if your goal is to edit/assign a phone and a template file name to an extension number, what has been suggested so far in this thread for the form (using an array name for the form field names) is correct. you would actually retrieve any current assignment and pre-select the options in the select/option menus. you would also need to have a way of un-provisioning the phone assigned to an extension number. when the form gets submitted, the form processing code would need to insert new data and update existing data (there a single query that can do this), and delete any data for phones that have been un-assigned (not sure if you need a configuration file in this case that points the phone to a nonexistent extension number or something else to disable it.) the assignment data should be stored in a database table. this will let you edit the current assignments and will also let you produce reports based on the data. the mac-address.cfg configuration files are the end result of the assignment. if the phones are on the same network where the web server/php is at, you can let a php script serve the configuration files, without having actual files. this will keep all the data in sync, since you won't have to create and maintain actual files. anytime a phone makes a request for its configuration, it will get the current values, because they will be retrieved from the database tables at the time they are requested. -
Need example of inserting form data into a Mysql db
mac_gyver replied to elentz's topic in PHP Coding Help
actually, no. based on the form you have posted, you are selecting a phone id and a template id to be associated with an extension number. you would store only these three numbers in a database table. if you are trying to edit the secret/password, that's a different concern from assigning a phone id and template id to an extension and should be handled separately. btw - passwords should be hashed when stored, so displaying the stored value doesn't serve any useful purpose. next, you need to separate all the database specific code out of the html document, by fetching the data from each query into a php array variable, then just use the php array variables in the rest of the code. this will make it easier to write and test your code, your code will be less cluttered, and it will make it easier to switch to a different php database extension, since all the database specific code will be grouped together. as long as the same data is fetched into the php variables, you won't have to touch the rest of the code that's using the fetched data. the form field names you are using will be what php uses for the submitted data. if you are using name='phone' and name='template' for the two select/option menus, the data will be in $_POST['phone'] and $_POST['template']. there will not be any - $_POST['extension'], $_POST['secret'], and $_POST['mac'] variables because you don't have any form fields with these names. since the extension number is apparently what identifies the data being inserted, when you change the form fields to be array names, i would use the extension number as the array index. this will also support the next task you will likely have of being able to edit/update data that has already been inserted into the database table. -
Need example of inserting form data into a Mysql db
mac_gyver replied to elentz's topic in PHP Coding Help
how many rows of data, where is this data coming from/what format is it in now, and how frequently is this going to be performed, since the answers to these questions determine the best method to use to get the data into a database table(s)? if the data is already in the form of a file or some other computer based format, so that it could be uploaded as a csv formatted file, you can just run a single LOAD DATA LOCAL INFILE ... sql query to get the data into a database table. if the data is something that you can copy/paste into a single form field, a php script could break it into rows to loop over them for inserting the data into a database table. if you are going to have a set of form fields holding the data, you would use array names for the different form fields. this will cause the data to be submitted as arrays, that a php script can use a foreach(){} loop to loop over. for the cases where you will have a loop in a php script, you would use a prepared query, prepared once before the start of any looping, with place-holders for the data values, then supply each set of data and execute the query inside of the loop. -
where and how are the agency codes defined now? they must be defined somewhere, since you are able to produce the values you are storing in the orders table. the proper way of doing this is to have the agency codes defined in an agency_code database table, then just retrieve the values to produce the output. once you have 10's of thousands of records in the orders table, you would NOT attempt to extract the agency codes, after the fact, every time you need to produce the select/option menu.
-
MySQL Login -> Password always correct even if wrong?
mac_gyver replied to ChrisX930's topic in MySQL Help
you need to read the documentation for any php function you are trying to use. strcmp returns a zero if the strings are the same. don't even use strcmp for your passwords. you should be using php's password_hash() and password_verify() to handle your password hashing and comparison. there are examples in the php.net documentation showing how to use these. next, Don't Repeat Yourself - DRY. you are already running one sql query to find and then fetch the row matching the username. don't run that query again to get a single piece of data. you already have all the data from the row, from the first time you executed the query. don't loop to fetch data from a query that will at most match a single row. the while() loop code will go away anyway since you don't need to run the query the second time. you need to use a prepared query to supply any data to an sql query statement to prevent sql injection. you should not use or die() logic to handle sql query errors. use exceptions to handle sql errors and you should not output the raw php/mysql errors to the browser on a live site. you should validate each input separately and output a unique message for each validation error. you should NOT identify if the username or the password is the reason for not being able to log in. this will allow someone/bot script to repeatedly submit values to your code and first find valid usernames, then bruit force find a password. output the same generic - invalid username/password for each of these cases. you can log internally the actual reason for a login failure. don't use $_REQUEST variables. if you expect data to be in $_POST variables, use $_POST. you should also detect that a post method form was submitted at all, before trying to use any $_POST variables. this will prevent php errors. if the current visitor is already logged in, you should not run your login form/form processing code. lastly, when the visitor is correctly authenticated, you should store the user's id in a session variable to remember that they are logged in and who they are. all other code that tests if the visitor is logged in would test if the session variable holding the user's id is set and if they need to retrieve any current data about the visitor, they would use the user id to do so. this will insure that any user data is current and up to date. -
changing image icon with button with text in phreebooks
mac_gyver replied to mythri's topic in PHP Coding Help
where the logic test goes is - -
changing image icon with button with text in phreebooks
mac_gyver replied to mythri's topic in PHP Coding Help
because the toolbar class constructor, add_icon() method, and add_help() method are used throughout the application to define/add items to toolbars and set parameters for the added items (some of the constructor's icon_list properties are being set directly in the application code), you would change the existing relevant toolbar class code, not add new primary methods (and hope that none of the application code is defining it's own icon_list entries, since it's all publicly accessible data.) i would keep all the existing functionality. this will allow the application to be returned to it's current operation and if there are cases where the application code is defining it's own icon_list entries, the application will still work while you are finding and fixing these occurrences. just add a 'use buttons' feature to the existing code, i.e. if you have defined an entry to use a button, it will trigger the new code. i would just add a 'button' field to the icon_list definition. if the button field exists ( isset() ), the logic will run the new code for the button functionality. next, the code already has defined constants that are used for the current image alt='...' parameter. you should use these as your button text so that you are not repeating things in code that have already been defined. presumably, this has been set up to support multiple languages with a language selection menu/configuration. so, in the toolbar class constructor, add_icon(), and add_help() methods, add a 'button'=>true element to any icon_list entry that you want to switch to use a button. in the build_toolbar() method, add a logic test for this button array element. if it's not set, call the existing html_icon() function. if it is set, call a new function that's similar to the html_icon() function code but produces the html that you want for a button. -
your code and queries are only as secure as you make them. if you use a prepared query incorrectly, it will won't be secure. by using a true prepared query (the PDO extension has emulated prepared queries turned on by default for all database types, despite what the documentation states, and you need to turn them off when you make the database connection) to supply data values to the sql query statement, your sql query will be safe against sql special characters in the data from breaking the sql syntax or breaking out of, i.e. escaping from, the sql syntax in the case of intentionally injected sql. after you choose the php database extension you are going to use, the posted code needs to do or not do a number of things - 1) you are mixing procedural and OOP style for the msyqli statements. you should be constant in your programming. using the PDO extension will fix this since it only has OOP statements. 2) using prepared queries will eliminate all the ...real_escape_string() calls. you are using one in the case of a value being output to the browser. the ...real_escape_string() statements are only used on string data being supplied to a non-prepared sql query statement, not on data being output to the browser. 3) you need to use exceptions to handle database statement errors. your code has error handling on only one of the query statements now. the PDO extension already uses exceptions for connection errors. you need to set the error mode to exceptions, for all the rest of the statements, when you make the connection. 4) all the post method form processing code should be grouped together and come near the top of your code. you should actually test if a post method form was submitted, then if you have multiple possible forms, detect a field name or field value that identifies if the Delete or Update form was submitted. 5) you should validate all the submitted data before using it, then only use it if it is valid. use an array to hold validation errors. you can then test if the array is empty or not to determine if there have been any validation errors. to display the errors, just output the contents of the array. 6) your delete checkbox logic only works for a single/last checkbox. in fact, all the form fields don't work when there is more than one set of data in the form. you need to use array names for all the form fields, with the $row['id'] value as the array index (this is needed to distinguish which row each form field value corresponds to) and you need to remove the hidden field with name='checkbox' (having this causes only the last checkbox in the form to work.) you would also need to add a loop in the Update form processing code to loop over all the submitted sets of data. 7) with prepared queries, when you are looping over data and executing the query inside the loop, you will prepare the query once before the start of the loop. the code inside the loop only gets the correct set of data and calls the ->execute() method. when you remove the hidden form field with name = 'checkbox' (which was done to prevent php errors when no checkboxes are checked, but because it is being output repeatedly, only allows the last checkbox to work), the logic in the delete form processing code will need to be changed. if there are no checked checkboxes, $_POST['checkbox'] won't be set. you need to add an if(isset($_POST['checkbox'])) test. 9) the code to retrieve the data needed to display the page should be removed from the actual html document/template. this will make it easier to write and test your code, and if you need to change the code to use a different database extension, such as the PDO extension, consolidates the database specific code in one place and makes the html document/template general purpose. just fetch the data from the query into a php variable and use that variable in the html document/template. 10) the html document you are creating is reusing DOM id='...' attribute values. id's must be unique. if the client-side code isn't actually referencing the id's, don't even put them into the markup. 11) you are outputting an empty <tr></tr> after each actual <tr>....</tr> of output. makes no sense and is repeating an id attribute value which is also not valid. only output markup that you need. 12) you are outputting the $row['id'] value in a form field. this is not an editable data value. the $row['id'] specifies which row the data belongs to. you can display the $row['id'] value if you wan't, but it should not be in a visible form field. see item #6 in this list for how the $row['id'] value should be used to associate the submitted values with the $row['id'] value they belong to. 13) when your SELECT query doesn't match any data, your code is correctly skipping over the code to produce the output from that data, but your code is also not doing anything to notify the user that there was no data to display. you should set up and display a message that the reason for the blank section on the page is that there is no data to display. 14) all data values being output to the browser should be passed through htmlentities(), with an appropriate 2nd parameter value, to prevent any html entities in the data from breaking the html on the page and to help prevent cross site scripting. 15) you are repeating the <tbody>...</tbody> tags for each set of data being output. while this is valid markup, unless you are going to style each table body section separately, there's no point in doing this and it is just adding clutter to the result and would prevent a large table body section from being able to be scrolled on the page.
-
to get the initial undefined index error, your index.php page probably has nested forms or some invalid markup at some point and isn't submitting a $_POST['id'] value. it's also possible that with all the redirecting you are doing, that you have redirected back around to the edit_author.php page from somewhere else. you should actually do all of this on a single page. it will simplify all the code and markup you are having to write and test. three things - 1) you should actually be using a link or a get method form on the index.php page, since you are determining what data will be gotten and displayed on the edit_author.php page. 2) you must ALWAYS validate the inputs you expect and set up and display error messages when the input isn't present, isn't a valid value or format, or doesn't match any expected data. only use the input value(s) after it has been validated. 3) you need to always have an exit; statement after a header() redirect to prevent the rest of the code on the page from running. this may be the cause of your undefined index error, if the code later on the page or on some other page is redirecting to the edit_author.php page. next, your UPDATE form processing code must first test if a post method form was submitted before trying to use the submitted data, then validate that data before using it. the UPDATE form processing code should come first in the logic flow, then you should retrieve any data for populating the form. you also need to detect if the update form has already been submitted to control if you should retrieve the data for populating the form (if there was a validation error and you re-display the form, you want to populate it with the just submitted data, not the values from the SELECT query.) the easiest way of determining if you should run the SELECT query or not is to use an internal array variable to hold the data being operated on. the UPDATE form processing code would copy the submitted $_POST data to the internal array variable. at the point of running the SELECT query, if the internal array variable is empty, run the SELECT query and retrieve the data into the internal array variable. use the internal array variable as the values you populate the form fields with. it will initially be the values from the SELECT query. after the form has been submitted, it will be the submitted form values.
-
see the following example, that separates all the database code out of the presentation logic, making it easier to write, test, and debug just the presenation logic - // retrieve and store the data into a structure that supports the output you are producing // this is made up data, your code would produce this same structure from your actual data $data = array(); // the main array index is the page name - gets tested against the value in $page for the active attributes $data['home'] = array('link'=>'not sure if your links include the / or if it is part of the shopConfig url','menu_display'=>'Home','children'=>array()); // parent only, no-empty children $data['riders'] = array('link'=>'riders','menu_display'=>'Riders','children'=>array( array('id'=>1,'identifier'=>'lee-smart','rider_name'=>'Lee Smart'), // add an array to the children array for each rider data row )); // married with children - go Al Bundy // produce the output from the data ?> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <?php foreach($data as $page_name=>$arr) { if(empty($arr['children'])) { // parent only, no children $active = $page == $page_name ? " class='active'" : ''; echo "<li{$active}><a href='{$shopConfig['url']}{$arr['link']}'>{$arr['menu_display']}</a></li> "; } else { // w/children $active = $page == $page_name ? "active " : ''; echo "<li class='{$active}dropdown'> <a href='{$shopConfig['url']}{$arr['link']}' class='dropdown-toggle' data-hover='dropdown' data-toggle='dropdown'>{$arr['menu_display']}<b class='caret'></b></a> <ul class='dropdown-menu'> "; // loop over the children foreach($arr['children'] as $child) { // define different handling for different data structures switch($page_name) { case 'riders': echo "<li><a href='{$shopConfig['url']}{$arr['link']}/{$child['id']}/{$child['identifier']}'>{$child['rider_name']}</a></li> "; break; default: // child echo "<li><a href='{$shopConfig['url']}{$child['link']}'>{$child['menu_display']}</a></li> "; } } echo "</ul> </li> "; } } ?> </ul> </div><!-- /.navbar --> </div><!-- /.container --> </nav> for the example output you posted, this code produces the correct opening and closing elements and should work.
-
you have too many queries, code, and logic, so it's not possible to make any sense from the code you posted what result you actually want from that code. you should not run select queries inside of loops and you have closing html markup in an else{} statement, at about about line 90, that corresponds to opening html markup that's inside the corresponding if(){} statement. start by separating the concerns in your code. you should execute ONE sql query statement that gets all the related data at that you want, in the order that you want it, then fetch that data into a php array variable, then loop over the fetched data to produce the output. you can test each step to make sure it is doing what you want before going onto the next step. edit: you should also use exceptions to handle database statement errors so that you don't have to have error handling logic at each statement that can fail. with exceptions, your main code only has to deal with error free statements.