How to make a reusable SELECT method in OOP php [duplicate] - php

This question already has answers here:
How can I fix MySQL error #1064?
(3 answers)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 2 years ago.
im new here and im also pretty new to php and OOP so if i dont ask the right question also tell me ;p
im trying to make a class that handles all the queries from and to the database. I want to make this class as reusable as plossible so i dont have to keep writing selects and insert statements in all my methods and functions.
my question is: is it plossible to call on an method with parameters and then have those parameters finish the query for me ?
this is what i had come up with so far:
Database connection class:
class Database {
private $host;
private $user;
private $pass;
private $dbname;
private $charset;
public function connect() {
$this->host = 'localhost:3306';
$this->user = 'root';
$this->pass = '';
$this->dbname = 'Testdb';
$this->charset = 'utf8mb4';
try {
$dsn = 'mysql:host='.$this->host.';dbname='.$this->dbname.';charset='.$this->charset;
$pdo = new PDO($dsn, $this->user, $this->pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
echo "Connection failed:".$e->getMessage();
}
}
}
this is my query's class:
class QueryDatabase extends Database {
public function getData($tablename, $selector, $value) {
if (!isset($selector)){
echo 'Something went wrong!';
} else if ($selector == ''){
$stmt = $this->connect()->query("SELECT * FROM $tablename");
while ($row = $stmt->fetch()){
return $row;
}
}else {
$stmt = $this->connect()->query("SELECT * FROM $tablename where $selector = $value");
while ($row = $stmt->fetch()){
return $row;
}
}
}
public function setData($tablename, $colums, $data) {
if (!isset($tablename) or !isset($data)) {
echo 'Something went wrong!';
} else {
$sql = "INSERT INTO $tablename ($colums) VALUES ($data)";
$q = $this->connect()->prepare($sql);
$q->execute();
}
}
protected function addData() {
}
protected function delData() {
}
}
and this is what i mean with the parameters for example:
$test = new QueryDatabase;
$test->setData('contact_form_messages', 'u_id, name, email, subject, message, date', ' , Kees, Kees#gmail.com, Test, Hopefully it works, ');
i get this error message :
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' Kees, Kees#gmail.com, Test, Hopelijk werkt hij, )' at line 1 in D:\webProjects\project\classes\querydatabase.class.php:31
Stack trace: #0 D:\webProjects\project\classes\querydatabase.class.php(31): PDOStatement->execute() #1 D:\webProjects\project\includes\header.inc.php(5):
QueryDatabase->setData('contact_form_me...', 'u_id, name, ema...', ' , Kees, Kees#g...') #2 D:\webProjects\project\contact.php(1): include('D:\\webProjects\\...') #3 {main} thrown in D:\webProjects\project\classes\querydatabase.class.php on line 31
if you have any suggestions i'd be happy to hear them!
thanks a lot!
Floris

Related

PHP: Fatal error: Uncaught PDOException: SQLSTATE[HY000]

I have a class named player that creates, deletes and controls if a player entity exists. In another file, I have the database connection with PDO and, finally, in third file I have the call to player class. Here's all the code:
file: player.php
<?php
class player
{
private $pdo;
private $network_id;
public $color;
public function __construct($pdo, $network_id, $color)
{
$this->pdo = $pdo;
$this->network_id = $network_id;
$this->color = $color;
}
public function create_player()
{
if(!$this->exists_player())
{
$sql = 'INSERT INTO players SET network_id = :network_id';
$query = $this->pdo->prepare($sql);
$query->execute(array(':network_id' => $this->network_id));
}
else
{
echo 'error';
}
}
public function delete_player()
{
if($this->exists_player())
{
$sql = 'DELETE FROM players WHERE network_id = :network_id';
$query = $this->pdo->prepare($sql);
$query->execute(array(':network_id' => $this->network_id));
}
else
{
return -1;
}
}
private function exists_player()
{
$sql = 'SELECT COUNT(*) FROM players WHERE network_id = '.$this->network_id;
$result = $this->pdo->exec($sql);
if($result > 0) return true;
else return false;
}
}
?>
file: test.php
<?php
include './Php/db_connection.php';
include './Php/player.php';
$player = new player($pdo, 1112, 'red');
$player->create_player();
?>
file: db_connection.php
$pdo = new PDO('mysql:host=localhost; dbname=myDbName', 'dbUtent', 'myPassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The thing is that when I call test.php, I get this error:
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. in F:\Software\Coding_Development_Software\Server\wamp\www\myProject\Ajax\Cube\Php\player.php on line 21
All code is an exemple.
Any ideas?
The thing here is that you need to fetch until it fails for a row fetch attempt. In fact, your own exception is telling you the solution:
Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. in F:\Software\Coding_Development_Software\Server\wamp\www\myProject\Ajax\Cube\Php\player.php on line 21

Fatal error: Uncaught Error: Call to a member function prepare() on null [C:\xampp\htdocs\twitter\core\classes\user.php on line 19] [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 27 days ago.
On logging in, This error pops up.
Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\twitter\core\classes\user.php:19 Stack trace: #0 C:\xampp\htdocs\twitter\includes\login.php(17): User->login('user#email.com', 'passwordofuser') #1 C:\xampp\htdocs\twitter\index.php(59): include('C:\xampp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\twitter\core\classes\user.php on line 19
I'm a beginner in PHP and was trying to validate the "entered" email and password by connecting it to SQL DATABASE. I wanted to display an "error" message if the email or password is not available in database.
This is user.php.
The error is at line 19.
$stmt = $this->pdo->prepare("SELECT `user_id` FROM `users` WHERE `email` = :email AND `password` = :password");
user.php
<?php
class User
{
protected $pdo;
function _construct($pdo)
{
$this->pdo = $pdo;
}
public function checkInput($var)
{
$var = htmlspecialchars($var);
$var = trim($var);
$var = stripcslashes($var);
return $var;
}
public function login($email, $password)
{
$stmt = $this->pdo->prepare("SELECT `user_id` FROM `users` WHERE `email` = :email AND `password` = :password");
$stmt->bindParam(":email", $email, PDO::PARAM_STR);
$stmt->bindParam(":password",md5($password), PDO::PARAM_STR);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_OBJ);
$count = $stmt->rowCount();
if($count > 0)
{
$_SESSION['user_id'] = $user->user_id;
header('Location: home.php');
}
else
{
return false;
}
}
}
?>
Now, here is my connection.php
<?php
$dsn = 'mysql:host=localhost; dbname=tweety';
$user = 'root';
$pass = '';
try
{
$pdo = new PDO($dsn, $user, $pass);
}
catch(PDOException $e)
{
echo 'Connnection error! ' . $e->getMessage();
}
?>
Here is login.php
I know that this question is asked previously but i can't help myself find a solution.Any help would be appreciated.
WHAT I TRIED:
Tried checking for typo error in connection.php
Tried restarting my SQL server from XAMPP.
Tried referring other "stackoverflow" questions.
In user.php
Rename _construct to __construct. Now the constructor isn't executed, so the pdo variable will remain empty.
add below lines to catch your exact error in your connection.php
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
this will show your details error exception if any available.
I guess that the variable $getFromU is an instance of the User class. But you have not yet instantiated it before using it.

I can't resolve this error Call to a member function quote() on null

I'm programming a website on localhost and I found this error when I try to login to submit a new user
Fatal error: Uncaught Error: Call to a member function quote() on null
in C:\xampp\htdocs\recipes\db_manager\users.php:31 Stack trace: #0
C:\xampp\htdocs\recipes\users_manager\checkSubmit.php(15):
notExistsUser('usertest') #1 {main} thrown in
C:\xampp\htdocs\recipes\db_manager\users.php on line 31
checkSubmit.php:
<?php
session_start();
include_once("../db_manager/common.php");
if(isset($_POST["username"]) && isset($_POST["pwd"])) {
$username = $_POST["username"];
$pwd = $_POST["pwd"];
if(notExistsUser($username)){
submit($username, $pwd);
redirect("../index.php", "User successfully submitted!");
} else {
redirect("../submit.php", "This username already exists");
}
}
?>
funcion notExistsUser in users.php
function notExistsUser($username) {
$db = attachdb();
$user = $db->quote($username); //Line 31
$rows = $db->query("SELECT * FROM Users WHERE username = $user");
if($rows->rowCount() > 0)
return false;
else
return true;
}
function attachdb()
function attachdb() {
$add = 'mysql:dbname=Recipes;host=localhost';
try {
$db = new PDO($add, 'root', 'mysql');
return $db;
} catch (PDOException $ex) {
?>
<p>A database error occurred!.</p>
<?php
return NULL;
}
}
What this error means and how can I fix it?
Your database connection must be wrong. Are you sure your password for root is mysql?
attachdb() will return NULL on connection problems.
// at this point $db IS NULL and not the desired PDO Instance
$user = $db->quote($username); //Line 31
To fix this: You have to make sure the db connection is working and then there is no error.

More detailed exceptions

I've nearly finished converting my old sql website to pdo to move to php7 and use prepared statements but im having trouble with a handful of errors.
The exceptions are not as clear as i would like, most errors point to my database class eg
Uncaught Exception: 2020-01-18 20:23:35 - SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'username' AND UNIX_TIMESTAMP('2020-01-18 20:23:35')-UNIX_TIMESTAMP(date) < 30' at line 1 in file /home/test/public_html/backend/dbclass.php on line 39
Uncaught Exception: 2020-01-18 20:23:43 - SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '86.28.135.16'', donated=0, forumbanned='no', warned='no', modcomment='', enabled' at line 1 in file /home/test/public_html/backend/dbclass.php on line 39
I am using a blunt singleton class this was the easiest way (i known this is not the best) and i had 1000 queries so a global static suited me to make it quicker. I would prefer not to wrap every query in try/catch to identify exceptions. Is they any function that might help like backtrace or gettrace im a novice so maybe theres a better way any help would be very appreciated
dbclass.php
<?php
define('DB_HOST', 'host');
define('DB_NAME', 'db');
define('DB_USER', 'user');
define('DB_PASS', 'pass');
define('DB_CHAR', 'utf8');
class DB
{
protected static $instance = null;
protected function __construct() {}
protected function __clone() {}
public static function instance()
{
if (self::$instance === null)
{
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => FALSE,
);
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHAR;
self::$instance = new PDO($dsn, DB_USER, DB_PASS, $opt);
}
return self::$instance;
}
public static function __callStatic($method, $args)
{
return call_user_func_array(array(self::instance(), $method), $args);
}
public static function run($sql, $args = [])
{
if (!$args)
{
return self::instance()->query($sql);
}
$stmt = self::instance()->prepare($sql);
$stmt->execute($args);
return $stmt;
}
}
exception_handler
function handleUncaughtException($e){
// Show general page to public
header("Location: exceptionerror.php");
// Construct the error string
$error = "Uncaught Exception: " . $message = date("Y-m-d H:i:s - ");
$error .= $e->getMessage() . " in file " . $e->getFile() . " on line " . $e->getLine() . "\n";
// Log details of error in a file
error_log($error, 3, "error_log.txt");
}
// Register custom exception handler
set_exception_handler("handleUncaughtException");
example of query
$stmt = DB::run("SELECT word FROM censor ORDER BY word");
while ($row = $stmt->fetch())

Fatal error: Uncaught Error: Call to a member function query() on null login.php:38 [duplicate]

This question already has answers here:
Fatal error: Call to a member function query() on null
(2 answers)
Closed 5 years ago.
I'm using webstera cpanel for host my web application and here is my code and i'm using session for log in
Fatal error: Uncaught Error: Call to a member function query() on null
in /home/buddhika/public_html/login.php:38 Stack trace: #0 {main}
thrown in /home/buddhika/public_html/login.php on line 38
<?php
#ob_start();
session_start();
?>
<html>
<head>
<?php
include_once('php/db-connect.php');
$error = "";
$msg = "";
if (isset($_SESSION["isLoggedIn"])) {
header("Location: index.php");
}
global $sql;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$sql = "SELECT fname, password FROM login";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
if (($_POST["username"] == $row["fname"]) && (($_POST["pass"]) == $row["password"])) {
header("Location: index.php");
$_SESSION["isLoggedIn"] = true;
$_SESSION["username"] = $row["fname"];
$_SESSION["image"] = $row["adimage"];
//alert();
$msg = "login success.";
} else {
$error = "Enter a valid username/password !!!";
}
}
}
}
db connection class
<?php
class Db {
// The database connection
protected static $connection;
/**
* Connect to the database
*
* #return bool false on failure / mysqli MySQLi object instance on success
*/
public function connect() {
// Try and connect to the database
if(!isset(self::$connection)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('./config.ini');
self::$connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if(self::$connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return false;
}
return self::$connection;
}
public function query($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query);
return $result;
}
"non-object" means that the variable ($conn) doesn't refer to an object. Did you assign it to your database class (e.g., $conn = new databaseClass();, or whatever the class you're using is named)?

Categories