Cannot echo database items - php

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..

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

undefined Index Conn . I am Accessing object from one file to another file

<?php
require_once("../include/connClass.php");
// $conn = new mysqli("localhost", "root", "", "hrms");
$db = new dbObj();
// var_dump($db);
$connString = $db->getConnstring();
// var_dump($connString);
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$objDesignationMaster = new DesignationMaster($connString);
switch($action) {
case 'add':
$objDesignationMaster->insertDesignationMaster($params);
break;
case 'edit':
$objDesignationMaster->updateDesignationMaster($params);
break;
case 'delete':
$objDesignationMaster->deleteDesignationMaster($params);
break;
default:
$objDesignationMaster->getDesignationMaster($params);
return;
}
class DesignationMaster {
protected $conn;
protected $data = array();
function __construct($connString) {
$this->conn = $connString;
}
// public function getDesignationMaster($params) {
// $this->data = $this->getRecords($params);
// echo json_encode($this->data);
// }
function insertDesignationMaster($params){
$data = array();
$sql = "INSERT INTO department_master (dm_department)
VALUES(
'" . $params["txtDepartment"] . "'); ";
// echo $sql;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
function getDesignationMaster($params){
}
function deleteDesignationMaster($params){
}
function updateDesignationMaster($params){
}
}
?>
I am Getting Error on this code I am Including Connection File From another file any idea about this. the object is created successfully connection object is not.
And here is my connection class
<?php
Class dbObj{
var $servername = "localhost";
var $username = "root";
var $password = "";
var $db = "hrms";
var $conn;
Public function getConnstring() {
// Create connection
$con = new mysqli($this->servername, $this->username, $this->password,
$this->db);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
} else {
$this->conn = $con;
}
return $this->conn;
}
}
?>
Use
if($this->conn->query($sql) === TRUE){ //$conn is not defined
}
$this->conn contains the connection itself. You defined it in the construct function

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 connect to database using mvc in php [duplicate]

This question already has an answer here:
PHP simple DB connection class for MVC
(1 answer)
Closed 1 year ago.
dbconnect.php
class dbconnect
{
public function connect()
{
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host, $user, $pass, $db);
return $connection;
}
}
dao.php
include 'dbconnect.php';
class dao extends dbconnect
{
private $conn;
function __construct()
{
$dbcon = new dbconnect();
$conn = $dbcon->connect();
}
function select($table, $where = '', $other = '')
{
if (!$where = '') {
$where = 'where' . $where;
}
$sele = mysqli_query($this->conn, "SELECT * FROM $table $where $other") or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
controller.php
include 'dao.php';
$d = new dao();
if (isset($_POST['btn_login'])) {
extract($_POST);
$username = $_POST['user_name'];
$pswd = $_POST['pswd'];
$sel = $d->select("users", "email_id = '" . $username . "'AND password='" . $pswd . "'") or die('error from here');
$result = mysqli_fetch_array($sel);
if ($result['email_id'] == $username && $result['password'] == $pswd) {
SESSION_START();
$_SESSION['user_name'] = $result['email_id'];
$_SESSION['message'] = 'Invalid Username Or Password';
header("location:index.php");
} else {
$_SESSION['error'] = 'Invalid Username Or Password';
}
}
I got an error
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /opt/lampp/htdocs/ankit_demo/dao.php on line 13
Warning: mysqli_error() expects parameter 1 to be mysqli, null given in /opt/lampp/htdocs/ankit_demo/dao.php on line 13
Please help me to solve this.
Try this out, there was issues with if condition as well as the where condition. and we can't echo a object or can't convert object to string.
dbconnect.php:
<?php
class dbconnect{
public function connect(){
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host,$user,$pass,$db);
return $connection;
}
}
dao.php:
<?php
include 'dbconnect.php';
class dao extends dbconnect {
private $conn;
public function __construct() {
$dbcon = new parent();
// this is not needed in your case
// you can use $this->conn = $this->connect(); without calling parent()
$this->conn = $dbcon->connect();
}
public function select( $table , $where='' , $other='' ){
if($where != '' ){ // condition was wrong
$where = 'where ' . $where; // Added space
}
$sql = "SELECT * FROM ".$table." " .$where. " " .$other;
$sele = mysqli_query($this->conn, $sql) or die(mysqli_error($this->conn));
// echo $sele; // don't use echo statement because - Object of class mysqli_result could not be converted to string
return $sele;
}
}
?>
controller.php:
<?php
include 'dao.php';
$d = new dao();
if(isset($_POST['btn_login'])){
extract($_POST);
$username = $_POST['user_name'];
$pswd = $_POST['pswd'];
$sel = $d->select("users" , "email_id = '" . $username . "' AND password='" . $pswd . "'" ) or die('error from here');
$result = mysqli_fetch_array($sel) ;
if($result['email_id'] == $username && $result['password'] == $pswd){
SESSION_START();
$_SESSION['user_name'] = $result['email_id'];
$_SESSION['message'] = 'Invalid Username Or Password';
header("location:index.php");
}
else{
$_SESSION['error'] = 'Invalid Username Or Password';
// header("Location:login.php");
}
}
?>
Change name of your constructor from __dao() to __construct().
Replace your line 6-th line of code by:
$this->conn = $dbcon->connect();
try this :
include 'dbconnect.php';
class dao extends dbconnect{
private $conn;
function __construct(){
$dbcon = new dbconnect();
$this->conn = $dbcon->connect();
}
function select( $table , $where='' , $other='' ){
if(!$where = '' ){
$where = 'where' . $where;
}
$sql = "SELECT * FROM ".$table." " .$where. " " .$other";
$sele = mysqli_query($this->conn, $sql) or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
Connection file:
class dbconnect{
public function connect(){
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host,$user,$pass,$db);
return $connection;
}
}
dao file:
include 'dbconnect.php';
class dao extends dbconnect {
private $conn;
public function __construct() {
$dbcon = new parent(); // this is not needed in your case
// you can use $this->conn = $this->connect(); without calling parent()
$this->conn = $dbcon->connect();
}
public function select( $table , $where='' , $other='' ){
if(!$where = '' ){
$where = 'where' . $where;
}
$sele = mysqli_query($this->conn,"SELECT * FROM $table $where $other") or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
But I think it would be better to use PDO or much better a ORM system like laravel eloquent.

OOP database connect/disconnect class

I have just started learning the concept of Object oriented programming and have put together a class for connecting to a database, selecting database and closing the database connection. So far everything seems to work out okay except closing the connection to the database.
class Database {
private $host, $username, $password;
public function __construct($ihost, $iusername, $ipassword){
$this->host = $ihost;
$this->username = $iusername;
$this->password = $ipassword;
}
public function connectdb(){
mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
echo 'successfully connected to database<br />';
}
public function select($database){
mysql_select_db($database)
OR die("There was a problem selecting the database.");
echo 'successfully selected database<br />';
}
public function disconnectdb(){
mysql_close($this->connectdb())
OR die("There was a problem disconnecting from the database.");
}
}
$database = new database('localhost', 'root', 'usbw');
$database->connectdb();
$database->select('msm');
$database->disconnectdb();
When I attempt to disconnect from the database I get the following error message:
Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in F:\Programs\webserver\root\oop\oop.php on line 53
I'm guessing it isn't as simple as placing the connectdb method within the parenthesis of the mysql_close function but can't find the right way to do it.
Thanks
I would add a connection/link variable to your class, and use a destructor.
That will also save you from haveing to remember to close your connection, cause it's done automatically.
It is the $this->link that you need to pass to your mysql_close().
class Database {
private $link;
private $host, $username, $password, $database;
public function __construct($host, $username, $password, $database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->link = mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
mysql_select_db($this->database, $this->link)
OR die("There was a problem selecting the database.");
return true;
}
public function query($query) {
$result = mysql_query($query);
if (!$result) die('Invalid query: ' . mysql_error());
return $result;
}
public function __destruct() {
mysql_close($this->link)
OR die("There was a problem disconnecting from the database.");
}
}
Example Usage:
<?php
$db = new Database("localhost", "username", "password", "testDatabase");
$result = $db->query("SELECT * FROM students");
while ($row = mysql_fetch_assoc($result)) {
echo "First Name: " . $row['firstname'] ."<br />";
echo "Last Name: " . $row['lastname'] ."<br />";
echo "Address: " . $row['address'] ."<br />";
echo "Age: " . $row['age'] ."<br />";
echo "<hr />";
}
?>
Edit:
So people can actually use the class, I added the missing properties/methods.
The next step would be to expand on the query method, to include protection against injection, and any other helper functions.
I made the following changes:
Added the missing private properties
Added __construct($host, $username, $password, $database)
Merged connectdb() and select() into __construct() saving an extra two lines of code.
Added query($query)
Example Usage
Please if I made a typo or mistake, leave a constructive comment, so I can fix it for others.
edit 23/06/2018
As pointed out mysql is quite outdated and as this question still receives regular visits I thought I'd post an updated solution.
class Database {
private $mysqli;
private $host, $username, $password, $database;
/**
* Creates the mysql connection.
* Kills the script on connection or database errors.
*
* #param string $host
* #param string $username
* #param string $password
* #param string $database
* #return boolean
*/
public function __construct($host, $username, $password, $database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->mysqli = new mysqli($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$this->mysqli->select_db($this->database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return true;
}
/**
* Prints the currently selected database.
*/
public function print_database_name()
{
/* return name of current default database */
if ($result = $this->mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Selected database is %s.\n", $row[0]);
$result->close();
}
}
/**
* On error returns an array with the error code.
* On success returns an array with multiple mysql data.
*
* #param string $query
* #return array
*/
public function query($query) {
/* array returned, includes a success boolean */
$return = array();
if(!$result = $this->mysqli->query($query))
{
$return['success'] = false;
$return['error'] = $this->mysqli->error;
return $return;
}
$return['success'] = true;
$return['affected_rows'] = $this->mysqli->affected_rows;
$return['insert_id'] = $this->mysqli->insert_id;
if(0 == $this->mysqli->insert_id)
{
$return['count'] = $result->num_rows;
$return['rows'] = array();
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$return['rows'][] = $row;
}
/* free result set */
$result->close();
}
return $return;
}
/**
* Automatically closes the mysql connection
* at the end of the program.
*/
public function __destruct() {
$this->mysqli->close()
OR die("There was a problem disconnecting from the database.");
}
}
Example usage:
<?php
$db = new Database("localhost", "username", "password", "testDatabase");
$result = $db->query("SELECT * FROM students");
if(true == $result['success'])
{
echo "Number of rows: " . $result['count'] ."<br />";
foreach($result['rows'] as $row)
{
echo "First Name: " . $row['firstname'] ."<br />";
echo "Last Name: " . $row['lastname'] ."<br />";
echo "Address: " . $row['address'] ."<br />";
echo "Age: " . $row['age'] ."<br />";
echo "<hr />";
}
}
if(false == $result['success'])
{
echo "An error has occurred: " . $result['error'] ."<br />";
}
?>
you're not returning anything from connectdb() yet you're passing this function's return to mysql_close().
You should be aware that mysql_* functions were introduced in PHP 4, which is more then 1 yours ago. This API is extremely old, and the process has begun to actually deprecating this extension.
You should not in 2012 write new code with mysql_* functions.
There exist two very good alternative : PDO and MySQLi. Both of which are already written with object oriented code in mind, and they also give you ability to use prepared statements.
That example you showed in the original post written with PDO would look like this:
//connect to the the database
$connection = new PDO('mysql:host=localhost;dbname=msm', 'username', 'password');
//disconnects
$connection = null;
Of course there are more complicated use-case, but the point stand - time to evolve.
mysql_close requires a parameter to disconnect but you are providing nothing.
class Database {
private $host, $username, $password, $con;
public function __construct($ihost, $iusername, $ipassword){
$this->host = $ihost;
$this->username = $iusername;
$this->password = $ipassword;
$this->con = false;
}
public function connect() {
$connect = mysql_connect($this->host, $this->username, $this->password);
return $connect;
}
public function connectdb(){
$conn = $this->connect();
if($conn)
{
$this->con = true;
echo "Successsfully Connected. ";
return true;
}
else {
echo "Sorry Could Not Connect. ";
return false;
}
}
public function select($database){
if($this->con)
{
if(mysql_select_db($database))
{
echo "Successfully Connected Database. $database. ";
return true;
}
else
{
echo "Unknown database. ";
}
}
else {
echo "No active Connection. ";
return false;
}
}
public function disconnectdb(){
if($this->con)
{
if(mysql_close($this->connect()))
{
$this->con = false;
echo "Successfully disconnected. ";
return true;
}
}
else
{
echo "Could Not disconnect. ";
return false;
}
}
}
$database = new database('localhost', 'root', '');
$database->connectdb();
$database->select('databaseoffacebook');
$database->disconnectdb();
Object Oriented Programming works well with PDO and mysqli. Give it a try
<?php
class Database{
private $link;
//private $host,$username,$password,$database;
//private $status;
public function __construct(){
$this->host = 'localhost';
$this->username = 'root';
$this->password = '';
$this->database = 'workclass';
$this->link = mysqli_connect($this->host,$this->username,$this->password);
$this->status = mysqli_select_db($this->link,$this->database);
if (!$this->status) {
return $this->status="Failed to Connected with Database";
}else{
return $this->status="Database is connected";
}
}
}
$object = new Database();
echo $object->status;
?>

Categories