I have the following code...
$rec = "Ashen Polish";
include("database_connect.php");
$db= $conn;
$tableName="wh_recipes";
$columns= ['recipe', 'item_descr_1', 'item_descr_2', 'skill', 'req_skill', 'kit', 'material_1', 'm1n', 'material_2', 'm2n', 'material_3', 'm3n', 'material_4', 'm4n', 'material_5', 'm5n', 'material_6', 'm6n', 'material_7', 'm7n', 'notes'];
$fetchData = fetch_data($db, $tableName, $columns);
function fetch_data($db, $tableName, $columns){
if(empty($db)){
$msg= "Database connection error";
}elseif (empty($columns) || !is_array($columns)) {
$msg="columns Name must be defined in an indexed array";
}elseif(empty($tableName)){
$msg= "Table Name is empty";
}else{
$columnName = implode(", ", $columns);
$query = "SELECT ".$columnName." FROM ".$tableName ." WHERE recipe='".$rec."' ";
$result = $db->query($query);
if($result== true){
if ($result->num_rows > 0) {
$row= mysqli_fetch_all($result, MYSQLI_ASSOC);
$msg= $row;
} else {
$msg= "No Data Found";
}
}else{
$msg= mysqli_error($db);
}
}
return $msg;
}
I am trying to fill a table with with all the information regarding a particular recipe in my database by calling the name of the recipe to populate it using the $rec variable, however $rec does not return a value and I receive the message "no data found", if I replace the $rec variable with the actual recipe name then the correct data is displayed, I assume that I am getting the concatenation wrong for the "where" part of the query.
I have looked at a few solutions on Stack Overflow that seem to work for others and I cant seem to get any of them working for my example.
My current solution is base upon How to pass a php variable in WHERE clause of SELECT statement? , this is the closest example I could find to what I'm trying to do but doesn't seem to work for me for some reason.
It's just that $rec is not defined inside the scope of the function, you need to pass it in (as a parameter) and it will work, this line:
function fetch_data($db, $tableName, $columns){
should be fixed like this:
function fetch_data($db, $tableName, $columns, $rec){