Empty query result in new file - php

I write script login php oop.
I created file Db.php method runQuery:
function runQuery($query) {
$this->last_query_result = $this->conn->query($query);
if (!$this->last_query_result) {
$this->setError("Nie udalo sie wykonac zapytania: " . $this->conn->error);
}
}
And in file login.php i created new method loginUser:
public function loginUser($login, $pass) {
$this->result = parent::runQuery("SELECT * FROM users WHERE name = '" . $login . "' AND pass='" . $pass . "'");
var_dump($this->result);
}
The problem is that the query returns NULL.
The entire file db.php
class DbUser {
private $conn;
private $host;
private $user;
private $pass;
private $base;
private $last_query_result;
function __construct($host, $user, $pass, $base) {
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->base = $base;
$this->connect();
}
public function setError($error) {
throw new Exception($error);
}
protected function connect() {
$this->conn = #new mysqli($this->host, $this->user, $this->pass, $this->base);
if ($this->conn->connect_errno) {
$this->setError("Nie udalo sie polaczyc z baza danych: " . $this->conn->connect_error);
}
}
function runQuery($query) {
$this->last_query_result = $this->conn->query($query);
if (!$this->last_query_result) {
$this->setError("Nie udalo sie wykonac zapytania: " . $this->conn->error);
}
}
function fullList() {
$return = array();
while (($row = mysqli_fetch_assoc($this->last_query_result)) !== NULL) {
$return[] = $row;
}
return $return;
}
}
And file login.php
//kalsa logowania uzytkownika
include 'db.php';
class login extends DbUser {
private $login;
private $pass;
private $result;
function __construct() {
parent::__construct('localhost', 'michal', 'saba9811', 'test');
}
public function loginUser($login, $pass) {
$this->result = parent::runQuery("SELECT * FROM users WHERE name = '" . $login . "' AND pass='" . $pass . "'");
var_dump($this->result);
}
}
try {
$login = $_POST['login'];
$pass = $_POST['pass'];
$log = new login();
$log->loginUser($login, $pass);
} catch (Exception $e) {
echo $e->getMessage();
}

Your runQuery()function doesn't return anything -
function runQuery($query) {
$this->last_query_result = $this->conn->query($query);
if (!$this->last_query_result) {
$this->setError("Nie udalo sie wykonac zapytania: " . $this->conn->error);
}
}
So when you try to assign the return value to another variable, it has nothing to assign:
$this->result = parent::runQuery("SELECT * FROM users WHERE name = '" . $login . "' AND pass='" . $pass . "'");
Fetch your query results from $this->last_query_result or refactor your code. Or just have runQuery() return $this->last_query_result, but that's a bit redundant.

Related

how to find email id is registered in db or not in php?

Here is my code:
<?php
class Db
{
private $servername = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'emp';
function __construct()
{
$this->db = new mysqli(
$this->servername,
$this->username,
$this->password,
$this->dbname
);
if ($this->db->connect_error) {
die("Connection failed: " . $this->db->connect_error);
}
}
public function insert_record($table, $fields)
{
$sql = "";
$sql .= "INSERT INTO " . $table;
$sql .= " (" . implode(",", array_keys($fields)) . ")values";
$sql .= " ('" . implode("','", array_values($fields)) . "')";
$query = mysqli_query($this->db, $sql);
if ($query) {
return true;
}
}
}
//making object of the class
$crudobj = new Db;
//insert code for adding data in to the db
if (isset($_POST['submit'])) {
$myArray = array(
"username" => $_POST["unm"],
"email" => $_POST["eid"],
"password" => $_POST["pass"]
);
//inserting data
if($crudobj->insert_record("users", $myArray))
{
header("location: login.pho")
}
}
?>
Call it with your input email.
if($crudobj->is_email_exists($_POST["eid"]))
{
echo "Email Already Exist";
}
Add below function in your DB class:
public function is_email_exists($email)
{
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
$email = mysqli_real_escape_string($this->db, $email);;
$sql = "SELECT email FROM users WHERE email='".$email."';";
if($result = mysqli_query($this->db, $sql))
{
return mysqli_num_rows($result);
}
}
return true;
}

PHP: Prepared Statements inside a OOP based project

I'm a little confused about Prepared Statements in PHP, I've been watching the following tutorial on youtube: https://www.youtube.com/watch?v=aN5KqxK1slc
After I've received the following note on my currently Mysqli source code:
You are wide open to SQL Injections and should really use Prepared
Statements instead of concatenating your queries. Specially since
you're not escaping the user inputs at all!
My question:
How would I prepare the statement since I'm creating the syntax for the statement inside my register class and only pass the statement to my database class to execute it using the execute_query function?
Would I just prepare the statement inside the execute_query function and check if its either a statement of the format INSERT or SELECT and then prepare the values?
I appreciate any kind of suggestions and feedback.
My current code looks like the following:
Register class:
<?php
class register extends database
{
function __construct($username, $password, $email)
{
$this->username = $username;
$this->password = password_hash($password, PASSWORD_DEFAULT);
$this->email = $email;
$this->activation_id = $this->generateActivationId();
$this->sender_email = 'support#url.com';
$this->activation_link = 'http://url.com/folder/activate.php?id=' . $this->activation_id;
$this->database = new database();
}
function generateActivationId()
{
$generator = bin2hex(random_bytes(10));
return $generator;
}
function registerAccount()
{
$this->database->connect();
$user_lookup = $this->database->execute_query("SELECT * FROM users WHERE username = '" . $this->username . "'");
if (mysqli_num_rows($user_lookup) > 0)
{
return false;
}
else
{
$this->database->execute_query("INSERT INTO users (username, password, email, activation_id) VALUES ('" . $this->username . "', '" . $this->password . "', '" . $this->email . "', '" . $this->activation_id . "')");
$user_lookup_comfirm = $this->database->execute_query("SELECT * FROM users WHERE username = '" . $this->username . "'");
if (mysqli_num_rows($user_lookup_comfirm) > 0)
{
$this->sendRegisterEmail();
return true;
}
else
{
return false;
}
}
}
function sendRegisterEmail()
{
$subject = 'Registration - Activate your account';
$message = 'Thank you for registering. Please activate your account by visiting the following site: Website link';
$headers = 'From: ' . $this->sender_email . "\r\n" .
'Reply-To: ' . $this->sender_email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($this->email, $subject, $message, $headers);
}
}
?>
Database class:
<?php
class database
{
function __construct()
{
$this->dBusername = 'xxx';
$this->dBpassword = 'xxx';
$this->dBhost = 'localhost';
$this->dBdatabase = 'xxx';
$this->dBcharset = 'utf8';
}
function connect()
{
$mysqli = new mysqli($this->dBhost, $this->dBusername, $this->dBpassword, $this->dBdatabase);
if ($mysqli->connect_errno)
{
$this->_mysqli = false;
}
else
{
$mysqli->set_charset($this->charset);
$this->_mysqli = $mysqli;
}
}
function execute_query($sql)
{
if($results = $this->_mysqli->query($sql))
{
return $results;
}
else
{
return false;
}
}
}
?>
<?php
class Config{
private function Db(){
$db = null;
$dsn = UR DSN;
$user = UR USER;
$pass = UR PASS;
try{
$db = $pdo = new PDO($dsn, $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_TIMEOUT => "10"));
return $db;
} catch(Exception $e){
var_dump($e);
}
return null;
}
function execPreparedStatement($sql , Array $param = null){
try{
$db = $this->Db();
if($db != null && ($db instanceof PDO)){
$db->beginTransaction();
$stm = $db->prepare($sql);
for ($i = 0 ; $i < count($param) ; $i++){
$stm->bindValue($i + 1,$param[$i]);
}
$dat = $stm->execute();
$db->commit();
$stm = null;
$db = null;
return $dat;
}
} catch (PDOException $e) {
$db->rollBack();
var_dump("<br><br>Error: ".$e->getMessage().' in '.$e->getFile().' on line '.$e->getLine(), $sql, $param);
}
}
function getPreparedStatement($sql , Array $param = null,$type = null) {
$db = $this->Db();
if($db != null && ($db instanceof PDO)) {
$stm = $db->prepare($sql);
if(!empty($param)){
for ($i = 0 ; $i < count($param) ; $i++){
$stm->bindParam($i+1, $param[$i]);
}
}
try {
$stm->execute();
if($type) {
$dat = #$stm->fetchAll(PDO::FETCH_ASSOC);
} else {
$dat = #$stm->fetchAll();
}
$stm = null;
$db = null;
return $dat;
} catch (Exception $e){
var_dump("<br><br>Error capturado: ".$e->getMessage().' in '.$e->getFile().' on line '.$e->getLine(),$sql,$param);
}
}
}
}
this is a PDO class u can use it as this
<?php
$db = new Config();
// This is for an update
$db->execPreparedStatement('update table set a = ?, b = ? where id = ?)', array(value1, value2, id));
// Select With out filter
$data = $db->getPreparedStatment('select * from table');
// With Filter.
$data = $db->getPreparedStatment('select * from table where id = ?', array(id));
this is just and example i can give u more feed back if u need. but i think with this u can do it on ur own

PHP - Call to a member function query() on null - Error [duplicate]

This question already has answers here:
Fatal error: Call to a member function query() on null
(2 answers)
Closed 5 years ago.
I have the following code in php for connecting to my database:
<?php
class MY_SQL{
private $username;
private $password;
private $conn;
public function __construct($SERVERNAME){
$this->username = "username";
$this->password = "password";
if($SERVERNAME == "data_"){
$server = "Servername";
}
else {
$server = $SERVERNAME;
}
// Create connection
$conn = new mysqli($server, $this->username, $this->password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
public function SQLCommand($cmd) {
if ( $this->conn->query($cmd) === TRUE ) {
echo "New record created successfully";
} else {
echo "Error: " . $cmd . "<br>" . $conn->error;
}
}
}
$sql = "INSERT INTO _test(test1, test2) VALUES ('hello','hi');";
$database = new MY_SQL("Servername");
$database->SQLCommand($sql);
?>
I get the following error:
Fatal error: Call to a member function query() on null
What is going wrong?
$this->conn = $conn; in __construct()
I would suggest you to improve your class with this example (taken from https://github.com/opencart/opencart/blob/master/upload/system/library/db/mysqli.php)
final class My_SQLi
{
private $connection;
public function __construct($hostname, $username, $password, $database, $port = '3306')
{
$this->connection = new \mysqli($hostname, $username, $password, $database, $port);
if ($this->connection->connect_error) {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno);
}
$this->connection->set_charset("utf8");
$this->connection->query("SET SQL_MODE = ''");
}
public function query($sql)
{
$query = $this->connection->query($sql);
if (!$this->connection->errno) {
if ($query instanceof \mysqli_result) {
$data = array();
while ($row = $query->fetch_assoc()) {
$data[] = $row;
}
$result = new \stdClass();
$result->num_rows = $query->num_rows;
$result->row = isset($data[0]) ? $data[0] : array();
$result->rows = $data;
$query->close();
return $result;
} else {
return true;
}
} else {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno . '<br />' . $sql);
}
}
public function escape($value)
{
return $this->connection->real_escape_string($value);
}
public function countAffected()
{
return $this->connection->affected_rows;
}
public function getLastId()
{
return $this->connection->insert_id;
}
public function isConnected()
{
return $this->connection->ping();
}
public function __destruct()
{
$this->connection->close();
}
}
$sql = "INSERT INTO _test(test1, test2) VALUES ('hello','hi');";
$mysql = new My_SQLi('host', 'user', 'password', 'db');
$result = $mysql->query($sql);

Php class inside connection close or class close?

i have php class USER and Database class im doing 10000 users app, and that user will be query 3-4 times a day minumum . my class base and function base here them looking yet for thats have any problem ? or need any fix ?
MY db class
class Database
{
private $host = "";
private $db_name = "";
private $username = "";
private $password = "";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
print'{"success": "0","message": "Service Error, Please try again later "}';
}
return $this->conn;
}
}
Also my USER class here
<?php
require_once('dbconfig.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID)
{
try
{
$stmt2 = $this->conn->prepare("UPDATE Products SET productCode='$code',productName='$name',productDescription='$description',specialWarning='$specialwarning',productQuantity='$quantity',productPrice='$price' WHERE ID=$productID");
$stmt2->execute();
echo'{"success": "1", "message": "Product Updated"}';
return true;
}
catch(PDOException $e)
{
}
$this->conn = null; // HERE I DID NULL FOR DISABLE MAX CONNECTIONS
}
}
AND HER MY updateproduct.php
<?php
header('Content-type: application/json');
$name = $_REQUEST['name'];
$code = $_REQUEST['code'];
$description = $_REQUEST['description'];
$quantity = $_REQUEST['quantity'];
$price = $_REQUEST['price'];
$specialwarning = $_REQUEST['specialwarning'];
$productID = $_REQUEST['productID'];
include_once 'class.user.php';
$user = new USER($DB_con);
if($user->updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID))
{
}
else
{
}
?>
Can you check my codes is good class for big users ? and good connection returns ? Can i add something ? or need any fix ?Also need to close class ?
Thanks

Cannot echo database items

I am trying to echo out some database items in php but nothing seems to be coming out. The initialize php that is required calls out the database.php that stores all the configurations as show below.What am I doing wrong?
SQL statement:
<?php
require_once("includes/initialize.php");
$userName = $_POST["name"];
$userEmail = $_POST["email"];
$sqlName = "SELECT name FROM individual";
$sqlEmail = "SELECT email FROM individual";
if ($sqlEmail == $userEmail || $sqlName == $userName){
$message = "Hi " + $userName + "this is your new password.";
echo $message;
}
?>
The database configurations are in another php file called database.php.
database.php:
<?php
require_once ("config.php");
class MySQLDatabase {
private $connection;
function __construct() {
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME) or die
("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
$db_select = mysqli_select_db($this->connection, DB_NAME);
}
public function close_connection() {
if (isset($this->connection)) {
mysqli_close($this->connnection);
unset($this->connection);
}
}
public function query($sql) {
$result = mysqli_query($this->connection, $sql);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result) {
if (!$result) {
die("Database query failed.");
}
}
public function escape_value($string) {
$escaped_string = mysqli_real_escape_string($this->connection, $string);
return $escaped_string;
}
public function fetch_array($id){
if (mysqli_fetch_array($id)) {
return true;
}
}
}
$database = new MySQLDatabase();
$db = & $database;
?>
Your not running your query.. ..or getting its results..
$sqlEmail = "SELECT email FROM individual";
$query = $db->query($sqlEmail);
$user = $db->fetch_array($query);
var_dumpr($user);
Hope this helps..

Categories