0

我正在尝试将它们放在一个单独的文件中,该文件将包含在每个页面上

$sql = 'select id, name, age, address, pincode from json where name = :name';
$arr = array(":name" => $name);
// There are some 30 diff sql's and arrays

另一个页面

$name = 'peter';
$conn = connect();

function myType(){
global $conn;
global $sql; 
global $arr; 
$stmt = $conn->prepare($sql);
$stmt->execute($arr);

while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
      foreach ($row as $value) {
      echo $value.' <br>';
      }
   }
}

myType();

我试图将 sqls 和数组保存在一个单独的文件中,并在需要时使用它们。保持物品清洁且易于维护。但是变量是稍后声明的,这给了我:Notice: Undefined variable: name in C:\web\apache\htdocs\dev\json.php on line 24

你能找到一种方法来做到这一点而不使事情变得丑陋吗?

4

2 回答 2

0

那么你应该使用两个文件

  1. sql.php
  2. 获取.php

然后在 fetch.php 你将使用require_once 'sql.php'

这是 fetch.php 的代码:

$name = 'peter';
$conn = connect();
require_once 'sql.php';
function myType(){
global $conn;
global $sql; 
global $arr; 
$stmt = $conn->prepare($sql);
$stmt->execute($arr);

while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
      foreach ($row as $value) {
      echo $value.' <br>';
      }
   }
}

myType();

这是 sql.php

$sql = 'select id, name, age, address, pincode from json where name = :name';
$arr = array(":name" => $name);

这应该很有帮助,您可以随时使用 sql.php。

于 2013-06-17T12:46:57.893 回答
0

将查询和绑定参数存储在单独的包含中有点奇怪。包含后如何更改绑定参数?

我的建议是创建一个模型来处理数据库操作。这样做的好处是您可以封装数据库工作并将其与您的应用程序逻辑分开,并且还可以轻松地在整个过程中重用它。

基本示例:

class CustomersModel
{
    protected $db;

    public function __construct($db)
    {
        $this->db = $db;
    }

    public function getByName($name)
    {
        $result = array();
        $sql = 'select id, name, age, address, pincode from json where name = :name';

        if($stmt = $conn->prepare($sql))
        {
            $stmt->execute(array(":name" => $name));
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        return $result;
    }
}

用法:

require_once('/path/to/CustomerModel.php');
$conn = connect();

$model = new CustomerModel($conn);
$customers = $model->getByName('peter');

foreach($customers as $c)
{
    echo htmlspecialchars($c['name']) . '<br />;
}
于 2013-06-17T13:04:38.783 回答