我写下了以下一段代码:
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
$db = new PDO ('mysql:host=localhost;dbname=ozdatabase;charset=utf8', 'root', '');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, 'ERRMODE_EXCEPTION');
$stmt = $db->prepare("SELECT id, users FROM ozusers WHERE username=? AND password=?");
$stmt->execute(array($username, $password));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$id = $rows['id'];
$user = $rows['users'];
if ($id) {
print "Logged";
}
else {
print "not good";
}
?>
这是HTML表单:
<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<fieldset >
<LEGEND>COMMUNICATION</LEGEND>
<input type='hidden' name='submitted' id='submitted' value='1' />
<label for='username' >UserName*:</label>
<input type='text' name='user' id='username' maxlength="50" />
<label for='password' >Password*:</label>
<input type='password' name='pass' id='password' maxlength="50">
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form>
我在尝试登录页面时收到错误并写了: &#34;致命错误:在第15行&#34;
上的非对象上调用成员函数execute()为什么会这样?我遵循了最佳实践指南,它显示使用&#34; execute()&#34;功能完全像...
由于
答案 0 :(得分:3)
ERRMODE_EXCEPTION是不断引用它的引用
$db->setAttribute(PDO::ATTR_ERRMODE, ERRMODE_EXCEPTION);//Your code fails at this line
答案 1 :(得分:0)
<?php
//error_reporting(0);
$username = $_POST['user'];
$password = $_POST['pass'];
// Connecting, selecting database
$db = new PDO ('mysql:dbhost=localhost;dbname=ozdatabase;charset=utf8', 'root', '');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, ERRMODE_EXCEPTION);
//first
$stmt = $db->prepare("SELECT id, users FROM ozusers WHERE username = :username AND password = :password");
$stmt->execute(array(':username'=>$username, ':password' => $password));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows AS $r) {
$id = $r['id'];
$user = $r['users'];
}
if ($id) {
print "Logged";
}
else {
print "not good";
}
?>
答案 2 :(得分:0)
在try catch中包装数据库init以捕获任何连接失败。
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
目前db-&gt; prepare()失败,返回false,因此不允许你在非对象上调用execute。