can someone help me to convert this query for Mysqli?
/* Load website settings */
$config = array();
$configs = $db->QueryFetchArrayAll("SELECT config_name,config_value FROM `site_config`");
foreach ($configs as $con)
{
$config[$con['config_name']] = $con['config_value'];
}
unset($configs);
This code is placed in the main.php file which gets called to every necessary page. It includes all necessary functions and as well db connection.
I have tried:
$query = "SELECT config_name, config_value FROM site_config";
$result = mysqli_query($con, $query);
$config = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf("%s (%s)n", $config["config_name"], $config["config_value"]);
Which basically works because value gets printed, but if I do:
My website title is: About <?=$config['site_name']?>
I’m getting
Warning: Undefined array key "site_name"
I have: site_name as config_name and my website as config_value.
Please do not tell me to read associate or general arrays tutorials because I’ve spent hours reading them already. Thanks
2
Answers
The documentation clearly states:
You have the array with
config_name
andconfig_value
keys, but trying to accesssite_name
key, which obviously doesn’t exist.You have to iterate over the array and check
if ($config["config_name"] == "site_name")
and act accordingly.Or just use a
WHERE
clause.First get all the rows with
$configs = mysqli_fetch_all($result, MYSQLI_ASSOC);
(see https://php.net/manual/en/mysqli-result.fetch-all.php). As per its own documentation,mysqli_fetch_assoc
only fetches one row at a time. You can (as per the examples in that function’s documentation), use a loop to call it repeatedly until there are no more rows, butmysqli_fetch_all
is simpler.Once you’ve got that, you should be able to use your
foreach
loop from your old code.