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?
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?