有人可以帮助我检查表用户是否有用户名? 我正在使用SQLite3,PHP和PDO,我编写了像
这样的代码 try {
$db = new PDO('sqlite:/var/db/db_users.db');
$query = 'SELECT COUNT(*) FROM users WHERE username= :username';// moze LIMIT 1 da se stavi jer je sigurno jedan sa istim username i password sine
$sth = $db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':username' => $username));
$result = $sth->fetchAll();
} catch (Exception $e) {
return (array('message' => 'error'));
}
但没有single_fetch或我找不到。任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
只需使用一次获取..因为只有一行你jsut像普通一样获取它而不是循环然后关闭光标。如果你只是在特定值之后,你也可以突然拉出这个列......
try {
$db = new PDO('sqlite:/var/db/db_users.db');
// add an alias.. not really necessary but good practice
$query = 'SELECT COUNT(*) AS usercount FROM users WHERE username= :username';
$sth = $db->prepare($query);
$sth->execute(array(':username' => $username));
// just call regular fetch for the first an only result
// use fetch(PDO::FETCH_COLUMN) or fetchColumn to jsut get
// a single column value from the row
$result = $sth->fetchColumn(0);
// be nice and close the cursor since we are done.
$sth->closeCursor();
} catch (Exception $e) {
return (array('message' => 'error'));
}