php - 如何使 PDO 查询在函数内部工作

标签 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();

最佳答案

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

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 以外的客户更有用。

关于php - 如何使 PDO 查询在函数内部工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8181202/

相关文章:

php - Codeigniter 项目在本地工作但不在线 - 找不到 404 页面

php - 在 macOS Mojave 10.14.2 上升级 PHP 有哪些选项?

php - Laravel PDO 找不到驱动程序

php - 构建面向对象软件的好资源或书籍

PHP - 基于 Off Factor 对数组进行排序::usort?

php - MySQL 语句注入(inject)安全吗?

php - 将 password_hash 与 bindParam 一起使用

PHP 7 session_regenerate_id 失败和 PDO 调用成员函数prepare() null

php - 出现 'Class PDO not found' 错误

javascript - 使用 FormData 对象获取 CKeditor 值