Jump to content

Barand

Moderators
  • Posts

    24,423
  • Joined

  • Last visited

  • Days Won

    806

Posts posted by Barand

  1. All existing records will have the timestamp auto updated to the time the column was added.

    When new records are added that timestamp column will be the time added.

    You could set that column to zero date (for currently existing records) so only new records get a time stamp. 

    UPDATE tblTraffic SET logged = 0;

    Then you will know which time to use - the timestamp if non-zero or the time column if timestamp is zero.

    SELECT TIME_FORMAT(IF(logged=0, time, logged), '%T') as time

    EDIT:

    Alternatively, copy the date and time columns' values into the timestamp column

  2. Try this...

    Add a TIMESTAMP type column to your table

     `logged` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

    then use the time portion of this column in your query instead of your current time column. (You don't need to change the INSERT query as it will update itself automatically)

    $sql = mysqli_query($conn, "SELECT ip
                                         , page
                                         , CASE WHEN referrer = ''
                                                THEN 'N/A'
                                                ELSE referrer
                                           END as referrer     
                                         , DATE_FORMAT(date, '%m/%d/%y') as date
                                         , TIME_FORMAT(logged, '%T') as time
                                    FROM tblTraffic 
                                    ORDER BY date DESC, time DESC");

     

  3. I do but we cannot  see what you can see. I am not clairvoyant nor am I standing behind you looking over your shoulder at your screen. I don't know your table structure. I cannot see your data. So sometimes there is a need to ask questions in order to give that help.

  4. It should function as posted (at least, it does for me). You should have a "census.csv" file that resembles this...

    "Hamilton, Oh",3,30000
    "Hamilton, Oh",1,25000
    "Butler, Oh",1,22000
    "Butler, Oh",1,44000
    "Clermont, Oh",1,65000
    "Clermont, Oh",1,15000
    "Clermont, Oh",2,11000
    "Warren, Oh",3,20000
    "Warren, Oh",1,100000
    "Campbell, Ky",2,50000
    "Kenton, Ky",8,20000
    "Kenton, Ky",4,15000
    "Kenton, Ky",4,18000
    "Warren, Oh",1,70000
    "Warren, Oh",2,100000
    

    ...which gets processed and output by lines 51 -75 (Output table is stored in "$analysis" variable and output in the HTML section - 5 lines from the end)

  5. 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

  6. 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);

     

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

  8. 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

     

  9. 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
  10. 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;
    }

     

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