PDO/PHP LoginScript ending in error 500 using MAMP - php

I've been trying for a while now to get my loginscript working and i can't seem to find the issue, either im just blind or there's something else going on here.
It doesn't matter if i input the correct credentials or not into the form, i still end up getting a lovely error 500.
Any ideas?
The DB connect funtion:
function db_connect() {
if i move this column-->
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
<---
return $conn; /added this as suggested, still returns NULL.
}
The login file:
include('../lib/functions.php'); //This is correct!
db_connect();
<-- HERE, it works -->
Earlier had an issue where my password hash during register was faulty, so password_verify($_POST['password'], $results['passw'])had no effect, always returning false even with correct input.
if(!empty($_POST['username']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT uname,passw FROM users WHERE uname = :user AND passw = :pass');
$records->bindparam(':user', $_POST['username']);
$records->bindparam(':pass', $_POST['password']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0 && password_verify($_POST['password'], $results['passw']) && $_POST['username'] == $results['uname']) //Also tried removing the &&-->username area incase two and statements were wrong without any luck {
die('It works!');
} else {
die('OR NOT!');
}
endif;

Your db_connect() function defines $conn in it's own scope. So, variable $conn is local. And after db_connect() ends executing $conn just disappears.
Outside this function $conn is simply NULL.
Return $conn to outer scope from your function:
function db_connect() {
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
return $conn; // here
}
And in your script:
include('../lib/functions.php'); //This is correct!
$conn = db_connect();
// other codes

Related

Parsing Json From PHP to Xcode(Swift) with Mysql query

Morning All,
Im after a bit of advice/help with the below issue.
i have tried looking around and google'ing but I still don't understand where I'm going wrong. Please forgive me as I'm a complete noob at this.
some of you may have seem this code before but I'm want to adapt it. Once the user logs in i want to get the user ID from the MySQL Database and send that to swift in the JSON but i can't get it to work, i have tried putting the query in different places with no luck, JSON is completely new to me :(
Ideally > user logs in> swift sends JSON to verify>JSON-PHP verified by MySQL > PHP - JSON reply with success AND user id from the db.
Any Help would be amazing !!
<?php
header('Content-type: application/json');
require("conn.php");
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = '***';
$db_user = '***';
$db_password = '***';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username = ? and password = ?")) {
$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($id);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($id) {
error_log("User $username: password match.");
echo '{"success":1, "ID":0}';
} else {
error_log("User $username: password doesn\'t match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
} else {
echo '{"success":0,"error_message":"Invalid Username/Password."}';
}
}else {echo '{"success":0,"error_message":"Invalid Data."}';
}
?>

PDO MSSQL error query on null

I am trying to select rows from my database table, and I am getting an error stating that
Fatal error: Call to a member function query() on null in..
Our connection to the database shows successful. Below is my php code:
<?php
require_once("dbconn.php");
$db = getConnection();
$input_pid = "870104-07-5448";
$sql = "SELECT * FROM Pat WHERE PID ='$input_pid'";
$stmt = $db->query($sql);
$row = $stmt->fetchObject();
echo $row->PID;
echo $row->Name;
?>
This is the dbconn.php code:
function getConnection(){
try {
$hostname = "busctrlctr-pc";
$dbname = "DispenserSystem";
$username = "sa";
$password = "123456";
$db = new PDO ("sqlsrv:Server=$hostname;Database=$dbname", $username, $password);
echo 'We are succesful to connect the database !!'.'<br>'; // successful word
} catch (PDOException $e){
echo "connection failed problem is >> ". $e -> getMessage()."\n";
exit;
}
}
Can i know why I am getting this error. Thank you.
You never return $db in your funtion getConnection();
change the funtion to:
function getConnection(){
try {
$hostname = "busctrlctr-pc";
$dbname = "DispenserSystem";
$username = "sa";
$password = "123456";
$db = new PDO ("sqlsrv:Server=$hostname;Database=$dbname", $username, $password);
echo 'We are succesful to connect the database !!'.'<br>'; // successful word
return $db;
} catch (PDOException $e){
echo "connection failed problem is >> ". $e -> getMessage()."\n";
exit;
}
}

Mysqli connection in function PHP

I'm facing a PHP problem. I've searched the web but couldn't find the answer. This is my code so far:
<?php
$db_host = 'db_host';
$db_user = 'db_user';
$db_password = 'db_password';
$db_name = 'db_name';
//not showing you the real db login ofcourse
$conn = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if($conn) {
echo 'We are connected!';
}
Up to here, everyting goes well. The connection is established and 'We are connected!' appears on the screen.
function login($username, $password, $conn) {
$result = $conn->query("SELECT * FROM users");
echo mysqli_errno($conn) . mysqli_error($conn);
}
When I run this function however, the mysqli error 'No database selected pops up. So I added the following piece of code the the file before and in the function, so the total code becomes:
<?php
$db_host = 'db_host';
$db_user = 'db_user';
$db_password = 'db_password';
$db_name = 'db_name';
//not showing you the real db login ofcourse
$conn = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if($conn) {
echo 'We are connected!';
}
if (!mysqli_select_db($conn, $db_name)) {
die("1st time failed");
}
function login($username, $password, $conn, $db_name) {
if (!mysqli_select_db($conn, $db_name)) {
die("2nd time failed");
}
$result = $conn->query("SELECT * FROM users");
echo mysqli_errno($conn) . mysqli_error($conn);
}
$username = 'test';
$password = 'test';
login($username, $password, $conn, $db_name);
?>
The first time adding the database name works fine, however, in the function it doesn't work. I've also tried using global $conn inside the function but that didn't work either. Changing mysqli_connect() to new mysqli() also doesn't have any effect.
Thanks in advance!
Please be aware, this code is refactored based on your code, and the login logic is NOT RECOMMENDED. Please try this code and make the changes that you think you need.
Make sure that your Database information is also updated as needed.
MyDB Class
Class MyDB {
protected $_DB_HOST = 'localhost';
protected $_DB_USER = 'user';
protected $_DB_PASS = 'password';
protected $_DB_NAME = 'table_name';
protected $_conn;
public function __construct() {
$this->_conn = mysqli_connect($this->_DB_HOST, $this->_DB_USER, $this->_DB_PASS);
if($this->_conn) {
echo 'We are connected!<br>';
}
}
public function connect() {
if(!mysqli_select_db($this->_conn, $this->_DB_NAME)) {
die("1st time failed<br>");
}
return $this->_conn;
}
}
Login Class
Class Login {
protected $_conn;
public function __construct() {
$db = new MyDB();
$this->_conn = $db->connect();
}
//This is a HORRIBLE way to check your login. Please change your logic here. I am just kind of re-using what you got
public function login($username, $password) {
$result = $this->_conn->query("SELECT * FROM user WHERE username ='$username' AND password='$password'");
if(!$result) {
echo mysqli_errno($this->_conn) . mysqli_error($this->_conn);
return false;
}
return $result->fetch_row() > 0;
}
}
Usage
$login = new Login();
$logged = $login->login('username', 'password');
if ($logged) {
echo "yeah!! you are IN";
} else {
echo "boo!! . Wrong username and password";
}

Prepared statement database connection must be instansiated first?

The parts in bold are what I am questioning. Inside the search_for_new_user function, if I change $conn->prepare to $this->db_connection()->prepare. I receive a lost connection error. However in the function right above it db_conn_test I can use this syntax. In both cases I am returning the $connection so I don't understand why there must be a difference in syntax.
class Database {
function db_connection() {
$server = "localhost";
$user = "user";
$password = "password";
$database = "database";
return $connection = new mysqli($server, $user, $password, $database);
}
function db_conn_test() {
if (**$this->db_connection()->connect_errno**) {
die($this->db_connection()->connect_errno . ": " . $this->db_connection()->connect_error);
} else {
echo "connected to mysql database";
}
}
function search_for_new_user($email) {
**$conn = $this->db_connection();**
if ($stmt = **$conn->prepare**("SELECT email FROM users where email = ?")) {
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
echo $result;
$stmt->close();
$conn->close();
}
}
}
In db_conn_test you call db_connection twice only if you got connection error during first db_connection call, so in this case connection to DB is not created.
But in search_for_new_user you create connection twice.
I.e.:
in db_conn_test:
// if connection not created, because you got error
if ($this->db_connection()->connect_errno) {
// therefore each time you call db_connection(),
// you again try create connection, and got same error
// and return it in die text
die($this->db_connection()->connect_errno . ": " . $this->db_connection()->connect_error);
} else {
echo "connected to mysql database";
}
but in search_for_new_user: you call db_connection() and create connection(if all is ok). And then if you call db_connection in second try, first connection is gone away and you got error.
Your class should looks like this:
class Database {
protected $connection;
function db_connection() {
if ($this->connection !== null) {
return $this->connection;
}
$server = "localhost";
$user = "user";
$password = "password";
$database = "database";
return $this->connection = new mysqli($server, $user, $password, $database);
}
}

PHP MySQL connection error

guys!I got a littile trouble.
There is connection.inc.php in "includes" folder:
<?php
function dbConnect($usertype, $connectionType = 'mysqli') {
$host = 'localhost';
$db = 'testdb';
if ($usertype == 'read') {
$user = 'readuser';
$pwd = 'testpass';
} elseif ($usertype == 'write') {
$user = 'writeuser';
$pwd = 'testpass';
} else {
exit('Unrecognized connection type');
}
if ($connectionType == 'mysqli') {
return new mysqli($host, $user, $pwd, $db) or die('Cannot open database');
} else {
try {
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch(PDOException $e) {
echo 'Cannot connect to database';
exit;
} // end of try block
} // end of $connectionType if
} // end of function
I use Linux for this test,and the lastest xampp 1.7.4
But things become worse when I use the following code:(I already have created my DB, and two users 'readuser' and 'writeuser')
<?php
// I use mysqli extension to connect my DB
require_once(includes/connection.inc.php);
// connect to DB
$conn = dbConnect('read');
// I need to get some picture infomations from images table
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error());
// find out how many records were retrieved
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>
And when I load it in my browser:
Fatal error:Call to a member function query() on a non-object in /opt/lampp/htdocs/mysqli.php on line 9
So I guess $conn is not a object now,but It works when I write this code:
<?php
$host = 'localhost';
$user = 'readuser';
$pass = 'testpass';
$db = 'testdb';
$sql = 'SELECT * FROM images';
$conn = new mysqli($host, $user, $pass, $db);
$result = $conn->query($sql) or die(mysqli_error());
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>
And it outputs:We have 8 pictures in DB
That's really a strange thing,I can't figure it out...Thanks guys!
Try saving the new mysqli() result as a variable, then return that variable instead. That logic makes no sense, I know, but I've had problems like that before.
$a = new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
return $a;

Categories