Jump to content

Barand

Moderators
  • Posts

    24,319
  • Joined

  • Last visited

  • Days Won

    794

Posts posted by Barand

  1. Like this?

    image.png.cc2eee06897a8bac78bf501c2cf0f5aa.png    image.png.8ae00d0f455154caf0397358e5c945ac.png

    Code

    <?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST')  {
        ##
        ##  Process posted data
        ##
        $number = $_POST['number_entered'] ?? 0;
        $answer = $_POST['answer'] ?? 0;
        $question = $_POST['question'] ?? '';
        $check = $number == $answer ? "<span class='w3-badge w3-green w3-xlarge'>&check;</span>" :
                                       "<span class='w3-badge w3-red w3-xlarge'>&times;</span>";
        $output = <<<OUT
            <span class="qtext">$question $number</span>
            $check
            <br><br>
            <a href='' class='w3-button w3-indigo'>Ask me another</a>
    OUT;
    }
    else  {
        ##
        ## Ask new question
        ##
        $rand1 = rand(1, 9);
        $rand2 = rand(1, 9);
        $randoperator = rand(0, 3);
    
        $operators = array('&times;', '&divide;', '&plus;', '&minus;');
    
        $finalvalue = match($randoperator) {
                            0 => $rand1 * $rand2,
                            1 => handleDivide($rand1, $rand2),
                            2 => $rand1 + $rand2,
                            3 => $rand1 - $rand2
                        };
    
        $question = "$rand1 {$operators[$randoperator]} $rand2 =";
    
        $output = <<<OUT
            <form method='POST'>
                <span class="qtext">$question</span>
                <input type='hidden' name='question' value='$question'>
                <input type='hidden' name='answer' value='$finalvalue'>
                <input type='number' name='number_entered' placeholder='?' autofocus>
                <br><br>
                <button class='w3-button w3-indigo'>Submit answer</button>
            </form>
    OUT;
        
    }
    
        
    
    
    function handleDivide(&$r1, $r2)
    {
        $fv = $r1;
        $r1 *= $r2;
        return $fv;
    }
    
    
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="utf-8">
       <title>Example</title>
       <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> 
       <style type='text/css'>
           div {
               padding: 16px;
               text-align: center;
           }
           input {
               width: 70px;
               text-align: center;
               font-size: 20pt;
           }
           .qtext {
               font-size: 20pt;
           }
       </style>
    </head>
    <body>
    <div class='w3-blue-gray'>
        <h1>Do the Math</h1>
    </div>
    <div>
        <?= $output ?>
    </div>
    </body>
    </html>

     

  2. An easier approach is to search for those records with today's char in the recurrence column set to "1"

    $sql = "SELECT id
                 , recurrence
                 , description
                 , begindate
                 , enddate
            FROM schedule
            WHERE ? BETWEEN begindate AND enddate
              AND SUBSTRING(recurrence, WEEKDAY(?)+1, 1)
              AND active
           ";
    $res = $pdo->prepare($sql);
    
    $searchDate = '2024-02-28';
    $res->execute([$searchDate, $searchDate]);

    Example outputs

    searchdate = Feb 26 2024 (Monday)
    +----+------------+-------------+------------+------------+
    | id | recurrence | description | begindate  | enddate    |
    +----+------------+-------------+------------+------------+
    | 39 | 1010100    | Event1      | 2023-08-31 | 3000-01-01 |
    +----+------------+-------------+------------+------------+
    
    
    searchdate = Feb 28 2024 (Wednesday)
    +----+------------+-------------+------------+------------+
    | id | recurrence | description | begindate  | enddate    |
    +----+------------+-------------+------------+------------+
    | 39 | 1010100    | Event1      | 2023-08-31 | 3000-01-01 |
    | 51 | 0010000    | Event2      | 2023-08-31 | 3000-01-01 |
    +----+------------+-------------+------------+------------+

     

    • Great Answer 1
  3. As well as chaging the rand() ranges to 1-9 I would also change the way rand1 and rand2 are used in the case of division.

    allocate rand1 to the finalvalue and then multiply rand1 by rand2. This avoids none integer results. IE..

    rand1 * rand2
    -------------   =   rand1
        rand2

    My code for this bit would be

    $rand1 = rand(1, 9);
    $rand2 = rand(1, 9);
    $randoperator = rand(0, 3);
    
    $operators = array('&times;', '&divide;', '&plus;', '&minus;');
    
    $finalvalue = match($randoperator) {
                        0 => $rand1 * $rand2,
                        1 => handleDivide($rand1, $rand2),
                        2 => $rand1 + $rand2,
                        3 => $rand1 - $rand2
                    };
    
    $question = "$rand1 {$operators[$randoperator]} $rand2 =";
    
    echo "$question $finalvalue<br>";
    
    
    function handleDivide(&$r1, $r2)
    {
        $fv = $r1;
        $r1 *= $r2;
        return $fv;
    }

     

  4. Try

    $categories = [];
    foreach ($res as $r)  {
        if (!isset($categories[$r['id']]))  {
             $categories[$r['id']] = [ 'catid' => $r['id'],
                                       'catname' => $r['name'],
                                       'videos' => []
                                     ];
        }
        $categories[$r['id']]['videos'][] = [ 'vidname' => $r['fname'],
                                              'vidthumbnail' => $r['fthumbnail'],
                                              'vidid' => $r['fid'],
                                              'vidlink' => $r['flink']
                                            ];
    }
    $result = json_encode($categories);

     

  5. 6 minutes ago, Adamhumbug said:
    		let fdata = $(this).serialize() + "&ajax=addNewZones";

    Yes.

    That is what I was going to suggest if you didn't want to use the hidden field approach. That way you send just a single querystring which will be handled automatically to create the $_POST array

    12 minutes ago, Adamhumbug said:

    How does one go about looping through this array to insert it into the DB but only when a zone name is present.

    Perhaps

        $stmt = $pdo->prepare("INSERT INTO mytable (zoneType, zoneName, printValue) VALUES (?,?,?)");
        foreach ($_POST['zoneName'] as $k => $zn)  {
            if ($zn) {
                $stmt->execute([ $_POST['zoneType'][$k], $zn, $_POST['printValue'][$k] ]);
            }
        }

     

    • Great Answer 1
  6. Your POST array looks like this, as you separate the "ajax" value from the serialized data in your JSON string...

    Array
    (
        [ajax] => testdata
        [data] => zoneType%5B%5D=1&zoneName%5B%5D=aa&printValue%5B%5D=1&zoneType%5B%5D=1&zoneName%5B%5D=bb&printValue%5B%5D=2&zoneType%5B%5D=1&zoneName%5B%5D=cc&printValue%5B%5D=3
    )

     

    With my code, where only the serialized form data is sent (which includes the "ajax" value from a hidden form field) it looks like this...

    Array
    (
        [ajax] => testdata
        [zoneType] => Array
            (
                [0] => 1
                [1] => 1
                [2] => 1
            )
    
        [zoneName] => Array
            (
                [0] => aa
                [1] => bb
                [2] => cc
            )
    
        [printValue] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
            )
    
    )

     

  7. Here's a sample script

    <?php
    
    ##
    ##  HANDLE AJAX REQUEST
    ##
        if (isset($_POST['ajax']))   {
            if ($_POST['ajax']=='testdata') {
                exit('<pre>' . print_r($_POST, 1) . '</pre>');      // JUST RETURNS THE ARRAY OF POSTED DATA FOR DISPLAY
            }
            exit();
        }
        
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="utf-8">
       <title>Example</title>
       <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
       
       <script type='text/javascript'>
           $(function() {
               $("#form1").submit(function(ev) {
                   ev.preventDefault()
                   let fdata = $(this).serialize()
                   console.log(fdata)
                   $.post(
                       "",
                       fdata,
                       function(resp) {
                           $("#test-output").html(resp)
                       },
                       'TEXT'
                   )
               })
           })
       </script> 
    </head>
    <body>
        <form id='form1'>
        <input type='hidden' name='ajax' value='testdata'>
          <div class="col">
            <label for="zoneType" class="form-label">Zone Type</label>
            <select name="zoneType[]" class="form-select zoneType">
              <option value="1">Normal Zone</option><option value="2">Special Zone</option>                            
            </select>
          </div>
          <div class="col">
            <label for="zoneName" class="form-label">Zone Name</label>
            <input type="text" class="form-control simple-string zoneName" name="zoneName[]">
          </div>
          <div class="col">
            <label for="printValue" class="form-label">Print Value</label>
            <input type="text" class="form-control simple-string printValue" name="printValue[]">
          </div>
          <br>
          
          <div class="col">
            <label for="zoneType" class="form-label">Zone Type</label>
            <select name="zoneType[]" class="form-select zoneType">
              <option value="1">Normal Zone</option><option value="2">Special Zone</option>                            
            </select>
          </div>
          <div class="col">
            <label for="zoneName" class="form-label">Zone Name</label>
            <input type="text" class="form-control simple-string zoneName" name="zoneName[]">
          </div>
          <div class="col">
            <label for="printValue" class="form-label">Print Value</label>
            <input type="text" class="form-control simple-string printValue" name="printValue[]">
          </div>
          <br>
          
          <div class="col">
            <label for="zoneType" class="form-label">Zone Type</label>
            <select name="zoneType[]" class="form-select zoneType">
              <option value="1">Normal Zone</option><option value="2">Special Zone</option>                            
            </select>
          </div>
          <div class="col">
            <label for="zoneName" class="form-label">Zone Name</label>
            <input type="text" class="form-control simple-string zoneName" name="zoneName[]">
          </div>
          <div class="col">
            <label for="printValue" class="form-label">Print Value</label>
            <input type="text" class="form-control simple-string printValue" name="printValue[]">
          </div>
          <br>
        <input type='submit'>
        </form>
        <div id='test-output'>
        </div>
    </body>
    </html>

    [edit]...

    NOTE - your form's input fields need name attributes

  8. 18 minutes ago, Adamhumbug said:

    Should probably have included in the previous post.

    Yes. Instead of saying this...

    1 hour ago, Adamhumbug said:

    The database connection comment was more about each function having to establish a connection and send a query to the database

     

     

  9. Whichever approach you use, do NOT connect to the database inside every function. Connect once to the db at start of each script and pass the connection to the functions. (The connection is the slowest part of the process)

    So the function calls are

    getFirstName($pdo, $id)
    getLastName($pdo, $id)
    getEmail($pdo, $id)
    getDietary($pdo, $id)
    getX($pdo, $id)

    I'd go with a single function

    
    $user = getUserData($pdo, $user_id);                              // get an array containing the user data
    if ($user) {
        $fullname = $user['firstname'] . ' ' . $user['lastname'];     // use array elements as required
    }
    
    function getUserData($pdo, $id)
    {
        $res = $pdo->prepare("SELECT firstname
                                   , lastname
                                   , email
                                   , diet
                                   , gender
                                   , x
                                   , y
                                   , z
                              FROM user
                              WHERE id = ?      
                              ");
        $res->execute([$id]);
        return $res->fetch();
    }
    

     

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