Php class inside connection close or class close? - php

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

Related

PHP Code not selecting from database

UPDATE: There was no issue with the code used in counting. There was just a typo error in connecting to database
$this->conn = new PDO("mysql:host=". $this->host . ";db_name=" . $this->db_name, $this->username, $this->password);
the db_name should be dbname. So its something like
$this->conn = new PDO("mysql:host=". $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
I am try a PHP REST api with mysql database but this doesn't seem to be working as i have tried to select from my database as the first step but this returns no result despite there being a record in the database
Below are my codes
database.php
<?php
class Database
{
//Database Credentials
private $host = "localhost";
private $username = "root";
private $password = "password";
private $db_name = "rtmdb";
public $conn;
//Get Database Connection
public function getConnection()
{
$this->conn = null;
//Try connection
try
{
$this->conn = new PDO("mysql:host=". $this->host . ";db_name=" . $this->db_name, $this->username, $this->password);
$this->conn->exec("set names utf8");
}
catch(PDOException $exception)
{
echo "Connection error:" . $exception->getMessage();
}
return $this->conn;
}
}
admin.php to select from database
<?php
class Admin
{
//Database Connection and Table name
private $conn;
private $table_name = "admin";
//object properties
public $id;
public $fname;
public $lname;
public $oname;
public $uname;
public $email;
public $idnumber;
public $password;
public $profimage;
public $datecreated;
public $modifiedby;
public $datemodified;
public $status;
//Construct $db as database connection
public function __construct($db)
{
$this->conn = $db;
}
public function crawl()
{
$query = "SELECT * FROM " . $this->table_name;
$stmt = $this->conn->prepare($query);
$stmt->execute();
return $stmt;
}
}
crawl.php file to get data and json_encode results
//Include database and object files
include_once "../config/database.php";
include_once "../objects/admin.php";
$database = new Database();
$db = $database->getConnection();
$admin = new Admin($db);
//Query Admin
$stmt = $admin->crawl();
$num = $stmt->rowCount();
echo json_encode($num);
if($num > 0)
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$admin_list = array(
"id" => $id,
"uname" => $uname
);
array_push($admin_arr['records'], $admin_list);
}
echo json_encode($admin_arr);
}
else
{
echo json_encode(
array("message" => "No registered admin found.")
);
}
But i get rowCount() as 0 and "no registered admin" despite having records
Below are screenshots of my table structures
the database structure
I also have only one data in the database
But these seem to give me no result. Please what the issue and how do i fix?

Object couldn't be converted to string

I'm getting this error message when trying to make a PDO connection:
Object of class dbConnection could not be converted to string in (line)
This is my code:
class dbConnection
{
protected $db_conn;
public $db_name = "todo";
public $db_user = "root";
public $db_pass = "";
public $db_host = "localhost";
function connect()
{
try {
$this->db_conn = new PDO("mysql:host=$this->$db_host;$this->db_name", $this->db_user, $this->db_pass);
return $this->db_conn;
}
catch (PDOException $e) {
return $e->getMessage();
}
}
}
The error is on the PDO line. Just in case, I insert the code where I access to the connect() method:
class ManageUsers
{
public $link;
function __construct()
{
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $link;
}
function registerUsers($username, $password, $ip, $time, $date)
{
$query = $this->link->prepare("INSERT INTO users (Username, Password, ip, time1, date1) VALUES (?,?,?,?,?)");
$values = array($username, $password, $ip, $time, $date);
$query->execute($values);
$counts = $query->rowCount();
return $counts;
}
}
$users = new ManageUsers();
echo $users->registerUsers('bob', 'bob', '127.0.0.1', '16:55', '01/01/2015');
Change your connection setting to the following:
class dbConnection
{
protected $db_conn;
public $db_name = "todo";
public $db_user = "root";
public $db_pass = "";
public $db_host = "localhost";
function connect()
{
try {
$this->db_conn = new PDO("mysql:host={$this->db_host};{$this->db_name}", $this->db_user, $this->db_pass); //note that $this->$db_host was wrong
return $this->db_conn;
}
catch (PDOException $e) {
//handle exception here or throw $e and let PHP handle it
}
}
}
In addition, returning values in a constructor has no side-effects (and should be prosecuted by law).
Please follow below code , its tested on my server and running fine .
class Config
{
var $host = '';
var $user = '';
var $password = '';
var $database = '';
function Config()
{
$this->host = "localhost";
$this->user = "root";
$this->password = "";
$this->database = "test";
}
}
function Database()
{
$config = new Config();
$this->host = $config->host;
$this->user = $config->user;
$this->password = $config->password;
$this->database = $config->database;
}
function open()
{
//Connect to the MySQL server
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->database, $this->user,$this->password);
if (!$this->conn)
{
header("Location: error.html");
exit;
}
return true;
}

Call to a member function query() on null with PDO

I just checked all of the answers are available on stackoverflow,they are similar but not my answer exactly. So please don't take this post as duplicate.
these are my codes when I'm executing it say's
Fatal error: Call to a member function query() on null in
C:\wamp64\www\ourCMS\index.php on line 12
Here is my snippet :
<?php
class DB
{
private $dbHost;
private $dbName;
private $dbUser;
private $dbPass;
protected $con;
function set_db($host, $db, $user, $pass)
{
$this->dbHost = $host;
$this->dbName = $db;
$this->dbUser = $user;
$this->dbPass = $pass;
}
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
}
}
// here is the place where i'm trying to use this actually
if (isset($_POST['submit']))
{
include('include/database.php');
$database = new DB;
$database->set_db("localhost", "ourcms", "root", "");
$conn = $database->connect();
$name = $_POST['nm'];
$query = "INSERT INTO testingpdo (name) VALUES ('$name')";
$data = $conn->query($query);
$result = $data->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
You don't return nothing from DB::connect ($conn = $database->connect();). Add return $this->con; at the end of the function.
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
return $this->con;
}

PDO query returning empty

I have a Connection class file which allows my other class "Functions" to connect to my MySQL database. However, when I execute a MySQL query, it returns with just Array (). The data I'm selecting is, in fact, there (I checked). What could the problem be?
Connection.php
<?php
class Connection extends PDO {
private $username;
private $password;
private $database;
private $hostname;
public function __construct($hostname, $username, $password, $database) {
$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;
$this->hostname = $hostname;
try {
parent::__construct("mysql:host=" . $this->hostname . ";dbname=" . $this->database, $this->username, $this->password);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
}
?>
Functions.php
<?php
require_once "Connection.php";
class Functions {
private $connection;
public function __construct() {
$this->connection = new Connection("127.0.0.1", "xxx", "xxx", "xxx");
}
public function sqlFetchAssoc($query) {
$sth = $this->connection->prepare($query);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
$functions = new Functions();
$row = $functions->sqlFetchAssoc("SELECT * FROM chatlogs WHERE id = 70");
print_r($row);
?>
I just spotted your bug in Connection.php:
$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;
$this->hostname = $hostname;
$this->hostname is repeated while $this->database is not set. However, you can strip altogether setting the $this->something, since you are using those values in the same function. This will make it simpler:
try {
parent::__construct("mysql:host=" . $hostname . ";dbname=" . $database, $username, $password);
}
I'd recommend going a step further. You should test each class separately. You can write this script and debug it (if needed) in testfunction.php:
<?php
class Functions {
private $connection;
public function __construct() {
$this->connection = new PDO("mysql:host=127.0.0.1;dbname=xxx", "xxx", "xxx");
}
public function sqlFetchAssoc($query) {
$sth = $this->connection->prepare($query);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
echo "Test started <br><br>";
echo "Initialization: <br>";
$functions = new Functions();
echo "Correct<br><br>";
echo "Performing a select: <br>";
$row = $functions->sqlFetchAssoc("SELECT * FROM chatlogs WHERE id = 70");
print_r($row);
echo "Test finished.";
?>
Then do something similar for the first class. Then not only it will be easier to spot the bug, but should a bug happen, you can come to these tests to see what went wrong instead of writing them all again. Remember not to include them in production code.

Mysqli oop method call

I'm really new to implementing OOP using mysqli things, I have this Object(Class) named Database, my real problem is how would I call my select method in my index.php and how can I use it
Database Class.php is below:
Class Database{
private $host = null;
private $user = null;
private $pass = null;
private $db = null;
public $error = "Error Po Sir!";
public $con;
public function connect($host, $user, $pass, $db){
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->db = $db;
$this->con = mysqli_connect($this->host, $this->user, $this->pass);
if(mysqli_connect_errno()){
echo "Connection Failed %s\n!", mysqli_connect_error();
exit();
}
}
public function select($condition){
$query = "select os_user from users WHERE os_user = {$condition}";
$result = mysqli_query($this->con,$query);
return $result;
}
}
this is how did I implement it:
require 'templates/dbclass.php';
$db = new Database();
$db->connect("localhost", "root", "", "os_db");
$username = $_POST['username'];
if($result = $db->select($username)){
echo $username;
if($result->num_rows > 0){
while($row = $result->fetch_object()){
echo $row->os_id;
}
}
}
But it does not show any results. When I var_dump($result) I get bool(false).
I've enabled error reporting, but there is no errors displayed.
There are 3 issues with your select function
is is vulnerable to SQL injection
it does no error checking
it is useless
Here is how it have to be
public function query($sql, $bind)
{
$db = $this->con;
$stm = $db->prepare($sql) or trigger_error($db->error." [$sql]");
$types = str_repeat("s", count($values));
array_unshift($bind, $types);
call_user_func_array(array($stm, 'bind_param'), $bind);
$stm->execute() or trigger_error($db->error." [$sql]");
$stm->store_result();
return $stm->get_result();
}
used like this
$sql = "select os_user from users WHERE os_user = ?";
$res = $db->select($sql, $_POST['username']));
while($row = $result->fetch_object()){
echo $row->os_id;
}

Categories