$pdo=new pdo(mysql:host=localhost;dbname=t1,root,); $stmt=$pdo->prepare(select * from table1); $stmt->execute(); $res=$stmt->fetchall(pdo::fetch_assoc); echo count($res);
回复内容: 页面需要用到总的条数 需要在这个页面一直展示 那么这个代码这样写可以吗 每次刷新页面都要去数据库里面查询一次吗 是不是影响性能呢?如果数据库有几万条数据怎么办?
$pdo=new pdo(mysql:host=localhost;dbname=t1,root,); $stmt=$pdo->prepare(select * from table1); $stmt->execute(); $res=$stmt->fetchall(pdo::fetch_assoc); echo count($res);
为什么不用 select count(*) from table
$stmt=$pdo->prepare(select count(*) as num from table);
$stmt->execute();
$res=$stmt->fetch(pdo::fetch_assoc);
return $res['num']
访问峰值的时候有点占内存了,可以考虑在insert语句和del语句的时候,把数据统计出来放在别的地方
你这么写肯定是每次都连接,你可以单独吧pdo封装一个类,实用单例模式进行处理,就避免了每次执行curd的时候都要尽兴连接操作了。我很早之前写过的例子:
true, pdo::attr_errmode => pdo::errmode_exception, pdo::mysql_attr_init_command => 'set names utf8' ) ); return self::$safepdo; } catch ( exception $e ) { throw $e; } } /** * description 覆盖__clone()方法,禁止克隆 */ private function __clone() { } /** * description 单例模式,实例化调用数据库链接 */ public static function calldb() { if (self::$safepdo == null) { self::$safepdo = self::pdolink (); } return self::$safepdo; }}
希望对你有帮助
