2014-04-29 29 views
-5

我一直在尝试几个小时到assign mysql rows in smarty php没有运气。如何在smarty php中分配mysql行?

我有这个在product.php文件:

require 'libs/Smarty.class.php'; 

$smarty = new Smarty; 

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

if (isset($_GET['id'])) { 
    // Connect to the MySQL database 
    include "config/connect.php"; 
    $id = preg_replace('#[^0-9]#i', '', $_GET['id']); 
    // Use this var to check to see if this ID exists, if yes then get the product 
    // details, if no then exit this script and give message why 
    $storeShop = isSubdomain(); 
    $sql = "SELECT * FROM $storeShop WHERE id='$id' LIMIT 1"; 
    $query = mysqli_query($db_conx, $sql); 
    $productCount = mysqli_num_rows($query); // count the output amount 
    if ($productCount > 0) { 
     // get all the product details 
      while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){ 

      $value[] = $line; 
      $id = $row["id"]; 
      $product_name = $row["product_name"]; 
      $price = $row["price"]; 
      $shipping = $row["shipping"]; 
      $details = $row["details"]; 
      $category = $row["category"]; 
      $manu = $row["manu"]; 
     } 

    } 

} 

$smarty->display('product.tpl'); 

,这就是我在product.tpl文件:

{if isset($smarty.get.id)} 


     {$smarty.get.id.product_name) 
<img src="images/{$smarty.get.id}Image1.jpg" alt="" border="0" width="120" height="100" /> 
{/if} 

,我能得到展示的唯一的事情就是图像,但我不能得到rows。例如:$product_name

有人可以帮助我,因为它真的给我一个很大的头痛。

谢谢你在前进,

+0

当使用'mysqli'时,您应该使用参数化查询和['bind_param'](http://php.net/manual/en/) mysqli-stmt.bind-param.php)将用户数据添加到您的查询中。 **不要**使用字符串插值来实现此目的,因为您将创建严重的[SQL注入漏洞](http://bobby-tables.com/)。在'$ _GET'数据上挥动正则表达式并不奇怪地使其安全。正确地逃脱它。 – tadman

+0

@tadman,我认为你的信息遍布谷歌,stackoverflow,雅虎,bing,php.net,谷歌和大约20000个博客上的所有论坛。所以请坚持回答这个问题,如果你不知道答案,那么你就知道该怎么做! – user3585872

+0

@ user3585872如果你会因为有人指出某些人令人惊讶仍然不知道的东西而失礼,那么人们可能不会帮助你。公平地说,你的正则表达式应该照顾你的情况。另外,如何在Smarty中分配变量在smarty文档中,很容易找到。 ;)(也在下面发布的答案中) – Jon

回答

1

从手册: http://www.smarty.net/crash_course

include('Smarty.class.php'); 

// create object 
$smarty = new Smarty; 

// assign some content. This would typically come from 
// a database or other source, but we'll use static 
// values for the purpose of this example. 
$smarty->assign('name', 'george smith'); 
$smarty->assign('address', '45th & Harris'); 

// display it 
$smarty->display('index.tpl'); 

你需要调用$smarty->assign()你想传递给模板中的每个变量。

--------- -----------编辑
$smarty->assign()需要两个参数:
1.名称您想使用的访问值模板文件(字符串)
2.您要访问的实际值

+0

就是这样。我尝试在我的php文件中添加'$ smarty-> assign('product_name','product_name');'在我的tpl文件中添加'{$ product_name}',并且在输出中完全没有任何内容。 – user3585872

+1

'$ smarty-> assign('product_name',$ product_name);'或者使用一个数组在模板中使用'$ product.key' – Jon

+0

@Jon,$ product.key从哪里来? – user3585872