Jump to content

mac_gyver

Staff Alumni
  • Posts

    5564
  • Joined

  • Days Won

    200

Community Answers

  1. mac_gyver's post in Php mysql edit data was marked as the answer   
    the key to updating an existing row or inserting a new row is the existence or absence of an id (autoincrement primary index) in the form data.
    if your database table doesn't already have an id/autoincrment column, add it. when you query to get the existing data to edit, add this column to the SELECT ... list (you should actually list out the columns you are selecting, rather than use *). output the id in a hidden form field. in the form processing code, if the id input is a true value, execute the code for an UPDATE query. if it is not a true value, execute the code for an INSERT query.
    to handle both having existing data to edit or no data, you should have an intermediate array variable, such as $post, that will initially hold any existing data that you fetch from the SELECT query, then inside the post method form processing code be assigned a trimmed copy of the $_POST form data. in the form value attributes, use php's null coalescing operator (??) to output the corresponding $post value or an empty value -
    Energie: <input type='text' name='Energie' value='<?=$post['Energie'] ?? ''?>'><br>  
  2. mac_gyver's post in Need Help tp simplify a function. was marked as the answer   
    assuming the function code already exists and you don't want to change it, you can use php's splat ... operator to call the function with an array of values that will get expanded into the individual input parameters.
    $gift_fields = [77, 80, 65, 66, 67, 83, 74, 87, 88, 90, 92]; $params = []; foreach($gift_fields as $field) { $params[] = $form_data['field'][$field]; } echo SpecificGifts(...$params); if you rewrite the function code to accept and operate on elements of a single array input parameter, you would change the last line to - echo SpecificGifts($params);
  3. mac_gyver's post in Need Help with PHP Function - newbie here was marked as the answer   
    $form_data doesn't exist inside the function (there would be php errors.) 
    you could actually just define the function to accept an array of data as the input and call the function with $form_data['field'][77] as the input parameter. this will allow the processing to be applied to any array of data, not hard-coded for $form_data['field']...
  4. mac_gyver's post in Match issue with /u switch was marked as the answer   
    substr() deals with single byte characters. try mb_substr()
  5. mac_gyver's post in Error 405 Not Allowed nginx was marked as the answer   
    i suspect the error is due to exceeding some limit at your free/cheap web hosting -
    you might ask their support group.
    already stated -
     
  6. mac_gyver's post in "SQL LIKE Keyword" search not functioning as it should was marked as the answer   
    the ? place-holder that's put into the sql query statement is only the ? character, no single-quotes, no wild-card characters. any wild-card characters go around the value you are supplying in the execute() call.
    you should also be using a method = 'get' form when performing a search and to get the form to submit to the same page it is on, simply leave the entire action='...' attribute out of the form tag.
    also, Don't Repeat Yourself (DRY.) use one single search form. to select which type of search, use either a select/option menu or radio buttons.
    the serach form should be 'sticky' and repopulate the form fields with any existing search inputs and use css instead of in-line styling.
  7. mac_gyver's post in GET form being posted to "index.php" every time / not doing what expected was marked as the answer   
    did you not read the reply in the existing thread for this task?
    anyways, the form field values for a get method form will replace any get parameters you try to put on the end of the url in the action='...' attribute. to supply 'additional' get parameters, you would need to use hidden form fields.
  8. mac_gyver's post in search for unknown number in a string? was marked as the answer   
    $string = 'Joe has 5 large apples'; // find any digit(s) in the string if(preg_match('!\d+!', $string, $matches)) { print_r($matches); // result in $matches[0] } else { echo 'no number found'; } // find digit(s) with the specific before/after text if(preg_match('!Joe has (\d+) large apples!', $string, $matches)) { print_r($matches); // result in $matches[1] } else { echo 'no number found'; }  
  9. mac_gyver's post in Upgrade from php 7 to 8 broke class code was marked as the answer   
    i just tried the code, and there is one php version difference. a method named the same as the class is no longer automatically called when an instance of the class is created. you must specifically name the method __construct. change function PicSQL($DBName = ""){ to function __construct($DBName = ""){
  10. mac_gyver's post in Login Form Username / Password Values was marked as the answer   
    @Barand, the OP is using PDO.  bindValue(), PDO::PARAM_STR, and errorInfo() are all PDO elements.
    the error you are getting, assuming that php's error_reporting is set to E_ALL, means that the query didn't match a row. you need to test when you fetch the row if anything was fetched. if a row was fetched, it means that the WHERE clause was true and there's no need to test in the current php code if the form username matched the fetched username. however, if no row was fetched, this indicates that the WHERE clause was false. that's the condition where you would setup the login failure message.
    as to why the query isn't matching a row, and isn't producing an error, are you sure the username/password that you used was correct? when you executed the query directly in phpmyadmin, did it contain the sha1() password hash or did it directly have the password in it?
    when you make the database connection are you -
    setting the character set to match your database tables? setting the error mode to exceptions setting emulated prepared queries to false setting the default fetch mode to assoc as to the link you posted, don't take a backward step and use the mysqli extension. the PDO extension is the best choice, though you can simplify how you are using it, and whatever is causing the current code to not match a row will still be a problem with a different database extension.
    btw - you should be using php's password_hash() and password_verify(). the simple sha... hashing functions where never intended for security purposes. you should also only store the user id (autoincrement primary index) in the session variable to identify who the logged in user is. you should query on each page request to get any other user information, such as the username or user role/permissions. this insures that any changes made to these values will take affect on the very next page request.
     
  11. mac_gyver's post in Call to undefined function Login_sucess() was marked as the answer   
    you have actually been give the answer -
    don't put function definitions inside of other function definitions.
  12. mac_gyver's post in Calendar paging was marked as the answer   
    the operation is to simply either add one day or subtract one day from the current date -
    <html> <head> <title></title> </head> <body> <form method="post" name="f1"> <?php error_reporting(E_ALL); ini_set('display_errors', '1'); // Default dates $today = date('Y-m-d H:i:s',strtotime('today')); // Check the form was submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { $today = $_POST['today']; if($_POST['Submit'] == 'Tomorrow'){ $today = date('Y-m-d H:i:s', strtotime($today . '+1 days')); } if($_POST['Submit'] == 'Yesterday'){ $today = date('Y-m-d H:i:s', strtotime($today . '-1 days')); } } ?> <table border="1" align="center" width="100%"> <input type="hidden" name="today" value=<?php echo $today;?>> <tr> <td align="center" width="20%"><input type="Submit" name="Submit" value="Yesterday"></td> <td align="center" width="60%"> <?php echo $today;?></td> <td align="center" width="20%"><input type="Submit" name="Submit" value="Tomorrow"></td> </tr> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { //<!--- Form view ---> echo"<tr><td>query</td></tr>"; } else{ //<!--- Default view ---> "<tr><td>default</td></tr>"; } ?> </table> </form> </body> </html>  
  13. mac_gyver's post in Problems saving to sql after updating to PHP 7.3 was marked as the answer   
    It's possible that some of the data values that are not present for a one-way trip don't have an acceptable default value and/or are not allowed to be a null value in the database table definition, and the database server mode is now set to strict mode, which will cause an error for those columns, rather than truncating data to the nearest min/max value.
    this code doesn't have any (useful) error handling for the database statements that can fail and the one place it does have some, won't work, because the connection variable is missing from the msyqli_error(...) call. the easiest way of adding error handling for all the database statements, without adding logic at each statement, is to use exceptions for database statement errors and in most cases let php catch and handle the exception, where php will use its error related settings to control what happens with the actual error information (database statement errors will get displayed/logged the same as php errors.) to use exceptions for errors for the mysqli extension, add the following line of code before the point where you make the one/single/first connection -
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); i hope that this code is just part of an assignment and is not on a live/public server, because it has no protection against sql special characters in the data values from breaking the sql query syntax, which is how sql injection is accomplished. you should be using prepared queries when supplying external, unknown, dynamic values to a query when it gets executed.
     
  14. mac_gyver's post in Give Image to HTML through PHP-doesn't work was marked as the answer   
    that opens the file through the file system, not the web server, so, any links in the html will also be read through the file system. you must use a url to the html file, such as http://localhost/phptest.html. this will cause the src="phptest.php?id=1" attribute to be read through http://localhost/phptest.php?id=1
  15. mac_gyver's post in Call to a member function query() on null was marked as the answer   
    https://www.php.net/manual/en/language.oop5.visibility.php
  16. mac_gyver's post in Inserting csv records into a mysql table was marked as the answer   
    check is a reserved work and should not be used as a column name. either use a different name for that column or you must enclose the column name in back-ticks to cause it to be treated as an identifier.
  17. mac_gyver's post in Session variables are not being read was marked as the answer   
    are you using full <?php opening tags, per the problem in one of your previous threads? https://forums.phpfreaks.com/topic/311034-includes-not-being-displayed-on-page  how about the other improvements made in that thread? you seem to have gone backwards.
     
  18. mac_gyver's post in php sql syntax error was marked as the answer   
    the WHERE clause in the sql statement is probably FALSE, because you are still checking if the number 104 is equal to some value.
     
    before you go any farther on your programming journey, don't use numbed or letter-numbed database columns or variables. you won't get very far, because people you are expecting to look at your code/queries won't waste their time trying to figure out what your code and queries are doing.
     
    your code should be self-documenting. anyone reading a section of your code should be able to figure out what it is doing. database columns and variables should be named as to the meaning of the data in them.
     
    your code is testing if the query execute without any errors. that doesn't mean that the query affected any row(s). if you want to specifically know if an row was updated, check the number of affected rows. if you are using the php mysqli extension, see the ->affected_rows property.
     
    you should also be hashing passwords (see php's password_hash() and password_verify() functions) and you should not put data directly into sql query statements. use prepared queries when supplying data to an sql query statement.
  19. mac_gyver's post in Call to a member function query() on null was marked as the answer   
    you are trying to convert procedural mysqli to OO mysqli, which will take a bunch of time. when you get around to using prepared queries, you will have to convert the code again, because the programming interface for non-prepared mysqli queries and prepared mysqli queries is completely different.
     
    save yourself the time and just convert the code once, to use PDO. the programming interface for non-prepared and prepared PDO queries is the same. i recommend that you review your thread where you asked if you should switch to PDO.
  20. mac_gyver's post in need help with login script was marked as the answer   
    if this is your "working on past hosting" code, it never worked correctly.
     
    the (miss named) viewProtectedArea() method returns an array of row(s). in order to reference the zero'th/only row, you would need to reference $user[0][...].
     
    since the query will at most match one row, you should use the ->fetch() method.
  21. mac_gyver's post in A really weird update problem was marked as the answer   
    the error message is probably coming from some other query in your code, perhaps after the one in question, if you don't for example have an exit; statement after a header() redirect.
     
    in any case, it would take seeing all your code, less any connection credentials, to be able to specifically help find the cause of the problem.
     
    btw - the old and obsolete php mysql extension has been removed from the latest php version and you should be updating your code to use either the php PDO extension (which is the best choice) or the php mysqli extension (turns out is not a good choice at all), and you should not be putting data values directly into the sql query statement, but using a prepared query, with place-holders in the sql statement for the data values, then supply the data when you execute the query.
     
    updating the code will also let you use exceptions to handle the database statement errors, so you can simply enable exceptions for the extension you end up using, let php catch the exception, where it will use its error_reporting, display_errors, and log_errors settings to control what happens with the actual error information, and you can then eliminate any error handling logic you have in your code, thereby reducing the amount of code you have to convert.
  22. mac_gyver's post in newbie getting unexpected $end was marked as the answer   
    the problem is because the closing heredoc _END; identifier doesn't start in the first column in a line.
     
    there's big red warning in the php.net string/heredoc documentation -
     
     
  23. mac_gyver's post in How can I select sections of a line to be saved as variables in a graphical way on a website? was marked as the answer   
    if you want to do a 'click' interface, you would use javascript, but the data you need to produce and submit needs to be similar/same to what is given in the example above (you could have a start and end instead and calculate the length when the data is received by the php code.)
     
    if you output each character of the sample string in its own span, with a common name + numerical id that indicates the position, when you click on a character, you can get numerical position from the id of the DOM element that was clicked. if there is no currently selected id, you would start a 'pick' sequence. the first pick would give the start value. a second pick would give the end value and you would calculate the length from the difference between the end and start values. you would populate the form fields with these values. you can either use a select/option menu to pick a name or click on list of displayed names to populate the name form field. once you have picked values for all three fields in a set, the logic would 'reset' and any picks would start the process for the next set of values. you can change the color of any picked character when it is clicked on and you can change all the characters between the start and end positions if you want.
  24. mac_gyver's post in Is there a cleaner way of doing this without all the if/elseif statements was marked as the answer   
    what you doing is mapping input values to a set of output values. rather than use conditional logic to do this, just store the data somewhere, addressed/indexed by the input value. a database would be the best choice, or for a smaller set of data, you can use an array.
     
    once you have the data stored, you can perform any calculation when you 'query' for the matching data, either in an sql query, if the data is stored in a database, or using php array functions, if the data is stored in an array.
     
    some additional advantages of storing the data in a database, you would be able to create an administrative interface that allows the data to be created/edited by someone who doesn't have any programming knowledge and you can display the various levels to the users simply by querying for the data and displaying it.
  25. mac_gyver's post in issue in inserting data from dropdown into mysql table was marked as the answer   
    actually, no, it's not. there are two problems with the form -
     
    1) the value attributes, that have already been pointed out.
     
    2) the name you have given the submit button is the same as the select field name and only the last field with the same names will be used, so, you are getting the submit button value, which there is none, rather than the select field value. use a different name for the submit button.
     
    however, you need to do some other things -
     
    1) the value you use for the options should be an id (auto-increment column) from tbl_paramhead, not the text/label string, because you should store an id in any table holding data related to a tbl_paramhead selection.
     
    2) in your form code, the sql query does not have any external data being supplied to it, and using a prepared query here is wasting time typing and executing code that isn't doing anything useful. change the ->prepare() and ->execute() calls to just $stmt = $pdo->query($sql); the rest of the code using the result from the query will remain the same.
     
    3) in your form processing code, you have missed a point of using a prepared query. you do not put data values directly into the sql query statement when using a prepared query. you put place-holders in the sql query statement for the values (without any single-quotes around the place-holders), then you supply the data values when you execute the query.
     
    also, in your form processing code -
     
    4) the if($_SERVER["REQUEST_METHOD"] == "POST") conditional test should come first and/or be the only test you need. if your form processing code will only handle a single form, there's no need for any additional logic.
     
    5) you need to validate all submitted form data before using it. if the text field is empty or no select option was picked, you should not run the INSERT query. if you use an array to hold he validation error messages, you can just test if the array is empty to dected if there are no validation errors.
     
    6) there's no good reason to write out line after line of code that is just copying variables to other variables. the original variables are perfectly fine to use in the rest of the code. what happens if your form has 10 fields? are going to write out 10 lines of code copying each of the $_POST variables to other variables? the answer to this question should be no.
     
    if you do have a need to copy an array to other variables, such as if you are making a trimmed copy of the data, you can do it using a single statement,
     
    7) if you put the form processing code and the form on the same page, you can display any validation errors when you display the form and you can populate the form fields with the submitted values when there is an error, so that the visitor doesn't need to keep filling in/selecting field values, they only need to correct the fields that have errors.
×
×
  • 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.