skip to Main Content

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


  1. The documentation clearly states:

    Returns an associative array representing the fetched row, where each key in the array represents the name of one of the result set’s columns, null if there are no more rows in the result set, or false on failure.

    You have the array with config_name and config_value keys, but trying to access site_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.

    $query = "SELECT config_name, config_value FROM site_config WHERE config_name = 'site_name'";
    
    Login or Signup to reply.
  2. 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, but mysqli_fetch_all is simpler.

    Once you’ve got that, you should be able to use your foreach loop from your old code.

    $query = "SELECT config_name, config_value FROM site_config";
    $result = mysqli_query($con, $query);
    $configs = mysqli_fetch_all($result, MYSQLI_ASSOC);
    foreach ($configs as $con) {     
      $config[$con['config_name']] = $con['config_value']; 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search