I am having trouble with PHP, where I populate an array with results from a MySQL query.
The problem is when I make a function to echo a certain element of the array, it's not working, where as without a function there are no errors.
Establish connection, perform query, store result in variable:
require_once("db.php");
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM arlista";
$query_result = mysqli_query($conn, $query);
mysqli_close($conn);
$result_array = array();
I pass the query results to an array, then I want to query a single value from the array. The problem is if I use a function like this, this does not work. I can't get the element of the array to display in the browser.
function arlista($attr, $rownum){
while($row = mysqli_fetch_array($query_result)){
$result_array[$i] = $row[$attr];
$i++;
}
echo $result_array[$rownum];
}
arlista("ar",1);
However this works if I do not use a function. The browser is displaying the value.
while($row = mysqli_fetch_array($query_result)){
$result_array[$i] = $row["ar"];
$i++;
}
echo $result_array[1];
Could someone explain what is going wrong with the function or how do I fix it to work? Thank you!
The server is running PHP 5.6.19
0when used in an arithmetic context.