Binding column name as mysqli param

I want to create a function where I can get customer information based on the column named passed into the function. For example…

<?php

function GetCustomer($customer, $field)
{
    global $sql_connect;
    $stmt_query = "SELECT " . $field. " FROM Customers WHERE customer_id  = ? LIMIT 1";
    $stmt = mysqli_prepare($sql_connect, $stmt_query);
    mysqli_stmt_bind_param($stmt, "i",  $customer);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $return_value);
    mysqli_stmt_store_result($stmt);
    mysqli_stmt_fetch($stmt);
    return $return_value;
}

echo GetCustomer(1, name); // Bob

?>

I can’t use bind_param for the column names because it will wrap them within quotes and MySQL will take the column names as strings. While the above query work, I feel it’s more of a “hack”, Is there a better or safer way to be doing this?

You can’t use them for the column names at all:

“However, they are not allowed for identifiers (such as table or column names)” ( http://php.net/manual/en/mysqli.prepare.php )

function GetCustomer($customer)
{
    global $sql_connect;
    $stmt_query = "SELECT * FROM Customers WHERE customer_id  = ? LIMIT 1";
    $stmt = mysqli_prepare($sql_connect, $stmt_query);
    mysqli_stmt_bind_param($stmt, "i",  $customer);
    mysqli_stmt_execute($stmt);
    $res = mysqli_stmt_get_result($stmt);
    return $res->fetch_assoc();
}

echo GetCustomer(1)['name']; // Bob

?>
1 Like

when a user enter his name in field then it will pass to a variable then we print this variable, and we get we desire column name.

That would work just fine for the example given, but I would also like to do an UpdateCustomer too where I can pass a customer number, column name, and value. How can I do that too?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.