我试图在函数内部创建一个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();
Run Code Online (Sandbox Code Playgroud)
Kri*_*ris 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);
Run Code Online (Sandbox Code Playgroud)
这是更好的,因为它不依赖于全局状态,功能永远不应该这样做.它使用准备好的,参数化的sql,使其更快,并且该功能对于id = 1的客户更有用.