Php 使用smarty和mysql数据库?

Php 使用smarty和mysql数据库?,php,mysql,smarty,Php,Mysql,Smarty,这是我第一次需要使用smarty,而且看起来很简单 然而,我的PHP代码中存在扭曲,这导致了一个问题 以下是我试图做的: 在你开始因为我没有使用mysqli函数等而责骂我之前,请注意,这段代码只是一个简单的测试,让我先了解smarty。所以我不会在我的项目中使用mysql,我不建议任何人这样做 不管怎样,我想做的是: 我在index.php页面中使用以下代码: <?php header("Content-type: text/html; charset=utf-8"); function

这是我第一次需要使用
smarty
,而且看起来很简单

然而,我的PHP代码中存在扭曲,这导致了一个问题

以下是我试图做的:

在你开始因为我没有使用mysqli函数等而责骂我之前,请注意,这段代码只是一个简单的测试,让我先了解smarty。所以我不会在我的项目中使用mysql,我不建议任何人这样做

不管怎样,我想做的是:

我在
index.php
页面中使用以下代码:

<?php
header("Content-type: text/html; charset=utf-8");
function isSubdomain()
{
    $host = $_SERVER['HTTP_HOST'];
    $host = explode('.',$host);
    $host = (is_array($host)?$host[0]:$host);
    return $host;
}
?>
<?php
// These are the smarty files
require 'libs/Smarty.class.php';

// This is a file which abstracts the DB connecting functionality (Check out PEAR)
include "config/connect_to_mysql.php";

$smarty = new Smarty;

$smarty->compile_check = true;
$smarty->debugging = false;
$smarty->use_sub_dirs = false;
$smarty->caching = true;

// This SQL statement will get the 5 most recently added new items from the database

$storeShop = isSubdomain();
echo $storeShop;

$sql = 'SELECT * ';
$sql .= 'FROM $storeShop ';
$sql .= 'ORDER BY `id` ';

$result = mysql_query($sql) or die("Query failed : " . mysql_error());

// For each result that we got from the Database
while ($line = mysql_fetch_assoc($result))
{
 $value[] = $line;
}

// Assign this array to smarty...
$smarty->assign('storeShop', $value);



// Assign this array to smarty...
$smarty->assign('$storeShop', $value);

// Display the news page through the news template
$smarty->display('index.tpl');

// Thanks to David C James for a code improvement :)
?>
在浏览器中运行
index.php
时,出现以下错误:

Query failed : Table 'mrshoppc_mainly.$storeShop' doesn't exist
但是当我使用下面的代码时,我得到了正确的输出,即子域的
名称
以及mysql数据库中表的
名称

$storeShop = isSubdomain();
echo $storeShop;
我知道桌子是存在的。另外,表名
$storeShop
是动态的,因此它可以是用户选择的任何名称,并将在mysql数据库中创建

我希望我解释得足够好,有人能帮助我

有人能告诉我为什么会出现上述错误以及如何解决它吗

我怀疑这是由smarty造成的,因为在我开始使用smarty之前,我从未遇到过这个错误


提前谢谢

您没有解析包含PHP变量的字符串

$sql .= 'FROM $storeShop ';
在PHP中,单引号的stings
实际上就是引号之间的stings

双引号字符串将由PHP解释

试试这个:

$sql .= "FROM $storeShop ";  // OR
$sql .= 'From '. $storeShop .' ';

我已经很久没有使用smarty了,但据我记忆,没有这样的皮带:

{$storeShop[$storeShop].id} 
但是,您可以使用:
{$storeShop.$other_storeShop.id}
如果$storeshop类似于数组('storeshop_key'=>array('id'->'id'))

同时
$smarty->assign('$storeShop',$value)将创建不正确的变量$$storeShop

提示:在发送到smarty
var_dump($value)
之前,用php打印数组,然后在smarty中使用
{$storeShop}@print_r}
确保一切正常

只需删除即可

$smarty->assign('$storeShop', $value);

从PHP代码中

如果希望解析变量,则需要使用双引号进行查询。既然您不知道这一点,我建议您在处理数据库驱动的网站之前,可能需要进行大量的初步学习。查找PHP入门,了解该语言的工作方式。如果你没有克服对基础知识的理解上的差距,那么生活就会轻松得多。@BrianWarshaw,感谢你的回复和你对我在使用核心PHP 3年后对PHP理解的批评。我假设你从来没有犯过那些校童错误,并且总是生成一个没有bug的顶级noch PHP代码。我只希望我能像那样呆一天。:)我的意图是帮助你,而不是侮辱你。当然,我们都会犯错误,但您的错误似乎表明您不熟悉一些基本的语言功能。如果不是这样,那就太棒了。
$smarty->assign('$storeShop', $value);