gpt4 book ai didi

php - 使用 PHP 和 smarty 模板进行 SQL 查询

转载 作者:行者123 更新时间:2023-11-29 21:24:38 27 4
gpt4 key购买 nike

我正在尝试在 results.tpl 页面上显示 SQL 查询的结果。

我一整天都在努力反对这个问题,有人可以看看我的代码并为我指出正确的方向吗?或者我最好尝试做某种 javascript/ajax 来让它工作?

就上下文而言,我正在使用预订的调度程序。为了使页面与站点模板相匹配 - 我必须链接到 results.php,该 PHP 会转到 resultspage.php,该 PHP 会转到 results.tpl。但我无法将 results.php 放入 smarty->display 中。

基本上这就是我想做的事情的流程。我需要添加更多查询/结果,但我只是想让基础知识发挥作用......

scan.tpl用户输入数字->handler.php查询数据库->results.tpl显示结果

非常感谢任何帮助!

扫描.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')

结果.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'}

关于php - 使用 PHP 和 smarty 模板进行 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35566640/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com