Reputation: 51
I've been working on my first big website and encountered a problem while trying to create a PHP function that returns a value based on criteria given when the function is called.
I have been having a problem for using the following code, all I could get to return was "DATABASE: 1"
function data_r_user($request, $username ) {
include("login/dbconnect.php");
$sqli = "SELECT " . $request . " FROM users WHERE username = " . $username;
$result = mysqli_query($dbconnect,$sqli ) or die();
return $result;
}
After searching up for a while I appear to of tracked the problem to the fact that all SQL queries return an array and not a string (I believe this to be the case sorry if I'm wrong).
I thought returning a single result would be easy but it appears not to be.
So basically I want a way to return a single result from this function and I'm indifferent as to whether it's procedural or object.
Upvotes: 3
Views: 2171
Reputation: 6581
Using prepared statements is highly recommended, so forgive me for not pointing you to mysqli_fetch_row but instead showing you how to do this securely:
function data_r_user($request, $username ) {
// you want require and only do it once
require_once("login/dbconnect.php");
$return = '';
// white list the allowed columns
$columns_allowed = array('id', 'username', 'firstname', 'lastname');
if (! in_array($request, $columns_allowed)) {
// if they ask for something not allowed give them nothing
return '';
}
/* create a prepared statement */
if ($stmt = mysqli_prepare($dbconnect, "SELECT " . $request . " FROM users WHERE username = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $username);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $return);
/* fetch value */
mysqli_stmt_fetch($stmt);
}
return $return;
}
Upvotes: 3