Jump to content

Barand

Moderators
  • Posts

    24,511
  • Joined

  • Last visited

  • Days Won

    819

Posts posted by Barand

  1. 1 hour ago, BIGB185 said:

    mysql_connect.php code:

     

    1 hour ago, BIGB185 said:

    require('mysqli_connect_registrar.php');

    Are you sure you know the name of the file?

    (Use the code <> button in the toolbar when posting code)

     

    EDIT: Stop using "@" to suppress errors - you want to know when things have gone wrong

  2. Are you trying to add a new user to the table or update an existing user's data?

    Either way, it's wrong.

    • The query as it is would set every record to have identical contents as there is no WHERE clause to limit it to update a particular record.
    • If you want add a new user you need an INSERT query.

    You aren't doing any checking to confirm the query did actually work, you just assume it did and output a success message. Easiest way to check for errors is to add the following line of code just before the line that creates your mysqli connection...

    mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

     

  3. 20 hours ago, ginerjm said:

    If you had php error checking turned on you would probably be seeing a warning/notice concerning that session var.

    A variable is "empty" if it doesn't exist  so the code will avoid "undefined index" notices. It's also empty if it is null, so the second condition is superfluous.

    Adding var_dump($_SESSION['product']) gives the expected error but not that line.

    However, contrary to makamo66's experience, it does print "else test" so the problem is probably caused elsewhere in the code.

  4. This is my version of your script. Data is stored in "census.csv". The analysis results are dynamically updated as each new record id entered

    <?php
    const DATAFILE = 'census.csv';
    
    
    $counties = ["Hamilton, Oh", "Butler, Oh", "Clermont, Oh", "Warren, Oh", "Campbell, Ky", "Boone, Ky", "Kenton, Ky"];
    // defaults
    $hhcounty = '';
    $hhsize = 1;
    $hhincome = 0;
    $errors = [];
    $messages = '';
    $analysis = '';
    //
    //  HAS FORM BEEN POSTED
    //
    if ($_SERVER['REQUEST_METHOD']=='POST') {
        $hhcounty = $_POST['hhcounty'] ?? '';
        $hhincome = $_POST['hhincome'] ?? 0;
        $hhsize   = $_POST['hhsize'] ?? 0;
        if (!in_array($hhcounty, $counties)) {
            $errors[] = "Not a valid county/state";
        }
        if (!ctype_digit($hhsize) || $hhsize==0) {
            $errors[] =  "Not a valid household size";
        }
        if (!ctype_digit($hhincome)) {
            $errors[] =  "Not a valid income amount";
        }
        
        if ($errors) {
            foreach ($errors as $e) {
                $messages .= "<p class='err'>$e</p>\n" ;
            }
        }
        else {
            // data OK - save in csv file
            // (at this point we'd normally save to a database, but we don't have one)
            $fp = fopen(DATAFILE, 'a');
            $rec = [$hhcounty, $hhsize, $hhincome ];
            fputcsv($fp, $rec);
            fclose($fp);
            
            header("Location: #");
            exit;
        }
    }
    
    //
    // analyse data
    //
    $data = [];
    if (file_exists(DATAFILE)) {
        $fp = fopen(DATAFILE, 'r');
        while (list($hhc, $hhs, $hhi) = fgetcsv($fp)) {
            $data[$hhc][] = [ 'size' => $hhs, 'income' => $hhi];
        }
        fclose($fp);
    }
    uksort($data, function ($a, $b) {
                                   $x = substr($b, -2) <=> substr($a, -2);         // state DESC
                                   if ($x==0) return ($a <=> $b);                  // county ASC
                                   return $x;
                                });
    foreach ($data as $cty => $households) {
        $tothh = count($households);
        $totpov = count(array_filter($households, function ($v) {
                                                      return isPoverty($v['size'], $v['income']);
                                                   }));
        $pcpov = number_format($totpov*100/$tothh, 2) . ' %';
        $avincome = array_sum(array_column($households, 'income'))/$tothh;
        $avsize = array_sum(array_column($households, 'size'))/$tothh;
        $avgi = number_format($avincome, 0);
        $avgsz = number_format($avsize, 2);
        $analysis .= "<tr><td style='text-align: left'>$cty</td><td>$tothh</td><td>$avgsz</td><td>$avgi</td><td>$totpov</td><td>$pcpov</td></tr>\n" ;
    }
    
    /**
    * compare income agains threshold values for household size
    * 
    * @param int $num    - household size
    * @param int $inc    - income amount
    * @return boolean true if below threshold
    */
            function isPoverty($num, $inc)
            {
                $thresholds=[
                          1 => 12000,
                          2 => 18000,
                          3 => 25000,
                          4 => 30000,
                          5 => 40000
                        ];  
                if ($num > 5) $num = 5;
                return $inc < $thresholds[$num];
            }
    
    /**
    * build conty/state option menu
    * 
    * @param array $counties      array of values
    * @param string $current      current value
    */
            function countyOptions(&$counties, $current)
            {
                $opts .= "<option value=''>- select county, state -</option>\n";
                foreach ($counties as $c) {
                    $sel = $c==$current ? 'selected' : '';
                    $opts .= "<option $sel>$c</option>\n";
                }
                return $opts;
            }            
    ?>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Household Survey</title>
    <meta name="creation-date" content="10/13/2019">
    <style type="text/css">
        body    { font-family: verdana, sans-serif; font-size: 11pt;}
        label   { display: inline-block; width: 200px; font-weight: 600; padding: 8px;}
        fieldset{ padding: 16px; margin: 20px 50px;}
        .err    { font-style: italic; color: #F00; }
        table   { width: 80%; border-collapse: collapse; margin: 30px 50px; }
        th      { padding: 8px; background-color: #396; color: #FFF; }
        td      { padding: 4px 8px; text-align: right;}
        p       { font-size: 9pt; font-style: italic;}
    </style>
    </head>
    <body>
    <h1>Household Survey</h1>
        <p>As you enter records the table of analysis results below is updated</p>
    <fieldset>
    <form method="post">
        <label>County, State</label>
        <select name="hhcounty"><?=countyOptions($counties, $hhcounty)?></select><br>
        <label>Number in household</label>
        <input type="number" name="hhsize" value="<?=$hhsize?>" size="5"><br>
        <label>Household income</label>
        <input type="number" name="hhincome" value="<?=$hhincome?>" size="5"><br>
        <label>&nbsp;</label><input type="submit" name="btnSub" value="Submit">
    </form>
    <?=$messages?>
    </fieldset>
    <h3>Analysis of Data</h3>
    <table>
        <tr><th>County/State</th><th>Households</th><th>Average Size</th><th>Average Income</th><th>Below Poverty Line</th><th>Percent Below</th></tr>
        <?=$analysis?>
    </table>
    
    </body>
    </html>

    image.thumb.png.d5893c4a46bed846c69c5e0278069a26.png

     

  5. However

    If you are going to restructure your array then IMHO it would make more sense if you just had ...

    Array
    (
        [A] => Array
            (
                [1] => Array
                    (
                        [1] => 0
                        [2] => 0
                        [3] => 0
                        [4] => 0
                    )
    
                [2] => Array
                    (
                        [2] => 0
                        [3] => 0
                        [4] => 0
                    )
    
            )
    
    

    … where you can access a seat value with 

    $val = $srs[$section][$row][$seat];

     

    • Like 1
  6. I've just written a convert_array() function that uses that easier method

    $output = convert_array($srs);
    
    
    function convert_array($arr) {   
        $new = [];
        foreach ($arr as $rec) {
            $new['sections'][$rec['section_name']]['rows'][$rec['row_name']]['seats'][] = $rec['seat_name'];
        }
        return $new;
    }

     

  7. Perhaps you want something like this

        $srs = [];
        foreach (range('A', 'D') as $section) {
            $srs['sections'][$section] = ['rows' => []];
            for ($row = 1; $row < 3; $row++) {
                $srs['sections'][$section]['rows'][$row] = ['seats' => []];
                for ($seat = 1; $seat < 4; $seat++) {
                    $srs['sections'][$section]['rows'][$row]['seats'][] = $seat;
                }
            }
        }
        echo '<pre>', print_r($srs, 1), '</pre>';

     

  8. 45 minutes ago, ajetrumpet said:

    in PHP only

    • HTML?
    • JavaScript?
    • CSS?

    I was referring to web languages in general and the interaction between them - you seem to have conned your current employer into believing you know what you're doing. 😉

  9. P.S.

    18 minutes ago, ajetrumpet said:

    you should know, u gave me the correct script!

    If you are talking about correcting your href in the other thread then all I ever saw was a variable called $col. There was no way I could know what was in it.

  10. 10 minutes ago, ajetrumpet said:

    he wants to know where his visitors are coming from.

    I was thinking you were using

    city = google.loader.ClientLocation.address.city

    which just shows location of current user (or user's proxy)

    10 minutes ago, ajetrumpet said:

    are you still running this consultancy?

    If anyone ever contacts it. It hasn't happened yet. I was thinking of contacting the Guiness Book of Records as the world's least visited site.

  11. 14 hours ago, ajetrumpet said:

    the president of this org. doesn't have to do anything but click on the link in the traffic report to see the ip geolocation information

    So you're writing an application for those in your company who don't know where they are when they are browsing reports?

  12. 45 minutes ago, gw1500se said:

    IP address locations are based on the ISP location not the assigned user location.

    My results could be right then - there is the possibility that my ISP is in Salford.

    As for the region, it could be Google has a Londoner's view of England where anywhere beyond the end of their Northern underground line is "the North" (beware, here be dragons!)

  13. It will get location info, but not necessarily the correct info. For me, it returned

    • Country : GB
    • Region: West Riding of Yorkshire
    • City : Salford.

    The country is correct. However I do not live in Salford or the West Riding of Yorkshire. Also, Salford is in Lancashire, not in the West Riding of Yorkshire.

    I'd class it as a "Failed".

    (Moved to new topic)

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