PHP not showing anything - php

I cannot see anything when on my xampp server and displays an empty page. I am trying to find the error but failed. anyone can help would be appreciated
here is class.db.php
<?php
class db {
private $conn;
private $host;
private $user;
private $password;
private $baseName;
private $port;
private $Debug;
function __construct($params=array()) {
$this->conn = false;
$this->host = 'localhost'; //hostname
$this->user = 'root'; //username
$this->password = ''; //password
$this->baseName = 'db'; //name of your database
$this->debug = true;
$this->connect();
}
function __destruct() {
$this->disconnect();
}
function connect() {
if (!$this->conn) {
try {
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->baseName.'', $this->user, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
if (!$this->conn) {
$this->status_fatal = true;
echo 'Connection BDD failed';
die();
}
else {
$this->status_fatal = false;
}
}
return $this->conn;
}
function disconnect() {
if ($this->conn) {
$this->conn = null;
}
}
function getOne($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetch();
return $reponse;
}
function getAll($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetchAll();
return $reponse;
}
function execute($query) {
if (!$response = $this->conn->exec($query)) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
return $response;
}
}
and index.php has at the top above <!doctype
<?PHP
include('db.class.php');
$bdd = new db();
?>
along my html code

You just created an instance of this class, this only triggered the constructor, you did not make any calls to functions, so nothing shows on that page.
For the future: enable displaying errors by adding
ini_set('display_errors',1);
this will help you to find and correct errors.

Related

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

How to insert data in multiple table with one query PDO mysql?

I need to insert data in mysql database with one query in PDO mysql.
I need the same thing what is here done with mysqli multi query.
This works fine
$insert ="
insert into comments (user_id,comment) values('$user_id','$comment');
insert into comments2 (user_id,comment) values('$user_id','$comment');
$run = mysqli_multi_query($con,$insert);
But how can I do this in PDO
connection.php :
<?php
class db {
private $conn;
private $host;
private $user;
private $password;
private $baseName;
private $port;
private $Debug;
function __construct($params=array()) {
$this->conn = false;
$this->host = 'localhost'; //hostname
$this->user = 'root'; //username
$this->password = ''; //password
$this->baseName = 'hotwall'; //name of your database
$this->port = '3306';
$this->debug = true;
$this->connect();
}
function __destruct() {
$this->disconnect();
}
function connect() {
if (!$this->conn) {
try {
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->baseName.'', $this->user, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
if (!$this->conn) {
$this->status_fatal = true;
echo 'Connection BDD failed';
die();
}
else {
$this->status_fatal = false;
}
}
return $this->conn;
}
function disconnect() {
if ($this->conn) {
$this->conn = null;
}
}
function getOne($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetch();
return $reponse;
}
function getAll($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetchAll();
return $reponse;
}
function execute($query) {
if (!$response = $this->conn->exec($query)) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
return $response;
}
}
what should I do here to insert in another table
$query = $bdd->execute('insert into comments (user_id,comment)
values('$user_id','$comment')');
Use 2 queries, not one. Of course it must be parameterized queries.
$stmt = $pdo->prepare("insert into comments (user_id,comment) values(?,?)");
$stmt->execute([$user_id,$comment]);
$stmt = $pdo->prepare("insert into comments2 (user_id,comment) values(?,?)");
$stmt->execute([$user_id,$comment]);
is all the code you need.

Empty query result in new file

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.

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

Login Function [PHP][PDO]

I've been having trouble trying to get my login function to work. Whenever I try to login it always gives me this Syntax error:
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\cereal_mod\includes\Cereal.php on line 53
I'm not sure if the Database connection is part of the problem but i'm not totally sure what's the big ideal of it not operating correctly.
Here is Database.php
<?php
namespace Cereal;
ini_set('error_reporting', E_ALL);
class Database Extends \PDO
{
public function __construct($dbHost,$dbName,$dbUser,$dbPass)
{
parent::__construct($dbHost,$dbName,$dbUser,$dbPass);
try
{
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
die($e->getMessage());
}
}
#get the number of rows in a result
public function num_rows($query)
{
# create a prepared statement
$stmt = parent::prepare($query);
if($stmt)
{
# execute query
$stmt->execute();
return $stmt->rowCount();
}
else
{
return self::get_error();
}
}
#display error
public function get_error()
{
$this->connection->errorInfo();
}
# closes the database connection when object is destroyed.
public function __destruct()
{
$this->connection = null;
}
}
?>
Here is the login.php
<?php
ini_set('error_reporting', E_ALL);
include "includes/Cereal.php";
$manager = new Cereal;
session_start();
if(isset($_POST['username'], $_POST['password'], $_POST['submit'])){
$login = $manager->login($_POST['username'], $_POST['password']);
}
?>
<form action="" method="POST">
<div id="login">
<input type="username" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</div>
and lastly Cereal.php
<?php
#namespace Cereal;
ini_set('error_reporting', E_ALL);
class Cereal {
private $configObj;
private $databaseObj;
public $playerData;
public function __construct(){
$this->loadConfig();
if($this->configObj){
try {
$dbHost = $this->configObj['Database']['Host'];
$dbName = $this->configObj['Database']['Database'];
$dbUser = $this->configObj['Database']['User'];
$dbPass = $this->configObj['Database']['Pass'];
$this->databaseObj = new Database('mysql:host=' . $dbHost . ';dbname=' . $dbName, $dbUser, $dbPass);
} catch(\PDOException $ex){
$this->__return($ex->getMessage, true);
}
}
}
private function loadConfig(){
$configPath = getcwd() . '/includes/config/Configuration.json';
$configData = file_get_contents($configPath);
$configObj = json_decode($configData, true);
if(!$configObj){
$this->configObj = $configObj;
} else {
}
}
public function __return($message, $die = false){
$successCheck = $die ? 'false' : 'true';
$messageArr = Array('success' => $successCheck, 'message' => $message);
echo json_encode($messageArr);
if($die) die();
}
public function login($username, $password){
try {
$login = $this->databaseObj->prepare("SELECT * FROM users WHERE username=:username AND password=:password");
$login->bindParam(':username', $username);
$login->bindParam(':password', md5($password));
$login->execute();
$row = $login->fetch(PDO::FETCH_ASSOC);
if($row) {
$_SESSION['auth'] = 1;
$_SESSION['username'] = $username;
die(json_encode(array("error"=>false, "message"=>"")));
} else {
die(json_encode(array("error"=>true, "message"=>"Incorrect credentials")));
}
} catch(PDOException $e) {
error_log('PDOException: ' . $e->getMessage());
die(json_encode(array("error"=>true, "message"=>"Database error, this has been logged.")));
}
}
}
?>
If someone could point out what i'm doing wrong I would really appreciate that because I haven't played with PDO in a while and i'm not sure if I am doing this correctly.
In Database.php you need to change
public function __construct($dbHost,$dbName,$dbUser,$dbPass)
{
parent::__construct($dbHost,$dbName,$dbUser,$dbPass);
}
to
public function __construct($dsn, $dbUser, $dbPass)
{
parent::__construct($dsn, $dbUser, $dbPass);
}
You also have to add use Cereal\Database; in top of Cereal.php
and use PDO; in top of Database.php
Try following:
if(!$configObj){
$this->configObj = $configObj;
} else {
}
should it not be if($configObj) ?

Categories