PHP Code not selecting from database - php

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?

Related

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;
}

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

php oop database query

I am self learning php and trying oop, I am struggling with following problem, Would anyone could help me how can I use following database connection in to another class function. In php.net it is defined as $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db'); but when I use this within a class it dose not work. Thanks
class dbconnect{
private $host;
private $user;
private $pass;
private $dabase;
function doConnect()
{
$this->host = 'localhost';
$this->user = 'root';
$this->pass = 'abc#123';
$this->dabase = 'database_5';
$db = new mysqli($this->host, $this->user, $this->pass, $this->dabase);
if (mysqli_connect_errno())
{
echo "<br /><hr />";
echo "<p style='align:center;'>Error : could not connect to database.. </p>";
echo "<hr />";
exit;
}
}
$mysql = new dbconnect();
function doQuery($mysql){
$queryUser = $mysql->query("SELECT * FROM b_admin_user WHERE username_d = 'admin'");
echo $queryUser_row = $queryUser->num_rows;
}
doQuery($mysql);
Try this
<?php
class MySQL {
//objekto kintamieji
private $host;
private $username;
private $password;
private $database;
private $conn; // connection
public function __construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
// jungiuosi prie db
$this->conn = mysql_connect($this->host, $this->username, $this->password)
or die("Couldn't connect");
}
public function database($set_database)
{
$this->database=$set_database;
//pasirenku lentele
mysql_select_db($this->database, $this->conn) or die("cannot select Database");
}
}
// jungiames
$connect = new MySQL('localhost','root','');
$connect->database('job');
?>

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.

PDO query doesn't work

I can't do a query.
This is my code, where I connect to database and try to query.
EDIT :
class DatabaseConnection {
private $host;
private $port;
private $dbname;
private $username;
private $password;
private $query;
function __construct($host, $port, $dbname, $username, $password) {
$this->host = $host;
$this->port = $port;
$this->dbname = $dbname;
$this->username = $username;
$this->password = $password;
try {
$conn = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
echo "PDO connection object created";
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
function setQuery($query) {
$this->query = $query;
$sth = $db->prepare($this->query);
$sth->execute();
$result = $sth->fetchAll();
var_dump($result);
}
}
$db = new DatabaseConnection('144.76.6.45','5432','eu','eu','eu123');
$db->setQuery('SELECT * FROM user');
This is my code, I don't have any errors, but still it doesn't work.....
Depending on the type of query you will want to fetch data after executing it. Take a look at fetch() and fetchAll() methods.
$sth = $db->prepare($this->query);
$sth->execute();
$result = $sth->fetchAll();
var_dump($result);
or use a loop and fetch row by row
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
var_dump($row);
}
after your edit:
Try to replace:
$conn = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
with
$this->db = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
and then call prepare method on it: $sth = $this->db->prepare($this->query); instead of $sth = $db->prepare($this->query);

Categories