0

I made a simple function that will go into the MYSQL DB and get the field I need based on an id. It works OUTSIDE the function. Inside the function the SQL statement is correct but I cannot figure out why it will not output the results of $row[$field]. Something I am doing wrong is not displaying when its inside the function.

function getVendor($field,$id) {
    $sql = "SELECT  $field from manufacturer where id=$id LIMIT 1";
    echo $sql;
    $result = $conn->query($sql);
    while($row = $result->fetch_assoc()) {
        echo $row[$field];
    }
}


getVendor('name','2');
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Sparkd
  • 9
  • 1
  • 2
    `$conn` is out of scope, feed the connection object in the function arguments as well – Kevin Aug 23 '19 at 01:43

1 Answers1

1

Your $conn is not in the function scope. Also, You don't need the while loop due the id should be unique.

function getVendor($conn, $field, $id) {

    $sql = " SELECT {$field} FROM manufacturer WHERE id={$id} ";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    echo $row[$field];

}


getVendor($conn, 'name','2');
Ezequiel Fernandez
  • 954
  • 11
  • 18