I have a php function that builds a mysql query and then gets products from the database and then turns the database rows into php objects...
function queryDbForProducts($conn, $place) {
$queryObject = buildSQLWhereClause($place);
$query = $queryObject['query'];
$queryParams = $queryObject['queryParams'];
$queryParamTypes = $queryObject['queryParamTypes'];
array_unshift($queryParams, $queryParamTypes);
$stmt = $conn->prepare($query);
call_user_func_array(array($stmt, 'bind_param'), makeValuesReferenced($queryParams));
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] =& $row[$field->name];
}
call_user_func_array(array($stmt,'bind_result'), $parameters);
while ($stmt->fetch()) {
foreach ($row as $key => $val) {
$x[$key] = $val;
}
//$results[] = $x;
$product = array(
"name" => $x['p_name'],
"brand" => $x['brand'],
"imagePath" => $x['image_path']
);
$shop = array(
"name" => $x['s_name'],
"country" => $x['country'],
"province" => $x['province'],
"city" => $x['city'],
"suburb" => $x['suburb'],
"street" => $x['street'],
"streetNumber" => $x['streetNumber']
);
$productInformation = array(
"product" => $product,
"shop" => $shop
);
$allProducts[] = $productInformation;
}
return $allProducts;
}
I would like to refactor it into more functions but it always stops working when I try. For instance:
function parseResultsToPHPObjects($stmt, $parameters) {
call_user_func_array(array($stmt,'bind_result'), $parameters);
while ($stmt->fetch()) {
foreach ($row as $key => $val) {
$x[$key] = $val;
}
//$results[] = $x;
$product = array(
"name" => $x['p_name'],
"brand" => $x['brand'],
"imagePath" => $x['image_path']
);
$shop = array(
"name" => $x['s_name'],
"country" => $x['country'],
"province" => $x['province'],
"city" => $x['city'],
"suburb" => $x['suburb'],
"street" => $x['street'],
"streetNumber" => $x['streetNumber']
);
$productInformation = array(
"product" => $product,
"shop" => $shop
);
$allProducts[] = $productInformation;
}//********************** line 66 *******************************
return $allProducts;
}
function queryDbForProducts($conn, $place) {
$queryObject = buildSQLWhereClause($place);
$query = $queryObject['query'];
$queryParams = $queryObject['queryParams'];
$queryParamTypes = $queryObject['queryParamTypes'];
array_unshift($queryParams, $queryParamTypes);
$stmt = $conn->prepare($query);
call_user_func_array(array($stmt, 'bind_param'), makeValuesReferenced($queryParams));
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] =& $row[$field->name];
}
return parseResultsToPHPObjects($stmt, $parameters);
}
Gives this error:
05-May-2016 21:16:41 Pacific/Auckland] PHP Parse error: syntax error, unexpected ';', expecting ',' or ')' in /Applications/MAMP/htdocs/the_vegan_repository/scripts/back_end/get_products.php on line 66
Rows are returned from the database still, but they contain no information. Can this function be split up successfully?