2011-03-04 51 views
0

我对mysqli预处理语句有基本的疑问。例如,我想执行SELECT查询,我应该这样做:关于mysqli预处理语句的问题

<? 
$city = "Amersfoort"; 

if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) { 
    $stmt->bind_param("s", $city); 
    $stmt->execute(); 
    $stmt->bind_result($district); 
    $stmt->close(); 
} 
$mysqli->close(); 
?> 

在上面的代码中,bind_result也是必需的吗?它究竟做了什么?

另外,我需要每次查询后关闭mysqli连接吗? 谢谢。

回答

2

bind_result使得它如此,当你遍历查询的结果,从结果集的列会自动映射到局部变量。

例如,假设您执行返回结果有三列设置这样的查询:

$query = "SELECT Name, CountryCode, District FROM myCity"; 

要执行的查询和做的结果的东西,比方说打印出来:

if ($result = $mysqli->query($query)) { 
    while ($row = $result->fetch_row()) { 
     printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]); 
    } 
} 

上述代码的“问题”是$row[0]不是很具描述性。另一种方法是使用bind_result,这是这样的:

$query = "SELECT Name, CountryCode, District FROM myCity"; 

if ($stmt = $mysqli->prepare($query)) { 
    $stmt->bind_result($name, $countryCode, $district); 

    while ($stmt->fetch()) { 
     printf("%s (%s,%s)\n", $name, $countryCode, $district); 
    } 
} 

正如你看到的,每次使用bind_result当你调用fetch变量$name$countryCode$district与值自动填充从目前的结果行。有一些你必须确保的细节,请阅读the documentation了解更多信息。

要回答您的其他问题:您并不需要,而且确实您不会在每次查询后关闭连接(除非您非常清楚自己在做什么)。

+0

感谢您的详细和明确的解释。 – Jay 2011-03-04 23:48:20

+0

@adam:很高兴帮助! – Jon 2011-03-05 00:06:58