簡體   English   中英

使用PHP和Smarty模板的SQL查詢

[英]SQL queries with PHP and smarty templates

我正在嘗試在我的results.tpl頁面上顯示來自SQL查詢的結果。

我整天都在朝着這個方向努力,有人可以看看我的代碼並指出正確的方向嗎? 還是我最好嘗試執行某種javascript / ajax來使其正常工作?

對於上下文,我使用的是預定的計划程序。 為了使頁面與站點模板相匹配-我必須鏈接到results.php,該結果將轉到resultspage.php,其結果將顯示在results.tpl中。 但是我不能將results.php放在smarty-> display中。

基本上,這就是我要執行的操作的流程。 我需要添加更多的查詢/結果,但我只是想使基礎知識起步...

scan.tpl用戶輸入數字-> handler.php查詢數據庫-> results.tpl顯示結果

任何幫助深表感謝!

scan.tpl

{include file='globalheader.tpl'}
<div id="xx">
<form action="handler.php" method="post" >
<input type="number" name="barcode" value="1" />
<input type="submit" value="Submit" name="submit" />
</form >
</div>
{include file='globalfooter.tpl'}

handler.php

{require_once('c:/xxx/Smarty/Smarty.class.php');
$smarty = new Smarty();
$host = "xxx";
$user = "xxx";
$password = "xxx";
$database_name = "xxx";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

$search=$_POST['barcode'];
$query = $pdo->prepare("SELECT * FROM xxx WHERE xxx LIKE '$search' LIMIT 0 ,   10");
$query->bindValue(1, "$search", PDO::PARAM_STR);
$query->execute();

$results = $query->fetch();

$smarty->assign('output', '$results');
$smarty->display('results.tpl')

results.tpl

{include file='globalheader.tpl'}
<div id="xx">
{$output}
</div>
{include file='globalfooter.tpl'}

看來,您的handler.php有一些錯誤。 首先,您必須使用<?php啟動php文件。 其次,字符串替換僅適用於雙引號字符串-但如果不需要替換,只需使用var。

<?php
require_once('c:/xxx/Smarty/Smarty.class.php');
$smarty = new Smarty();
$host = "xxx";
$user = "xxx";
$password = "xxx";
$database_name = "xxx";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

$search=$_POST['barcode'];
$query = $pdo->prepare("SELECT * FROM xxx WHERE xxx LIKE '$search' LIMIT 0 ,   10");
$query->bindValue(1, $search, PDO::PARAM_STR);
$query->execute();

$results = $query->fetchAll(PDO::FETCH_ASSOC);

$smarty->assign('output', $results);
$smarty->display('results.tpl')

您還應該在output.tpl文件中使用某種循環來顯示結果。

{include file='globalheader.tpl'}
<div id="xx">
<ul>
{foreach from=$output item="item"}
    <li>{$item.xxx}</li>
{/foreach}
</ul>
</div>
{include file='globalfooter.tpl'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM