Php 如何使PDO查询在函数内部工作
我试图在函数内部创建一个PDO sql,但它不起作用。没有得到任何回应。它在不使用函数时工作。我的目的是使我的代码变小。任何人都可以发光。谢谢Php 如何使PDO查询在函数内部工作,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 = $te
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();
您需要在函数中使pdo实例成为全局的
function Test() {
global $smt;
我可能会将您的代码重构为:
这更好,因为它不依赖全局状态,函数永远不应该这样做。它使用了预先准备好的、参数化的sql,使其速度更快,并且该函数对除id=1的客户以外的其他客户更有用。并且可能会检查它是否定义为全局思维,在局部范围内行动!
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);