我刚刚从mySQLi(从mySQL)切换到PDO,到目前为止一切都很好,也很容易,尤其是关于准备好的语句
这就是我准备好的带预选语句的东西
主数据库文件(包含在所有页面中):
class DBi {
public static $conn;
// this I need to make the connection "global"
}
try {
DBi::$conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuname, $dbpass);
DBi::$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
DBi::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo '<p class="error">Database error!</p>';
}
在我的页面中:
try {
$sql = 'SELECT pagetitle, pagecontent FROM mypages WHERE pageid = ? LIMIT 1';
$STH = DBi::$conn->prepare($sql);
$STH->execute(array($thispageid)); // $thispageid is from a GET var
}
catch(PDOException $e) {
echo '<p class="error">Database query error!</p>';
}
if ($STH) { // does this really need an if clause for it self?
$row = $STH->fetch();
if (!empty($row)) { // was there found a row with content?
echo '<h1>'.$row['pagetitle'].'</h1>
<p>'.$row['pagecontent'].'</p>';
}
}
一切正常。但是我做对了吗?还是可以简化一些地方?
使用if(!empty($ row)){}是一种好的解决方案,用于检查结果行是否包含内容?在准备好的缩小选择中找不到其他体面的方法来检查数字
catch(PDOException $e) {
echo '<p class="error">Database query error!</p>';
}
我将借此机会记录发生哪个数据库查询错误。
在此处查看示例:http : //php.net/manual/en/pdostatement.errorinfo.php
同样,如果发现错误,则可能应该return
从函数或脚本中进行。
if ($STH) { // does this really need an if clause for it self?
如果$STH
无效,则它应该已经生成了异常并已被先前捕获。而且,如果您从该catch块中的函数返回了代码,那么您将到达代码中的这一点,因此无需再次测试$STH
是否为非null。刚开始从中获取。
$row = $STH->fetch();
if (!empty($row)) { // was there found a row with content?
我会这样写:
$found_one = false;
while ($row = $STH->fetch()) {
$found_one = true;
. . . do other stuff with data . . .
}
if (!$found_one) {
echo "Sorry! Nothing found. Here's some default info:";
. . . output default info here . . .
}
无需测试是否为空,因为如果为空,则循环将退出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句