0

I'm trying to create a function that will return an array with all the fields of the query result and then loop through it and echo everything. This is what I have done so far. I tried some approaches from similar questions such as Putting a SQL query in a PHP function but so far I haven't been able to get it to work.

<?php

    $ID = $_POST['ID'];

    function query($ID){
    $servername = "x.x.x.x";
    $username = "xxxxx";
    $password = "xxxxx";
    $dbname = "xxxxx";

    $conn = mysqli_connect($servername, $username, $password, $dbname);
      if (mysqli_connect_errno()){
              echo "Failed to connect to MySQL: " . mysqli_connect_error();
                               }

    $query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM GROUP WHERE ID = '$ID'";
    $result = mysqli_query($conn, $sql);

    while($row = mysqli_fetch_array($result)){
    $resArr[] = $row;
    }
    return $resArr;
    }

    $person = query();
    foreach($person as $post) {
    echo $post['ID'] . "<br>";
    echo $post['NAME'] . "<br>";
    echo $post['POSITION'] . "<br>";
    echo $post['TELEPHONE_NUMBER'] . "<br>";
    echo $post['EMAIL'] . "<br>";
    }
    ?>
3
  • 1
    Other than your gaping wide-open sql injection attack vulnerability, what exactly is wrong with this code? doesn't work doesn't tell us anything. if it worked, you wouldn't be here. Commented May 5, 2015 at 14:55
  • 2
    you define your function with a parameter - function query($ID), but you call it without a parameter - $person = query();. You need to do $person = query($ID); Commented May 5, 2015 at 14:58
  • Marc B - User input is limited to integers on the page where POST is getting data from and if I knew what was wrong I still wouldn't be here I would probably fix it. Anyway, thanks Sean that did it and thanks to the rest of you guys! Commented May 6, 2015 at 8:16

1 Answer 1

1

there are few mistakes has been done for example $ID in your query can not get translated into normal id value so you have to close your query like this if ID is an integer than

 $query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM GROUP WHERE ID = ".$ID;

if ID is a varchar or any other than.

 $query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM GROUP WHERE ID = '".$ID."'";

also you are getting id via post but you are not assigning it to your function where you are calling it.

   $person = query();  

it must be

     $person = query($ID);

try these fixes and than post your result back.

Regards

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.