Reputation: 87
I wrote thte following piece of code:
<?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";
}
?>
This is the HTML Form:
<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>
I get an error when trying to login in the page and it's written: "Fatal error: Call to a member function execute() on a non-object in.. On line 15"
Why is this happening? I followed best practice guide and it showed to use the "execute()" function exactly like that..
Thanks
Upvotes: 0
Views: 90
Reputation: 5071
<?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";
}
?>
Upvotes: 0
Reputation: 22532
ERRMODE_EXCEPTION is constant wrap off quotes from it
$db->setAttribute(PDO::ATTR_ERRMODE, ERRMODE_EXCEPTION);//Your code fails at this line
Upvotes: 3
Reputation: 360
Wrap your database init in try catch to capture any connection failures.
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Currently the db->prepare() is failing, returning false and therefor not allowing you to call execute on a non object.
Upvotes: 0