Jump to content

garyed

Members
  • Posts

    176
  • Joined

  • Last visited

Posts posted by garyed

  1.  I thought about marking this thread as solved but I would be lying because I still am in the process of trying to solve all my errors. 

    It seems rather ridiculous that one version of php will work with errors turned off while a newer version won't. 

    I've already fixed over a hundred errors in php 8.x & things are looking worse than before I started. 

    I can go back to php 7.4 & the program will work flawlessly. If it's not an undefined variable error, it's a  string & int error or something else. 

    It's frustrating because I spent years writing this program & just learned as I was going along.  It's been working fine for 10 years & now the upgrade to php 8.x has killed it.   

    I've got over 1000 variables I'm dealing with & hundreds of calculations so it's not a simple task.  

     

  2. 1 hour ago, mac_gyver said:

    i was able to make the code repopulate the fields/select-option, when navigating around, using 3 lines of code and one conditional test, added to the get method business logic section. i won't post the code i came up with because it is probably not how your application is determining which step/page it is on. you could also just merge the successful $post data into the $_SESSION['step'] array inside the post method form processing code, then when the page is visited without any $post data, copy the whole $_SESSION['step'] array back into $post (which i just tested and it works as well.)

    if you want help with anything your application is or is not doing, you must post enough of the code so that someone here can reproduce what it is doing.

    I appreciate the help. It's a lot of good information that I've got to process. 

     I'm a little slow at times but i'll eventually get it. 

  3. 2 hours ago, mac_gyver said:

    for the activity you have shown in this thread and using the previously given programming practices about how to organize, cleanup, and code your form processing and form,  a lot of this typing of code goes away, you would end up with the following -

    <?php
    /*
    put any error relating settings in the php.ini on your system
    you may have a need to store the result from some step in session variable(s), but by unconditionally storing each piece of post data, you are doubling the amount of code needed. only store the end result. Keep It Simple (KISS.)
    to dynamically generate a select/option list, you would not use discrete variables for each value and write out logic for each option. you would instead have an array of the values, then loop to dynamically build the options.
    in html5, an empty action='' attribute is not valid. to get a form to submit to the same page it is on, leave the action attribute completely out of the form tag.
    you should validate your resulting web pages at validator.w3.org
    */
    
    // initialization
    session_start();
    
    $post = []; // an array to hold a trimmed working copy of the form data
    $errors = []; // an array to hold user/validation errors
    
    // post method form processing
    if($_SERVER['REQUEST_METHOD'] === 'POST')
    {
    	// trim all the data at once
    	$post = array_map('trim',$_POST); // if any of the fields are arrays, use a recursive trim call-back function here instead of php's trim function
    
    	// validate inputs
    	if($post['owner'] === '')
    	{
    		$errors['owner'] = 'The owner is required.';
    	}
    	if($post['renter'] === '')
    	{
    		$errors['renter'] = 'The renter is required.';
    	}
    	if($post['state'] === '')
    	{
    		$errors['state'] = 'The state is required.';
    	}
    	
    	// add validation for other inputs here...
    
    	
    	// if no errors, use the form data
    	if(empty($errors))
    	{
    		// if this is a step in a multi-step process, store the now validated data in a specific session variable
    		$_SESSION['step'][1] = $post;
    	}
    
    	// if no errors, success
    	if(empty($errors))
    	{
    		// if you want to display a one-time success message, store it in a session variable here,
    		// then test, display, and clear that session variable at the appropriate point in the html document
    		$_SESSION['success_message'] = 'Some success message for this step in the process';
    		// redirect to the exact same url of the current page to cause a get request for the page
    		die(header("Refresh:0"));
    	}
    }
    
    // get method business logic - get/produce data needed to display the page
    // query to get the states in the order that you want them
    
    // fake some values
    $states = [];
    $states[]="Maine";
    $states[]="Texas";
    
    // html document
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
    	<title>Form processing/form example</title>
    </head>
    <body>
    
    <?php
    // display and clear any success message
    if(isset($_SESSION['success_message']))
    {
    	echo "<p>{$_SESSION['success_message']}</p>";
    	unset($_SESSION['success_message']);
    }
    ?>
    
    <?php
    // display any errors
    if(!empty($errors))
    {
    	echo "<p>".implode('<br>',$errors)."</p>";
    }
    ?>
    
    <form method="post">
    <label>Owner: <input type="text" style="width:255px;" name="owner" value="<?=htmlentities($post['owner']??'',ENT_QUOTES)?>"></label><br>
    <label>Renter: <input type="text" style="width:255px;" name="renter" value="<?=htmlentities($post['renter']??'',ENT_QUOTES)?>"></label><br>
    <label>State: <select name="state">
    <option value="">select state</option>
    <?php
    foreach($states as $state)
    {
    	$sel = isset($post['state']) && $post['state'] === $state ? 'selected' : '';
    	echo "<option value='$state'$sel>$state</option>";
    }
    ?>
    </select></label><br>
    <input type="submit">
    </form>
      
    <?php
    // note: if you have the need for a 'clear' session function, add that as a separeate post method form, with a hidden field with a value to indicate that action
    // then test for that action value in the form processing code to clear the session data
    ?>
    
    <?php
    // display the content of the session
    if(!empty($_SESSION))
    {
    	echo '<pre>'; print_r($_SESSION); echo '</pre>';
    }
    ?>
    
    </body>
    </html>

    and as already mentioned, if you have more than 2-3 form fields, you should use a data-driven design, where you have a data structure (database table,  array) that defines the expected form fields (for each step), validation rules, and processing for each field, then dynamically validate and process the form data, rather than to write out bespoke logic for each field.

    I'm tried your code but it still doesn't insert the session data in the fileds & dropdown when I leave & return. 

    I'm not sure what I'm missing but the only thing I know to do is to add something similar to what I already have to get it to work. 

  4. 1 hour ago, ginerjm said:

    Way too complicated.  I tried to rewrite this but got lost in your logic and your very convoluted coding methods.

    Resolve your input issues before creating your html code.  Get the values you want to use by returning it from the function and then use that value in your html so that you don't have to use a php tag in the middle of your html.  Very bad coding IMHO.

    And I strongly recommend using heredocs;  Here is an example of how it works for you:

    $sel1 = $sel2 = '';
    $value1 = get_value(???);
    if ($value1 == $state1)
    	$sel1 = "selected='selected'";
    $value2 = get_value(???);
    $dropdown=<<<heredocs
    <select name='list'>
    <option value=''>Select a State</option>
    <option value='$value1' $sel1>$value1</option>
    <option value='$value2' $sel2>$value2</option>
    </select>
    heredocs;

    Now use the $dropdown var in your html output area.  You can see how I avoided leaving php mode and let the heredocs combine the assgned values with the html.  Not sure my code makes sense (as your code was confusing me too) but this shows you a cleaner way of coding.

    If I read it correctly you have some session values that are to default your desired values when they are not in the POST'ed input.  You do know that POST values from text inputs are always set so you don't have to do an isset on those parts.  They may be blank but at least they are present as blanks.

    Thanks,

    I'll check into "heredocs". I never even heard of it before you just mentioned it. 

    I'm also going to study your code until I understand it better.

    What I'm really trying to do is to havel all 50 states in the dropdown menu from a MYSQL database & put whichever one is selected into the session. Then change the page to perform another task then return to the page & have the state from the session be already selected upon return.     

  5. It seems to work fine but I would like to hear what you guys who are more versed in php think.

    In my previous post I was trying find a way to hide the errors but I really want to get things right this time.

    This is a sample code that I'm using as a test but on my site I'm going to be pulling my variables off a database & using a while loop to fill in all 50 states.   

    <?php 
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    session_start(); // Starts session & uses function to keep data  */
    function get_value($var)
    {
    // this will check your session if it's not empty and you send an empty post
    if ($_POST[$var]!="" || (!empty($_SESSION[$var]) && $_POST[$var] === '')) { 
       $_SESSION[$var]=$_POST[$var];   }
    if (isset($_SESSION[$var])){ return $_SESSION[$var];} else{ return $_POST[$var];} 
    }
    if(!isset($_POST['submitter'])) {$_POST['submitter']="anything"; }  // initialize to avoid Undefined array key error
    ?>
    <form name="test" action="" method="post"> 
    <input type="text" style="width:255px;" name="owner" value="<?php if(isset($_POST['owner'])) {echo get_value('owner'); } else { if(isset($_SESSION['owner'])){ echo $_SESSION['owner'];} } ?>"> <br>
    <input type="text" style="width:255px;" name="renter" value="<?php if(isset($_POST['renter'])) {echo get_value('renter');}else { if(isset($_SESSION['renter'])){ echo $_SESSION['renter'];} } ?>"> <br>
    <select name="state" >  <option value=""> select state </option>
    <?php
    $state1="Maine" ;
    $state2="Texas" ;
    ?>
    <option value="<?php echo $state1; ?>"  <?php  if(isset($_POST['state'])) { if(get_value('state') == $state1) { echo 'selected="selected"'; } }  else { 
    if(isset($_SESSION['state'])){ if ($_SESSION['state']==$state1) { echo 'selected="selected"'; } } }  ?>  > Maine </option>   
    <option value="<?php echo $state2; ?>"  <?php if(isset($_POST['state'])) {if (get_value('state')==$state2) { echo 'selected="selected"'; }}  else { 
    if(isset($_SESSION['state'])){ if ($_SESSION['state']==$state2) { echo 'selected="selected"'; } } }  ?>  > Texas </option>  
    </select> <br> <br> <br>
    <input type="submit" value="submit"> &nbsp; &nbsp; <input name="submitter" type="submit" value="clear session"><br>
    </form>
    <?php
    if ($_POST['submitter']=="clear session") { echo $_POST['submitter']."<br>"; session_destroy(); };
    print_r($_SESSION);
    ?>

     

  6. Thanks for the ideas, 

    I can get rid of the errors by initiating $_POST['submitter'] & testing if $_POST['owner'] is initiated but then my session variable gets lost when leaving the page. 

    Keeping the session variable is where my problem is.

    if(!isset($_POST['submitter'])) {$_POST['submitter']="hello"; } // insert before using $_POST['submitter']
    // change value of input to this:
    value="<?php if(isset($_POST['owner'])) {echo get_value('owner'); }?> " 

    The session variable is really not lost but it doesn't appear in the input field after leaving the page & coming back to it which is the problem especially if I'm dealing with a lot of inputs.  

     

  7. Follow up with code:

    I didn't know if i should post this as a separate thread or not since the question is about fixing errors instead of covering them up.

    I'm trying to figure out how to get rid of the errors in this code because it's very similar to my site with a lot more inputs & I'm stumped.

     

    <!DOCTYPE html>
    <html>
    <head> </head>
    <body>
    <?php 
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    session_start(); // Starts session & uses function to keep data  */
    function get_value($var)
    {
    // this will check your session if it's not empty and you send an empty post
    if ($_POST[$var]!="" || (!empty($_SESSION[$var]) && $_POST[$var] === '')) { 
       $_SESSION[$var]=$_POST[$var];   }
    if (isset($_SESSION[$var])){ return $_SESSION[$var];}else{ return $_POST[$var];} 
    }
    ?>
    <form name="test" action="" method="post"> 
    <input type="text" style="width:255px;" name="owner" value="<?php echo get_value('owner'); ?> "> <br>
    <input type="submit" value="submit"> &nbsp; &nbsp; <input name="submitter" type="submit" value="clear session"><br>
    </form>
    <?php
    if ($_POST['submitter']=="clear session") { session_destroy(); }
    print_r($_SESSION);
    ?>
    </body>
    </html>

     

  8. Thanks for the encouragement, 

    I know I'll get it done but it's just going to take time. I just do this as a hobby & the code on the site in question I wrote about 10 years ago. When you don't do it everyday, it's easy to forget how you did something that far back.  

     I was just hoping I could fool php8.0 like i did 7.2 for a little while longer :) 

  9. 35 minutes ago, requinix said:

    Your site does not work by turning off errors. The problems are there and need to be fixed regardless of whether you can see error messages about it or not.

    The only thing that the PHP 8 upgrade did was change error display settings. These problems, like "trying to access array offset on value of type null" and "undefined variable", have been there for a while. You just didn't know about it until now.

    Frankly, "thousands of lines of code" is not that much. Each error message tells you where the problem is - all you have to do is go to the code on that line and, most likely, make a small change.

    I understand what you're saying & I definitely want to straighten the code out & get rid of all the errors properly. 

    I had the same problem about a year ago,when my webhost upgraded the php version to 7.4. 

    I turned off the errors to keep the site up & running & started trying to fix things but I just gave up after a couple days. 

    I got lazy since everything was still working & just forgot about doing anything about the errors.

    I should have fixed things while I had the time but now I'm paying the price for procrastinating.

     

  10. I've got about a thousand of them :

    Undefined array key ... 


    Trying to access array offset on value of type null
     mysqli_real_escape_string(): Passing null to parameter #2 ($string) of type string is deprecated 
    Undefined variable ....
    Fatal error: Uncaught TypeError: Unsupported operand types: 

    Then it gets even worse because all of those errors can go away by turning off errors but then when you go further into the site it will lock up completely & go blank.

    If I keep the errors turned on then I can't get to the part of the site where it locks up to see what error is causing the lockup. 

    It's actually a very involved load calculation sight with a lot of inputs & a lot of people use it & I want to keep it going.  

  11. I have tried investigating but have come up dry. 

    Error 500 is pretty generic & doesn't give any specific details & I don't know where to start looking.

    Even if it's a permission issue I still don't know what to do to fix it.   

    I've tried a couple edits on config files the other day but they didn't work & I can't even remember what I tried now. 

    My next step was to copy all the phpmyadmin config files while I have 7.2 running & then compare them with the config files with 8.1 running.

    That's probably a waste of time but I figured before I do that I would post here & see if anyone was familiar with the problem.  

  12. My webhost has upgraded from php 7.4 to 8.0 & I have quite a few pages on different sites that just will not work with the upgrade. 

     I've been masking all my errors in 7.4 by using "display_errors = Off " in my php.ini & that's done the job until now but the pages will not work in 8.0 

    I guess all the bad code is catching up to me but we're talking about thousands of lines of code that I wrote years ago & it's going to take a long time to correct.

    I don't want my sites to be down so I'm paying a monthly fee to my webhost (1and1) to keep supporting php7.4 & I don't know how long that will last.

    I've also tried putting this in my pages to no avail:       

    error_reporting(E_ALL ^ E_NOTICE);

    I'm just trying to buy time until I can get things right so I'm wondering if anyone has any ideas for me in the mean time.

    I do test all my new code for errors as I'm going along but all my old code was never tested for errors. 

    This reminds me of what I was told about people who use computers a while back. There are two types, those who backup & those who will backup

  13. 7 hours ago, mac_gyver said:

    there are multiple ways of accoupling a task. you would need to post what you tried, along with the input data that 'worked'. 

    If I use either of these statements, the result is the same.

    Joe has ([\d.]+) large apples
    Joe has (\d.+) large apples

    It doesn't seem to matter whether I put the square brackets in or not. 

    Are those brackets are there for a reason beyond the scope of the usage in this particular statement?   

  14. On 7/14/2022 at 9:47 PM, kicken said:

    What you should do is spend a little time learning regular expressions, and play with them to find a working pattern.

    The pattern \d matches only digits (ie, 0 - 9).  As such, it'll only match numbers the consist of simply digits (no decimals, no grouping characters).

    If you want to match decimals, you'd need to add . to the list of allowed characters.  You can do that by specifying a set of possible characters using [ ].

    Joe has ([\d.]+) large apples

    If you needed groups, you could likewise add , to the set.

    I have been learning & experimenting with regular expressions as you suggested & was just curious as to why you use the square brackets inside the curly brackets. 

    I've found that whether I use the square brackets or not, the result is the same.  Is it optional or is there a specific reason why they should be used?

  15. 2 hours ago, kicken said:

    It's not just the decimals that you didn't consider / include in the problem description.  If decimals were the only thing, then Barand's solution would have still worked fine as it was ok with decimals. You also should have considered / mentioned this part from the beginning:

    So you were not just looking for a number in a string, you were trying to find a specific number in a string that possibly contains multiple numbers.

     

    It's good to try and simplify the problem in general, you just need to be careful not to simplify it too much.

    I see what you're saying now. 

  16. 1 hour ago, mac_gyver said:

    @garyed, this is why you must address all the actual extents and limits of a problem, upfront, so that you don't waste time on partial solutions. it's not possible to sneak up on programming, because programming is like a BS detector.

    My bad, I was trying to make my example simple to get across what I was trying to do & never even considered that the answer could be different if there were decimals involved. 

    Hopefully I'll be a little more thorough next time, but I really appreciate the help from you guys here.  

  17. 2 hours ago, kicken said:

    What you should do is spend a little time learning regular expressions, and play with them to find a working pattern.

    The pattern \d matches only digits (ie, 0 - 9).  As such, it'll only match numbers the consist of simply digits (no decimals, no grouping characters).

    If you want to match decimals, you'd need to add . to the list of allowed characters.  You can do that by specifying a set of possible characters using [ ].

    Joe has ([\d.]+) large apples

    If you needed groups, you could likewise add , to the set.

    Thank you, 

    That was what I needed & I definitely do need to spend a lot more time learning those expressions. 

    I know it's wrong but I usually learn backwards & try to find a solution to a problem when i run into one instead of learning the basics first.  

  18. 1 hour ago, Barand said:

    Bullsh*t. Have you even tried it?

    Example...

    $strings = [  "Joe has 5 large apples",
                  "Joe has 5.25 large apples",
                  "Joe has 500 large apples"
               ];
    
    foreach ($strings as $str) {          
        $number = current( array_filter(explode(' ', $str), 'is_numeric' ) ) ;
        echo "$str | $number<br>";
    }

    image.png.366c291c79693a10fb8004ca21556167.png

     

    I appreciate your help but I don't think that solves the problem. I just need to find one specific unknown number in a specific string out of a huge string with multiple numbers. 

    The example of "Joe has (x) large apples" would be the line I'm searching for in like 1,000 lines of code with multiple numbers where (x) is an unknown number. 

    Mac_gyver's solution worked because it took the specific string where the unknown number was inside it & pulled it out. 

    The only problem is that it would only pull out a whole number & the decimal part was lost. 

    Your solution would come up with too many numbers that I would still have to find a way to narrow it down to the specific string that holds the correct number.   

  19. 13 minutes ago, Barand said:

    Try my solution with 5.25

    Your solution would work if I knew the number in the string but the problem is that don't know the number that will be in the the string that I'm searching for.

    Basically I'm searching for the number inside a specific string that is inside a larger string. 

  20. Well I thought everything was solved but i found that (\d+) only works on whole numbers. 

    I didn't think it would matter if the number had a few decimal points but I was obviously wrong.  

    If there is a decimal like 5.5 or 5.25 then it will only pick up the 5 & not the rest of the number.  

×
×
  • 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.