-
Posts
5,476 -
Joined
-
Days Won
179
Everything posted by mac_gyver
-
Unable to pull data from database table
mac_gyver replied to portabletelly's topic in PHP Coding Help
after reviewing the code more, let me introduce you to 'event delegation'. this will let you simplify all the code for attaching events to the buttons. this works by attaching the event to a parent container, such as the div with class='right-content', that all the buttons will exist in, regardless of when they are created. you would then find which button has been clicked by testing an attribute value from the button, such as a class name. the code would look like - document.addEventListener("DOMContentLoaded", function() { console.log("✅ DOM fully loaded and parsed."); // use event delegation for dynamically added elements (buttons) // attach the event to a common parent element - class='right-content' const buttonWrapper = document.querySelector('.right-content'); // add the click event to everything in the common element, now or in the future buttonWrapper.addEventListener('click', function (event) { // examine the className of the clicked element console.log('target class: ',event.target.className); switch(event.target.className) { case 'view-details-btn': view_details(event.target); break; case 'change-status-btn': openStatusModal(event.target); break; case 'update-notes-btn': openNotesModal(event.target); break; case 'delete-btn': deleteRenewal(event.target); break; case 'closeModal': document.getElementById(event.target.getAttribute("data-modal-id")).style.display = "none"; break; case 'confirmChangeStatus': confirmChangeStatus(event.target); break; case 'confirmUpdateNotes': confirmUpdateNotes(event.target); break; } }); }); -
Unable to pull data from database table
mac_gyver replied to portabletelly's topic in PHP Coding Help
the most immediate problem is you are reusing id="updateNotesModal" for two modals. the modal you see is the one defined in get_renewal_details.php, but the javascript code that's running when you click the "update notes" button is what is defined in Renewals.php and this doesn't match the elements in the modal that is displayed. best suggestion is that get_renewal_details.php should only get and display the details. there should only be one id="updateNotesModal" modal defined, so there won't be any confusion about which one gets displayed and operated on. -
the php error you are getting is a follow-on error, because the query is failing, but there is no error handling for the query. the easiest way of adding error handling for all the mysqli statements that can fail - connection, query, exec, prepare, and execute, is to use exceptions for errors (this is the default setting now in php8+). to enabled exceptions for the mysqli extension, add the following line of code before the point where you make the database connection (or upgrade to php8) - mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); you should then be getting an uncaught exception error with the raw database error information in it about a non-groupby/non-aggerate column being referenced. the correct way of fixing this is to a) only select the columns you are using, and b) every column you are selecting needs to be either in the GROUP BY term or used in an aggerate function. there is a database server mode setting that control if this condition produces a query error (the current setting) or if it is just a warning. you may or may not have access to this database mode setting.
-
Using php to display different images based on the date
mac_gyver replied to Ocean_Voyager's topic in PHP Coding Help
the syntax error(s) are due to missing quotes on the end of each string and reusing the same type of quote inside the strings. you are building and echoing literal strings. the initial and final quotes on each string must be the same type and be a matching pair. you are missing the final quote on each string. the > at the end are part the <img ... > tag and belong inside the string, e.g. echo "<img ...>";. any quotes that are within a string must either be the 'opposite' type, single vs double, or they must be escaped so that they don't match the initial quote, which terminates the string. the initial and final quotes around the src="..." attribute should either be changed to single-quotes or escaped with \ characters. i prefer less typing, so i would use single-quotes. next, your conditional logic only needs - if( normal case){ echo normal output } else { echo special output }. lastly, your conditional comparisons need some help. you need to test if the 'm' and 'd' part of the date is greater than or equal a lower value AND less then or equal to a higher value. also, for testing purposes, you need to be able to manually set the value being tested, so this value should be built in a variable, which will be a string, e.g. '0106' for jan 6th. as long as the fields making up a string are the same width, and from left to right, most significant to least significant, you can directly compare strings, e.g. if('0106' <= $some_variable ... i'll let you cogitate on how to create and test the conditional logic needed. -
What am I doing wrong with this 'php include' coding?
mac_gyver replied to Ocean_Voyager's topic in PHP Coding Help
the file system path/filename must be to where the file is located on the disk, either using a relative path (relative to the file with the include/require starting in it) or an absolute path. a leading / refers to the root of the current disk, which is doubtful where that file is located, and which will be producing a php error about a non-existent path/file. you must get php to help you by reporting and displaying all the errors it detects. you can temporarily set php's error_reporting/display_errors in your code (you will want to remove the settings when you are done learning, developing, and debugging). you can add the following immediately after the first opening <?php tag in the main file - ini_set('display_errors', '1'); error_reporting(-1); -
Could use some insight on a database installation issue...
mac_gyver replied to Jim R's topic in MySQL Help
it would be nice to know what you do and what the software does concerning database creation, database user creation, and database user permissions. do you create the database, the database user, and assign permissions, then enter the connection information into the configuration file? are any tables being created in that database? are there any other similarly named databases that if they for example stripped out non-ascii characters could match the desired database name? what i suspect is there is more than one database, that they then get switch somewhere in the process so that at the point where the query in question is executed it's not using the correct database or that the table creation fails due to a permission issue and there's no error handling and/or no reporting of the failed table creation queries. -
What am I doing wrong with this 'php include' coding?
mac_gyver replied to Ocean_Voyager's topic in PHP Coding Help
a bunch of points - three ... in a relative file system path is invalid. you should be learning, developing, and debugging code on a localhost development system, such xampp. do you have php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your development system, so that php will help you by reporting and displaying all the errors it detects? is the main page a .php page? what does the 'view source' of the resulting web page show in the browser? you should use 'require' for things your code must have. your goal is to produce ONE valid web page. the file that you require is not a complete web page, it is only the code/content that you want to be required at that point in the web page. you need to validate the resulting web pages at validator.w3.org all the navigation links you have shown are all the same. you should be dynamically building the web pages using a Content Management System (CMS), in which case the navigation links would be dynamically built too, based on the defined pages, instead of manually creating and managing a bunch of pages yourself. -
Could use some insight on a database installation issue...
mac_gyver replied to Jim R's topic in MySQL Help
are you sure of the database name and its capitalization? what type of hosting is this? on shared web hosting, the actual database name usually gets some unique part of the account naming prepended to it, so that everyone who creates a database named 'abc' actually gets a separate database that only their account can see and access. -
send checkbox value to email using phpmailer
mac_gyver replied to ianhaney10's topic in PHP Coding Help
only checked checkboxes are set in the submitted form data. for what you are doing, you should only be concerned if they are set or are not set, not what the value is (the default value will be the text 'on'). i recommend that make an array that defines the checkbox field names and labels, then loop over this defining array to dynamically produce the form fields, pre-checking any existing checked boxes, in the case of a user/validation error, then loop over this defining array in the post method form processing code, testing which one(s) are set or are not set in the form data to produce whatever result you want.- 1 reply
-
- 1
-
-
what does the data look like? is there only one row of data or is there a set of rows of data? modern php no longer assumes that unquoted associative array indexes, that are not defined constants, are strings. you must use quotes around associate array indexes. if you tried the above code, did it produce php errors? do you have php's error_reporting set to E_ALL (it should always be this value) and display_errors set to ON, so that php will help you by reporting and displaying all the errors it detects?
-
the attached code displays the menu, but has nothing to do with adding items to an order (cart), entering the customer information, or submitting/saving that information as an order. some points about the posted code, most of which will greatly simplify it (eliminating more than half of the typing) - use 'require' for things your code must have. don't prepare and execute a query that doesn't have any dynamic value being supplied to it. just use the ->query() method. the settings don't need elseif() logic, just if(), because the option_name can only be one value at any time. Don't Repeat Yourself (DRY.) there are only a few small things different between the corresponding if/else code blocks. the conditional logic should only setup the values for the different things in variables, then simply output them in one instance of the code. don't run queries inside of loops. use a single LEFT JOIN query to get the menu categories and menu items all at once. when you fetch the data, index/pivot it using the category id as the main array index. you can then simply loop over the data using two nested foreach(){} loops to produce the output. don't create unused variables/code. when embedding a php echo statement in html markup, use php's short-open-echo tag <?= and you can leave out the closing ; right before a closing ?> tag, for example - <?=$source?> SELECT queries that can return more than one row need an ORDER BY ... term to insure that the rows are in an expected order.
-
here's an example for the fields you have shown in this thread - <?php // define the fields // you would add other things to this definition, such as validation rules and processing rules $fields["it_c"] = ['label'=>'Whatever it_c is','type'=>'numeric']; $fields["it_h"] = ['label'=>'Whatever it_h is','type'=>'numeric']; $fields["ot_c"] = ['label'=>'Whatever ot_c is','type'=>'numeric']; $fields["ot_h"] = ['label'=>'Whatever ot_h is','type'=>'numeric']; // add entires for all the form fields... // examine the submitted data echo '<pre>'; print_r($_POST); echo '</pre>'; ?> <?php // produce the form ?> <form method='post'> <input type='submit'><br> <?php foreach($fields as $field=>$arr) { switch($arr['type']) { case 'numeric': echo "<label>{$arr['label']}: <input name='$field' type='text' class='numeric'></label><br>"; break; // code for other types... } } ?> <input type='submit'> </form>
-
if you have more than 2-3 form fields, you should be dynamically validating (on the server) and processing them, and dynamically building the form, by defining a data structure (array or database table) in the server-side code that contains all the information about the fields - name, label, type, validation rules, processing rules, ... you would then loop over this defining data structure to produce the form, validate the data, and process the data. doing this dynamically produces Don't Repeat Yourself (DRY) code, because the code/markup for any particular type of thing only exists once. if you need to make a change or correction to anything, you only have to do so in one place, not each different place. for the case you have listed in this thread, when producing the form fields, the logic for all the items with type='numeric' would output a form field with a type='text' attribute and add the class attribute for the javascript to make use of.
-
this doesn't exist at the point when the ajax request is made, because they are two different http(s) requests. that's because ALL the code in index.php has already been executed during the initial http(s) request for index.php, by the time the ajax request occurs. for the initial case when the session variable doesn't exist, after you output the javascript code, the php code needs to exit/die without doing anything else (it currently runs to completion.) the ajax request needs to be to index.php, instead of screenDetect.php. the code will then set the session variable and it will be available when the rest of the code in index.php runs.
-
are the include_once statements (you should actually use require for things your code must have and include/require are not functions, the () around the path/file do nothing and should be remove) exactly as you have shown or are they actually using http(s) requests and you have redacted that information in the posted code? note: php's error_reporting and display_errors should be set before you execute any other php code (ideally they would get set in the php.ini on your system), in case that code produces an error. if the session is not persisting between requests, it's likely that the session_start() is failing, but you don't know that since you are setting the error_reporting/display_errors after the session_start() statement. also, you cannot set display_startup_errors in your code because php has already started at that point. edit: so I looked at the javascript. the php code that gets executed due to the http request it makes must have its own session_start(), but only if it has been requested via the ajax call, and the session parameters must be exactly the same as the index.php's session_start().
-
i recommend giving the fields a class name. you can then eliminate the array and just use getElementsByClassName to get a collection of the elements to loop over. see if this gets you closer to what you want - <html> <head> </head> <body> <script> function hasNumericValue() { const matches = document.getElementsByClassName("numeric"); for (let i = 0; i < matches.length; i++) { alert(Number.parseInt(matches[i].value)); } } </script> <form name="tester" method="post" action="" onsubmit="return hasNumericValue();" > <input name="it_c" type="text" class='numeric' value=""> <br> <input name="it_h" type="text" class='numeric' value=""> <br> <input name="ot_c" type="text" class='numeric' value=""> <br> <input name="ot_h" type="text" class='numeric' value=""> <br> <input type="submit" value="submit"> </form> </body> </html> you can then test if each value is or is not a number.
-
your example works as expected for me. what php version are you using? what does using - echo '<pre>'; print_r($spec_recipe); echo '</pre>'; show for the data?
-
you are doing 'date-ination'. it's like pagination, but using dates. you should be using a get request to determine what will be displayed on the page. this is so that if someone finds a result they would like to return to or share, they can bookmark or share the URL and can return to the same result. the dates you pass in the URL should be a standard YYYY-MM-DD format. format the dates as 'l j M' only when you display them. you would default to the current monday if there is no get input. you would produce the previous/next links with the previous/next monday's date and include any existing get parameters so that if you add other search/filters, they will automatically get propagated in the URL between pages. example code - <?php date_default_timezone_set('America/Denver'); // default to the current monday if there is no get input if(!isset($_GET['fdw'])) { $dw = new DateTime('monday this week'); $fdw = $dw->format('Y-m-d'); } else { // you should validate that the get input is a properly formatted date - code left up to you $fdw = $_GET['fdw']; } // use $fdw in your code to produce the output $dw = new DateTime($fdw); echo $dw->format('l j M') . '<br>'; // get a copy of any existing get parameters $get = $_GET; // produce the previous link // calculate previous date $dw = new DateTime($fdw); $pw = $dw->modify('-1 week'); $pfdw = $pw->format('Y-m-d'); // set the fdw element $get['fdw'] = $pfdw; // build the query string part of the url $qs = http_build_query($get,'','&'); echo "<a href='?$qs'><button>< Previous Week</button></a>"; // produce the next link // calculate next date $dw = new DateTime($fdw); $nw = $dw->modify('+1 week'); $nfdw = $nw->format('Y-m-d'); // set the fdw element $get['fdw'] = $nfdw; // build the query string part of the url $qs = http_build_query($get,'','&'); echo "<a href='?$qs'><button>Next Week ></button></a>";
-
need access for different account roles on a php page
mac_gyver replied to ianhaney10's topic in PHP Coding Help
the only user data you should store in a session variable upon login should be the user id, to identify WHO the logged in user is. this will either be set or it won't be. you should query on each page request to get any other user data, such as a username, permissions, or role. this is so that any changes made to this other user data takes effect on the very next page request. this will allow you to promote or demote a user without requiring them to logout and back in for the change to take effect. do you really want a situation where you have demoted or banned a user and they can still access a page because their session data says they can? i recommend that you simplify the logic and separate the login test from the user role test. also, to test if a variable is in a set of values, define an array of the permitted values and use in_array() to perform the test. using these suggestions, the logic would become - $page_roles = ['Member','Secretary']; // roles permitted for the current page $user_role = 'Guest'; // default value for a non-logged in user // is there a logged in user if(isset($_SESSION['user_id'])) { // query here to get any other user data, such as the user role, and store it in a regular variable // fake a value $user_role = 'Member'; // $user_role = 'Secretary'; // $user_role = 'Other'; } // logic to determine if the current user can access something on this page if(in_array($user_role,$page_roles)) { // access permitted echo 'permitted'; } // logic to determine if the current user cannot access something on this page if(!in_array($user_role,$page_roles)) { // access denied echo 'denied'; } -
MySql (with whatever variations in capitalization you like) is the database server type. mysqli and PDO are php's extensions that allow your php code to communicate with the database server. if you understand what your mysqli based code is doing, you should be able to convert the code. all it's doing is - building an sql query statement. which should be in a php variable, in order to separate the sql as much as possible from the php, and allow you to separate the common php code used or in this case change the database extension being used. there's no difference between the sql query statement for the mysqli or PDO extensions, when using positional ? prepared query place-holders. prepare the sql query. there's no difference in the php syntax for the the mysqli or PDO extensions, except that the connection variable must be (and is usually named) for the extension being used. bind input data/execute the prepared query. If you are using php8.1 or higher, the php syntax for the execute statement is exactly the same. you can then use msyqli's get_result() and fetch_all() methods to fetch all the data from the result set.
-
you are not seeing the new record until you add another one, because the overall code on your page is out of order. you are processing the post method form data after the point where you are querying for and displaying the data on the page. did you read my reply at the end of your previous thread? as to the data being repeated, when you examine the raw data in the database table are there duplicates?
-
the OP's 'working' database code is using the mysqli extension. the provided autosuggest example is using the PDO extension, along with a connection variable name, $pdo, hinting at what database extension it is using. i recommend that you convert your existing database specific code to use the much simpler and better designed PDO extension.
-
you would use a typeahead/autocomplete/autosuggest input field, using ajax to get a list of matching people, that the user can then click on one to select it.
-
Possible to have a single MySQL query for multiple items?
mac_gyver replied to wrybread's topic in PHP Coding Help
you should have a category table, with id and name columns. this would define the different categories of items. the item table would have id, category_id, name, description, and any other columns needed to define each item. to display the category menu you would query the category table to get the category data that you want in the order that you want it, then loop over the result of this query to produce the category menu. if someone clicks on one of the category menu links, the category id in the link would be used to query for and display the items matching that category. -
I'm gusseting the posted picture is after you have submitted the form? after you set php's error_reporting to E_ALL and display_errors to ON, you should find the reason for that problem. here are a ton of coding practices that will help organize and simplify the code - the code for any page should be laid out in this general order - initialization post method form processing get method business logic - get/produce data needed to display the page html document some specific points for the posted code - use 'require' for things your code must have. include/require are not functions. the () around the path/filename don't do anything and should be left out. don't echo large amounts of static html. drop out of php mode and put the html inline. if you use php's short open-echo tag and a closing tag around a value, you can output variables in the html document using <?=$var?> don't escape double-quotes inside a php double-quoted string. simply use single-quotes inside the string. don't unnecessarily switch out of and back into php mode. just stay in php mode. don't use post method forms for navigation. use href/links. your markup is out of date. you need to validate the resulting web pages at validator.w3.org because this entire page requires the current user to be an administrator, preform the user level test once, near the top of the code and take an appropriate action if the user isn't an administrator. to get a form to submit to the same page it is on, simply leave out the entire action='...' attribute. you need to store the customer first and last names in separate columns. as a more advanced programming subject, if you have more than 2-3 form fields, you need to dynamically validate and process the form data and dynamically produce the form fields, instead of writing out code for every possible field. some points for the post method form processing code - don't attempt to detect if the submit button is set. there are cases where it won't be. instead, detect if a post method form was submitted. keep the form data as a set in a php array variable, such as $post or $data, then operate on elements in this array variable throughout the rest of the code. trim all the input data before validating it, mainly so that you can detect if all white-space characters were entered. once you do item #2 on this list, you can trim all the data using one line of code. validate all the now trimmed input data, storing user/validation errors in an array using the field name as the array index. after the end of the validation logic, if there are no errors, use the submitted form data. use a prepared query to prevent any sql special characters in value from being able to break the sql query syntax. if it seems like using the mysqli extension is overly complicated and inconsistent, it is. this would be a good time to switch to the much simpler and better designed PDO extension. if an insert/update query can produce duplicate data errors, you need to test for and handle this in the query exception handling for the query and setup a message for the user (add it to the array holding the user/validation errors) letting them know what was wrong with the data that they submitted. after using the submitted form data, if there are no errors, perform a redirect to the exact same URL of the current page to cause a get request for that page. this will prevent to browser from trying to resubmit the form data should that page get browsed back to or reloaded. to display a one-time success message, store it or a flag value in a session variable, then test for this session variable, display the message, and clear the session variable at the appropriate location in the html document. if there are errors, the code will continue on to redisplay the html document, where you will test for an display any errors, either all at once or individually adjacent to the field they correspond with, and populate the form fields with any existing data so that the user doesn't need to keep reentering values over and over. any dynamic value you output in a html context needs to have htmlentities() applied to it to help prevent cross site scripting.