数据库表中的网站设置
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,
我正在构建CMS, p>
CMS信息存储在 名为 我想获取 我尝试使用 但这不起作用 ! p>
非常感谢您的帮助, p>
div> cms_settings code> p>
表 code>中的
mysql code>
database code> “https://i.stack.imgur.com/euatp.png"alt =”cms_settings table“> p>
setting_value code>并存储 它是一个变量,例如: p>
$ cms_url =?;
$ cms_theme =?;
code> pre>
mysqli_fetch_array() code>,但我做不到。 p>
&lt;?php
require( 'db.php');
$ s = mysqli_query($ conn,“SELECT * FROM cms_settings”);
$ i = mysqli_fetch_array($ s);
foreach($ i as $ key =&gt; $ 值)
{
$ cms_url = $ i [0] [2];
}
?&gt;
code> pre>
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);
?>