Jump to content

amirelgohary1990

Members
  • Posts

    25
  • Joined

  • Last visited

Posts posted by amirelgohary1990

  1. I am retrieving data via Ajax into Choices.js select options
    My scenario is when I select date, getting the available restaurant tables

    The retrieving data is 100% working, but it reflects in the select options only in the first request, then when I try to reselect another date I receive the below console error, and choices still keep the initial retrieved data
    choices.min.js:11   Trying to initialise Choices on element already initialised

     

    Choices setValue Function

    var el = document.getElementsByClassName("table_number")[0];
    if (el) {
      function setChoices(values) {
        const tableNumbers = new Choices(el, {
          removeItemButton: true,
        }).setValue(values);
      }
      setChoices(values);
    }

    Ajax Code

    let shiftDate = document.getElementById('reservation_shift_date');
          shiftDate.addEventListener("change", function(){
              let request = new XMLHttpRequest();
              request.open("POST","get_tables.php",true);
              request.setRequestHeader("content-type","application/x-www-form-urlencoded");
              request.onreadystatechange = function(){
                  if(request.readyState == 4 && request.status == 200){
                      setChoices(JSON.parse(request.responseText));
                  }
              }
              request.send("date="+shiftDate.value);
          });

     

    get_tables.php  

    if($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['date'])){
    
      $stmt = $conn->prepare("SELECT table_id FROM reservation WHERE shift_date = ?");
      $stmt->execute([$_POST['date']]);
      $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
      foreach($rows as $row){
        $reserved_tables_id[] = $row['table_id'];
      }
    
      $in = implode(',',$reserved_tables_id);
    
      $execute_query = mysqli_query($dbConnection,"SELECT id, table_name FROM tables WHERE id NOT IN ($in)");
    
      while($row = mysqli_fetch_assoc($execute_query)){
        $tbl_id = $row['id'];
        $tbl_name = $row['table_name'];
        $arr[] = ["value"=>$tbl_id,"label"=>$tbl_name];
      }
      echo json_encode($arr);
    }

     

  2. 6 hours ago, requinix said:

    1. Thank you for posting your reCAPTCHA secret to a public forum. Please cancel it and generate a new one immediately. And then don't publish it anywhere.
    2. The URL you're constructing has two problems, but they're irrelevant because:
    3. Per the documentation, you need to send a POST request to /siteverify. Not a GET request. Which typically means using cURL.

    If you still have problems, remember to post your updated code.

    Hello
    This secret code will not be published into the live site, just a test copy :D

    The below code worked with me

    if(isset($_POST['submitContact']) && $_SERVER['REQUEST_METHOD'] == 'POST'){
       $postdata = http_build_query(["secret"=>"6LfyPF0pAAAAAEsS5lfN_WL3wKHh1XfGo0oE_PYU","response"=>$recaptcha_response]);
        $opts = ['http' =>
            [
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            ]
        ];
        $context  = stream_context_create($opts);
        $result = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
        $recaptcha = json_decode($result);
         if($recaptcha->success ==true){
             if($recaptcha->score >= 0.5){
                echo "Recaptcha Success";
             }else{
                 echo"<pre>";
                 print_r("Recaptcha Not Verified");
                 echo"</pre>";
             }
         }else{
             echo"<pre>";
             print_r($recaptcha);
             echo"</pre>";
         }

     

  3. Hello

    I am receiving a huge amount of spam emails, now I am trying to implement Google Recaptcha V3 in my custom PHP From,

    I implemented all the steps for G-Recaptcha,
    but I receive error invalid-input-secret

    And I am sure that the secret code shout be copied right

     

    I added the below to the head tag

    <script src="https://www.google.com/recaptcha/api.js?render=6LfyPF0pAAAAAHLxp3315RTN7jrRvBe6kLdHGAiT"></script>
    <script>
      grecaptcha.ready(function() {
        grecaptcha.execute('6LfyPF0pAAAAAHLxp3315RTN7jrRvBe6kLdHGAiT', {action: 'submit'}).then(function(token) {
          let recaptchaResponse = document.getElementById("recaptchaResponse");
          console.log(recaptchaResponse);
          recaptchaResponse.value = token;
        });
      });
    </script>

     

    Then added hidden input before the submit button in the Form

    <input type="hidden" name="recaptcha_response" id="recaptchaResponse"> 
    <input class="contactInput no-border cursorPointer buttonStyle" name="submitContact" value="Submit" type="submit">

    And finally, I implemented the PHP code

     

    if(isset($_POST['submitContact']) && $_SERVER['REQUEST_METHOD'] == 'POST'){
         $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
         $recaptcha_secret = '6LfyPF0pAAAAAEsS5lfN_WL3wKHh1XfGo0oE_PYU';
         $recaptcha_response = $_POST['recaptcha_response'];
         $recaptcha = file_get_contents($recaptcha_url."?secret=".$recaptcha_secret."?response=".$recaptcha_response);
         $recaptcha = json_decode($recaptcha);
         if($recaptcha->success ==true){
             if($recaptcha->score >= 0.5){
                echo "Recaptcha Success";
             }else{
                 echo"<pre>";
                 print_r("Recaptcha Not Verified");
                 echo"</pre>";
             }
         }else{
             echo"<pre>";
             print_r($recaptcha);
             echo"</pre>";
         }
    }

     

    But receiving the below error

    stdClass Object ( [success] => [error-codes] => Array ( [0] => invalid-input-secret ) )

  4. 6 hours ago, maxxd said:

    Don't try to assign and compare on the same line; it makes things complicated. Assign the array_search result to $key on it's own line, absolutely compare $key to false. If $key is not false, unset the value at index $key.

    I tried this also, but same problem

     

    $bloodType_list = ['a+','a-','b+','b-','o+','o-','ab+','ab-']; 
       if($key = array_search('a+',$bloodType_list)){
       if($key !== false){
          unset($bloodType_list[$key]);
       }
       }
        foreach($bloodType_list as $bloodType_lists){
            echo $bloodType_lists."<br>";
        }

     

  5. 2 hours ago, mac_gyver said:

    the key/index for the 'a+' entry is 0. this is a boolean false value, so the if() logic branch is skipped. you need to perform an exact match for a non-false value. e.g. !== false

    You mean like below code ?

    $bloodType_list = ['a+','a-','b+','b-','o+','o-','ab+','ab-'];
    if($key = array_search('a+',$bloodType_list)) !== false {       
    unset($bloodType_list[$key]);
    }     
    foreach($bloodType_list as $bloodType_lists){         
        echo $bloodType_lists."<br>";
    }

    I tried that not working too

  6.  

    Hello, I am trying to unset from array using array_search, 
    it's working, except the first array value "a+" is not working

    $bloodType_list = ['a+','a-','b+','b-','o+','o-','ab+','ab-']; 
       if($key = array_search('a+',$bloodType_list)){
          unset($bloodType_list[$key]);
       }
        foreach($bloodType_list as $bloodType_lists){
            echo $bloodType_lists."<br>";
        }

     

  7. Hello,
    photos do not appear in the following cases
    1- inserting photo inside <picture> tag (In Server Side Only), Working normally in local
    2-   Not Working when site domain only www.mysite.com ,, Working when site domain = www.mysite.com/index.php 
     

    <picture class="hover1 runHover2">
     <img  src="assets/img/central-business-district-singapore.jpg">
    </picture>


    Note:

    -The path is right, and when opening inspect to check the photo, I find it
    - Tried to change the path to
    /assets/img/central-business-district-singapore.jpg  or www.mysite.com/assets/img/central-business-district-singapore.jpg , but not solved

  8. 13 minutes ago, mac_gyver said:

    1- FIND_IN_SET(id,?) (no quotes around the name)

    2- the 2nd parameter is the set to search in. it is a (string) consisting of a comma separated list of values. you would just implode() the array of values using a comma, and supply that as the prepared query input value.

    3- if the job status and/or the array of ids are statically defined in your code, and don't come from external, unknown, dynamic values, why are you going through the trouble of using a prepared query? just put the static values in the sql query statement.

    1- Noted, and edited

    2- I think this is the last point I need, I added the imploded ids inside mysqli_stmt_bind_param, is this right, or I have to put somewhere else,I tried even to put my integers manually inside the FIND_IN_SET('id',77,181), but did not work gives me error Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, bool given 

    3- Actually $the_array = [77,181]; I wrote here as static, but in my project this array comes from another dynamic query, that comes from the website when user search for specific country,
    Regarding 

  9. 6 minutes ago, ginerjm said:

    It "did work"?  Or it "did not work"?

    do you have error checking enabled for your script?

    Code not returning anything

    Yes, I enabled errors, also no errors, but I am sure something wrong, when I switch to normal query everything works normally with IN()
     

    ini_set('display_errors', 1);
    
    ini_set('display_startup_errors', 1);
    
    error_reporting(E_ALL);

     

  10. I tried to use FIND_IN_SET() with prepared statement, but did work, do not return any result, or even errors

    if(escape($_POST['jobCategory']) != "all-categories" && escape($_POST['countryId']) == "all-countries" && escape($_POST['careerLevel']) == "all-career-levels"):
    
    $the_array = [77,181];
    $job_id_imploded = implode(',',$the_array);
    $query = mysqli_prepare($dbConnection,"SELECT jobs.id, jobs.job_title, jobs.country_id, employers.employer_name FROM jobs LEFT JOIN employers ON jobs.employer_id = employers.employer_id WHERE job_status = ? AND FIND_IN_SET('id',?)");
    
    mysqli_stmt_bind_param($query,'si',$job_status,$job_id_imploded);
    
    endif;
    
    mysqli_stmt_execute($query);
    mysqli_stmt_bind_result($query,$job_id,$job_title,$countryId,$employer_name);
    while(mysqli_stmt_fetch($query)){
    
    ?>
    
    <div class="job-title">
    <a href="job_post.php?job_id=<?php echo htmlspecialchars($job_id) ?>" class="job-title-link"><?php echo htmlspecialchars($job_title); ?></a>
    </div>
    
    <?php } // End While ?>

     

  11. 20 hours ago, mac_gyver said:

    you will find that you can use a single prepared query place-holder if you use FIND_IN_SET() instead of an IN() comparison, which requires a place-holder for each value in the list.

    I tried to use FIND_IN_SET() with prepared statement, but did work, do not return any result, or even errors, that's why I used normal query until study PDO then switch this query into PDO,
    I will open new case with my code with FIND_IN_SET() may be something wrong in my code

  12. Hello

    I need to find a way to close loop outside if condition

    like below example

    if(escape($_POST['jobCategory']) != "all-categories" && escape($_POST['countryId']) == "all-countries"):
    
    $query = mysqli_query($dbConnection,"SELECT jobs.id, jobs.job_title, jobs.salary, jobs.employer_id, employers.employer_name, employers.employer_logo FROM jobs LEFT JOIN employers ON jobs.employer_id = employers.employer_id WHERE job_status = '".mysqli_real_escape_string($dbConnection,'Active')."' AND id IN (".mysqli_real_escape_string($dbConnection,$job_id_imploded).") ");
    
    while($row = mysqli_fetch_assoc($query)){  // Start Loop
     $job_id = $row['id'];
    $job_title = $row['job_title'];
    
    endif; 
    
    <div class="job-title">
    <a href="job_post.php?job_id=<?php echo htmlspecialchars($job_id) ?>" class="job-title-link"><?php echo htmlspecialchars($job_title); ?></a>
    </div>
    
    } // End Of Loop

     

    Gives me error 

    HTTP ERROR 500

  13. 21 hours ago, ginerjm said:

    Why did you choose to store your data in such a strange way???

    I started using serialize because I wanted to store multiple steps of values to create dynamic taxes for a HRM system

    I searched for a way I found that serialize can be used if these data will not be used for analytics, just will sore it, then later I  retrieve data as array normally

     

    Screen Shot 2023-07-17 at 7.30.25 PM.png

  14. 23 minutes ago, ginerjm said:

    You are showing us a couple of arrays but you are not showing us how the data that is being queried is stored.  Are you trying to display query results of arrays?

    Hello, I am selecting two rows, first is 'id' and second row I am selecting serialized 'category_ids', then I unserialized it
    Those two rows I selected 'id' + unserialized 'category_ids' ,, I am trying to output then into specific array template like the below array example

    The Array "I Need to achieve like this"

    ["172"=>["4","6"],"174"=>["4","6"],"175"=>["4","3","6"],"176"=>["4","3"],"177"=>["4","6"],"181"=>["3","6"],"182"=>["7"],"183"=>["3","4"],"184"=>["4","3","6"],"185"=>["3","6"],"186"=>["8","6"],"188"=>["3","6"],"189"=>["3","6"],"190"=>["6"],"191"=>["3","6","4","7"]];

    It's var_dump "I Need to achieve like this"

    array(15 { [172]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6"} [174]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6" } [175]=> array(3) { [0]=> string(1) "4" [1]=> string(1) "3" [2]=> string(1) "6" } [176]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "3" } [177]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6" } [181]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "6" } [182]=> array(1) { [0]=> string(1) "7" } [183]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "4" } [184]=> array(3) { [0]=> string(1) "4" [1]=> string(1) "3" [2]=> string(1) "6" } [185]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "6" } [186]=> array(2) { [0]=> string(1) "8" [1]=> string(1) "6" } [188]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "6" } [189]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "6" } [190]=> array(1) { [0]=> string(1) "6" } [191]=> array(4) { [0]=> string(1) "3" [1]=> string(1) "6" [2]=> string(1) "4" [3]=> string(1) "7" } }

     

     

    When I try to achieve this by the following 

     $asscArrays = [$job_id=>$job_category_id];  

    It's printing the array result but separately array(1) not array(15) ,, like the below

    array(1) { [172]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6" } } array(1) { [174]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6" } } array(1) { [175]=> array(3) { [0]=> string(1) "4" [1]=> string(1) "3" [2]=> string(1) "6" } } array(1) { [176]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "3" } } array(1) { [177]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6" } } array(1) { [181]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "6" } } array(1) { [182]=> array(1) { [0]=> string(1) "7" } }
    

    The array template I am willing to achieve is array(15)

  15. I need to output the exact below array format from the mysqli_fetch_assoc rows

    The Array "Need to achieve like this"

    ["172"=>["4","6"],"174"=>["4","6"],"175"=>["4","3","6"],"176"=>["4","3"],"177"=>["4","6"],"181"=>["3","6"],"182"=>["7"],"183"=>["3","4"],"184"=>["4","3","6"],"185"=>["3","6"],"186"=>["8","6"],"188"=>["3","6"],"189"=>["3","6"],"190"=>["6"],"191"=>["3","6","4","7"]];

    It's var_dump "Need to achieve like this"

    array(15) {
    [172]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6"}
    [174]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6" }
    [175]=> array(3) { [0]=> string(1) "4" [1]=> string(1) "3" [2]=> string(1) "6" }
    [176]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "3" }
    [177]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6" }
    [181]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "6" }
    [182]=> array(1) { [0]=> string(1) "7" }
    [183]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "4" }
    [184]=> array(3) { [0]=> string(1) "4" [1]=> string(1) "3" [2]=> string(1) "6" }
    [185]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "6" }
    [186]=> array(2) { [0]=> string(1) "8" [1]=> string(1) "6" }
    [188]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "6" }
    [189]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "6" }
    [190]=> array(1) { [0]=> string(1) "6" }
    [191]=> array(4) { [0]=> string(1) "3" [1]=> string(1) "6" [2]=> string(1) "4" [3]=> string(1) "7" }
    }

     

    My Code

    $query = mysqli_query($dbConnection,"SELECT id, job_category_id FROM jobs");
    while($row = mysqli_fetch_assoc($query)){
    $job_id = $row['id'];
    $job_category_id = htmlspecialchars($row['job_category_id']);
    $job_category_id = unserialize(base64_decode($job_category_id));

    $asscArrays = [$job_id=>$job_category_id];   // Here I am trying to achieve the array template like the I mentioned above

    }

    var_dump $asscArrays

    array(1) {
    [172]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6" }
    }
    array(1) {
    [174]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6" }
    }
    array(1) {
    [175]=> array(3) { [0]=> string(1) "4" [1]=> string(1) "3" [2]=> string(1) "6" }
    }
    array(1) {
    [176]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "3" }
    }
    array(1) {
    [177]=> array(2) { [0]=> string(1) "4" [1]=> string(1) "6" }
    }
    array(1) {
    [181]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "6" }
    }
    array(1) {
     [182]=> array(1) { [0]=> string(1) "7" }
    }

     

  16. 6 minutes ago, requinix said:

    Either the path is wrong or the file is not where you think it is. I don't know what else to tell you.

     

    If the first one works then why do you want to change it?

    I need to store PDFs in a folders, not keep random in the same index root,
    Actually it's very strange either path and file 100% are right I double checked

  17. 8 hours ago, requinix said:

    No, the path is not correct. Because if it were then all this would be working, wouldn't it?

    If you want to link to the PDF in your HTML then read this and give it another try:
    https://stackoverflow.com/questions/2005079/absolute-vs-relative-urls

    If you want to read the PDF with PHP code then read this one and give it another try:
    https://phpdelusions.net/articles/paths

    Hello,

    When I type admin/assets/cvs/myimage.png  It's working

    but when I type a pdf admin/assets/cvs/myfile.pdf  not working

    That's why I assumed that the path should be right 

    PDF only reads with me if the file in the same folder index like this <a href="myfile.pdf" target="_blank">View PDF</a> This working

  18. When I try to display  PDF , not working when pdf contains path, just working if the file is in the same index

    This Works 
    <a href="myfile.pdf" target="_blank">View PDF</a>

    The below not working .. ERROR The requested URL was not found on this server.
    <a href="admin/assets/cvs/myfile.pdf" target="_blank">View PDF</a>

    I am sure that the path is right and I tested with .png extensions.

     

    Also I tried to use header function to display PDF with PHP but got also error even if the file in the same directory index Failed to load PDF document.

     

    $fileName = "myfile.pdf";
    header('Content-type: application/pdf');
    header('Content-Disposition: inline; filename="' .urlencode($fileName). '"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($fileName));
    header('Accept-Ranges: bytes');
    @readfile($fileName);

  19. 12 hours ago, mac_gyver said:

    all of this code is unnecessary. you can use php's ... operator. see the Argument unpacking via ... example at this link - https://www.php.net/manual/en/migration56.new-features.php

     

     

    Hello @mac_gyver
    I tried this example in the link you shared Example #5 Execute a prepared statement using array for IN clause
    Actually the error gone, but did not echo the result from the database

     

     

    $arr_params = [1,2,5];
    $placeholders = implode(',', array_fill(0, count($arr_params), '?'));
    $query = "SELECT designation_id, designation_name FROM designations WHERE designation_id NOT IN ($placeholders)";

    try {
    $stmt = $conn->prepare($query);
    $stmt->execute($arr_params);
    $a_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
    trigger_error('Wrong SQL: ' . $query . ' Error: ' . $e->getMessage(), E_USER_ERROR);
    }

  20. Hello, I am trying to use array in bind statement to avoid entering bind manually

    Below, I set up the array, then imploded the array to insert on it    // to return 1,2,5 , but I got error Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables

    $arr = [1,2,5];
    $arr_as_string = implode( ',',$arr);
    $type = 'iii';

    $params = [$type,$arr_as_string];

    $tmp = [];

    foreach($params as $key => $value) $tmp[$key] = &$params[$key];

    call_user_func_array([$query, 'bind_param'], $tmp);

  21. On 9/20/2009 at 7:22 AM, corbin said:

    Hrmmmmm odd.  I just looked on the manual page for call_user_func_array and for some reason it appears that the array is passed by value.  Usually things are passed by value, but they're references until it is edited.

     

     

    This is a ghetto hacked suggested by someone:

     

     

            $params = array('ss', 'stan', 'Stanley');

            $tmp = array();

            foreach($params as $key => $value) $tmp[$key] = &$params[$key];

            call_user_func_array(array($stmt, 'bind_param'), $tmp);

    Hello

    Just I am trying to replace  $params = array('ss', 'stan', 'Stanley'); 

    With 
    $arr = [1,2,5];
    $params = array('ss', 'stan', $arr);

    But when I do that gives me error Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables 

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