I am building a CMS,
The CMS information is stored in a mysql
database
inside a table
called cms_settings
I want to get the setting_value
and store it to a variable, for example:
$cms_url = ?;
$cms_theme = ?;
I've tried to use the mysqli_fetch_array()
but I couldn't make it right.
<?php
require('db.php');
$s = mysqli_query($conn, "SELECT * FROM cms_settings");
$i = mysqli_fetch_array($s);
foreach($i as $key=>$value)
{
$cms_url = $i[0][2];
}
?>
but that didn't work!
your help is highly appreciated,
You need to loop through your results. Maybe try something like this:
<?php
require('db.php');
$settings = array();
$s = mysqli_query($conn, "SELECT * FROM cms_settings");
while($row = mysqli_fetch_assoc($s)) {
$settings[$row['setting_name']] = $row['setting_value'];
}
edit: added saving your settings into an array.
edit2: If you want to get specific settings, maybe put it in a function.
function getSetting($name) {
require('db.php');
$name = mysqli_real_escape_string($conn, $name);
$s = mysqli_query($conn, "SELECT * FROM cms_settings WHERE `setting_name` = '{$name}'");
while($row = mysqli_fetch_assoc($s)) {
return $row['setting_value'];
}
return false;
}
Its not working because you array is $I and your foreach loop is looping through the $key=>value, but in your foreach you are still referencing $i.
Instead, do this:
while($row = mysqli_fetch_array($s)) {
$cms_url = $row['cms_url'];
}
EDIT:
A foreach loop in this case would not be ideal as you would battle to give each result a unique variable name as a foreach loop will loop through each array item and apply the required tasks to the current value
You can create an array named 'cms_settings' and fill the array with the keys from your result
<?php
require('db.php');
$s = mysqli_query($conn, "SELECT * FROM cms_settings");
$i = mysqli_fetch_assoc($s);
$cms_settings= array();
foreach($i as $row)
{
$cms_settings[$row['setting_name']] = $row['setting_value'];
}
/* show a setting */
echo 'CMS url is: '.$cms_settings['cms_url'];
/* show all settings */
print_r($cms_settings);
?>