Jump to content

Barand

Moderators
  • Posts

    24,337
  • Joined

  • Last visited

  • Days Won

    795

Posts posted by Barand

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

     

  2. 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
  3. 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
            )
    
    )

     

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

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

     

     

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

     

  7. I wouldn't waste time on the first SELECT query.

    Place a UNIQUE key constraint on the email column then

    function createNewUser($pdo, $fname, $lname, $email, $password)
    {
        try {
            $sql2 = "INSERT INTO user (fname, lname, email, password) VALUES (:fname, :lname, :email, :password)";
            $hashedPwd = password_hash($password, PASSWORD_BCRYPT);
            $stmt = $pdo->prepare($sql2);
            $stmt->execute([
                ':fname' => $fname,
                ':lname' => $lname,
                ':email' => $email,
                ':password' => $hashedPwd
            ]);
            return 'User Created';
        }
        catch (PDOException $e) {
            if ( str_contains($e->getMessage(), '1062 Duplicate entry')) {
                return "That email already exists";
            }
            else throw $e;
        }
    }

     

  8. An insert query works better if your sql informs the server

    1. it's an INSERT query
    2. which table to insert into

    so needs to begin with "INSERT INTO tablename..."

    Also, string literals like $imageName need to be inside single quotes. However you should be using a prepared statement.

    I would also advise storing your image files in the filesystem and putting the metadata (such as filename) in the table.

  9. I don't fancy the chances of sorting your files by the dates embedded in their names.

    Instead, get the filenames, get the date of each file, store in array, then sort the dates.

    
    $files = glob("$dir/*.*");
    $fdates = [];
    
    foreach ($files as $f) {
        $fdates[basename($f)] = date('Y-m-d',filemtime($f));
    }
    asort($fdates);
    
    echo '<ul>';
    foreach ($fdates as $fn => $dt) {
        echo "<li>$dt &ndash; $fn</li>";
    }
    echo "</ul>";

    Results wil look something like this

    image.png.c18a8b0155b2de84d9c289c819600e8b.png

     

  10. Aside from the empty WHERE clause mentioned by @gizmola above, you may also have a problem with passing your limit and offset parameters.

    You don't show us the relevant connection and execution code, but If your PDO connection code does not set ATTR_EMULATE_PREPARES to false (the default is true) then you cannot pass the limit and offset as parameters in an array when executing. You can, however, pass them using bindParam()

    You should always set this attribute to false

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