如何在函数内部进行PDO查询

时间:2011-11-18 10:48:44

标签: php pdo

我尝试在函数内部创建一个PDO sql,但它不起作用。得不到回应。它不工作时使用。我的目的是让我的代码变小。任何人都可以发光。感谢。

function Test() {

    $get_name = $smt->prepare("SELECT * FROM customer WHERE id = '1'");
    $get_name->execute();

    foreach ($get_name as $temp) {
        $name = $temp['name'];
        $address = $temp['address'];
        $phone = $temp['phone'];
        $page = $temp['page'];
    }

    eval("\$page = \"$page\";");
    echo $page;

    eval("\$page = \"$page\";");
    echo $page;

}

Test();

2 个答案:

答案 0 :(得分:11)

我可能会将您的代码重构为:

function getCustomerInfo(PDO $pdo, $customerId) 
{
    // use a prepared statement that can get you info on any customer
    $statement = $pdo->prepare(
        "SELECT * FROM customer WHERE id = :customerId LIMIT 1");
    // get the result resource from the database
    $result = $statement->execute(array(
        ':customerId' => $customerId
    ));
    // fetch the first row in the result as an associative array
    // and return it to the caller.
    return $result->fetchFirst(PDO::FETCH_ASSOC);
}

// use your connection in place of $pdo
$customerData = getCustomerInfo($pdo, 1);

// now you can do stuff with your data
var_dump($customerData);

这更好,因为它不依赖于全局状态,功能永远不应该这样做。它使用准备好的参数化sql,使其更快,并且该函数对于id = 1的客户更有用。

答案 1 :(得分:6)

您需要在函数

中使pdo实例全局化
function Test() {

    global $smt;