我尝试在函数内部创建一个 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/