I'm trying to connect to the database, but dont know what is the problem with this one. the code goes like this. Please help I'm very new to the php. :(
db_config.php
<?php define('DB_USER', "root");
define('DB_PASSWORD', "database password");
define('DB_DATABASE', "ews_app");
define('DB_SERVER', "Im using the 'drupal' for webhosting should I give server address or localhost");
?>
db_connect.php
<?php
class DB_CONNECT {
function __construct() {
$this->connect();
echo "<p>server connected</p>";
}
function __destruct() {
$this->close();
}
function connect() {
require_once __DIR__ . '/db_config.php';
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
return $con;
}
function close() {
mysql_close();
}
}
?>
It should print server connected once it connect to the database. Are there any modification needed on it.
You don't appear to ever be instantiating the object, so the constructor never gets run, so of course no connection is established, so you don't get any output.
Try adding $connection = new DB_CONNECT()
Related
I am very new in PHP and I'm trying to connect to my mysql database.
The code for select is the following:
public function getAllTeams(){
$stmt = $this->conn->prepare("SELECT * FROM maras_app");
$stmt->execute();
$result = $stmt->get_result();
echo json_encode($result);
return $result;
}
The connection is successful because I put in code to echo if there is an error. The response I get is the following:
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
The tables have 14 columns.
In the dataBase I have only one row inserted with last 4 columns null.
Any idea why I'm getting null as response?
This is how I'm creating my connection:
private $conn;
//Constructor
function __construct()
{
require_once dirname(__FILE__) . '/Configuratii.php';
require_once dirname(__FILE__) . '/ConexiunDB.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
Here is Configuratii.php:
define('DB_USERNAME', '---');
define('DB_PASSWORD', '---');
define('DB_HOST', '---');
define('DB_NAME', '---');
And here is ConexiunDB.php:
class DbConnect
{
private $conn;
function __construct()
{
}
function connect()
{
require_once 'Configuratii.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// returing connection resource
return $this->conn;
}
}
I really can't get what's there and don't know to debug because is the second time I use PHP.
DbConnect.php
<?php
/**
* Handling database connection
*/
include_once ('Config.php');
class DbConnect {
private $conn;
function __construct() {
}
/**
* Establishing database connection
* #return database connection handler
*/
function connect() {
// Connecting to mysql database
$this->conn = new mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
// returing connection resource
return $this->conn;
}
}
class DbHandler {
private $conn;
function __construct() {
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}}
?>
config.php
<?php
/**
* Database configuration
*/
define('DB_USERNAME', 'medma');
define('DB_PASSWORD', 'medma');
define('DB_HOST', 'localhost');
define('DB_NAME', 'medma_sameer');
/**
* MSG91 configuration
*/
define('MSG91_AUTH_KEY', "130558AmTMgKzL582187bb");
// sender id should 6 character long
define('MSG91_SENDER_ID', 'MEDMA1');
define('USER_CREATED_SUCCESSFULLY', 0);
define('USER_CREATE_FAILED', 1);
define('USER_ALREADY_EXISTED', 2);
?>
Please tell me what could be the problem though i have posted before Not able to hit api to verify otp ( Used Volley)
but when i started testing each php file on my localhost folder where i have mounted i got stuck with the very initial step which is database connection the code i wrote above doesn't show anything except blank
There are 2 problems here that could cause the page to be blank:
The first is that you don't actually output anything in your script, at least not in the code you have posted.
The bigger problem is that this is probably wrong as you don't seem to be inside a method / class:
$db = new DbConnect();
$this->conn = $db->connect();
$this is defined in the scope of a method so using it like you are doing would lead to a fatal error:
Fatal error: Using $this when not in object context in ...
As a side-note: If you want to show the contents of a variable, you should use var_dump() instead of echo because the last only gives any meaningfull output for numbers and strings; not for database connections.
First of all you bad invoke a connection here
$db = new DbConnect();
$this->conn = $db->connect();
You can not access property conn in this scope (outside of a class) this way
You can do this using $db->conn. However in this situation you can't access it aswell as it is a private
If you would like to do this using your class you can try
$db = new DbConnect();
$conn = $db->connect();
and under $conn u have a db connection.
#edit:
Maybe try use this
<?php
include_once ('Config.php');
/**
* Handling database connection
*/
class DbConnect {
private static $_instance; //The single instance
private $_conn;
public static function getInstance() {
if(!self::$_instance) { // If no instance then make one
self::$_instance = new self();
}
return self::$_instance;
}
private function __construct() {
// Connecting to mysql database
$this->_conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
}
// Get connection
function getConnection() {
return $this->_conn;
}
}
To make a connection to database you can do that
$db = DbConnect::getInstance();
$conn = $db->getConnection();
$query= "SELECT foo FROM .....";
$result = $conn->query($query);
Currently My code is this to connect my database.
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
db_config.php is
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "leading10"); // database name
define('DB_SERVER', "localhost"); // db server
?>
on using the above code somewhere it shows an warning to use mysqli or PDO
I followed many stackoverflow questions but still I was not able to do it successfully .
One of the methods I know is to use # symbol before mysql_connect() but it may not work in future.
Any Help Appreciated
As other guys already wrote you should use mysqli_* functions. But this is not the problem in your case.
The problem is you assign the connection to $con which is a local variable and therefore - once connect() quits - the value gets lost.
This code works:
class DB_CONNECT
{
private $connection;
private $database;
function __construct() {
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
$this->connection = mysqli_connect( DB_SERVER, DB_USER, DB_PASSWORD ) or die(mysql_error());
$this->database = mysqli_select_db( DB_DATABASE ) or die(mysql_error());
}
function close() {
mysqli_close( $this->connection );
}
}
Note:
In your code you have twice or die(...) in a line.
Use this to turn off error reporting
write it on the top of the page
error_reporting(E_ERROR | E_WARNING | E_PARSE);
here is the link for more info
http://www.w3schools.com/php/func_error_reporting.asp
It is not working because you are using mysql, which is depreciated, change all mysql to mysqli. This is an edited version of your code.
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysqli_error());
// Selecing database
$db = mysqli_select_db(DB_DATABASE) or die(mysqli_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysqli_close();
}
}
?>
Am using MAMP local host server and am trying to get the data from the table below
I don't get any syntax errors or stack errors but when a blank browser page and yes the display_errors and all are all turned On in the php.in file.
Below are the function files am using:
For the config.php file :
<?php
define("DB_HOST", "MyLocalHost");
define("DB_USER", "user");
define("DB_PASSWORD", "");
define("DB_DATABASE", "db");
?>
For DB_Connect File
<?php
class DB_Connect {
// constructor
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
// Connecting to database
public function connect() {
require_once 'include/Config.php';
// connecting to mysql
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysqli_error());
// selecting database
mysqli_select_db($con,DB_DATABASE) or die(mysqli_error());
// return database handler
return $con;
}
// Closing database connection
public function close() {
mysql_close();
}
}
?>
For DB_Functions File:
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
public function getAppointments($did) {
$result = mysqli_query($this->db->connect(),"SELECT * FROM appointment WHERE did='$did'");
$appointments=array();
if($result){
while($row = mysqli_fetch_assoc($result)) {
$appointments[]=$row;
}
return $appointments;
}
else{
return false;
}
}
public function getAppointmentsByJSON($did){
echo json_encode($this->getAppointments($did));
}
}
?>
And for my getAppointmentsJson file :
<?php
//include "include/DB_Connect.php";
include "include/DB_Functions.php";
if(isset($_GET["did"])){
if(is_numeric($_GET["did"])){
$testObject = new DB_Functions();
$testObject->getAppointmentsByJSON($_GET["did"]);
echo json_encode($testObject);
}
}
?>
And help advices or tips provided will be greatly appreciated.
Thank you
After replicating your code and replicating the database.
The only conclusion i can come to is that, your getAppointmentsJson.php script expects a get parameter.
If you browsed to getAppointmentsJson.php?did=1
you would see an output.
Also i edited two lines in your DB_Connect class as mysqli_error(); expects exactly 1 parameter and you didn't pass it one.
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysqli_error($con));
// selecting database
mysqli_select_db($con,DB_DATABASE) or die(mysqli_error($con));
I'm sorry to imform you but a blank PHP page is 99% of the time an error in php and usually the syntax. While you can enable error reporting in your ini file I would suggest doing that above the constant definitions in your case.
error_reporting(-1); // enable error reporting on known and future defined errors
ini_set('display_errors', 'On');
In your getAppointmentsJson is an error, specifically echo json_encode($testObject,);
PHP expects an additional argument giving the ,.
I have following code, however $email is not getting printed on page. I don't know why.
<?php
$email = "myemil#gmail.com";
$tag = "login";
require_once 'DB_Functions.php';
$db = new DB_Functions();
echo $email;
?>
If I remove
require_once 'DB_Functions.php'; $db = new DB_Functions();
then it prints email on page. Why is this happening? I want to connect to DB. Please help.
Above code file is on godaddy server, in a subdomain.
DB_Functions.php looks like
class DB_Functions {
private $db;
function __construct() {
require_once 'DB_Connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
function __destruct() {
}
}
DB_Connect looks like
class DB_Connect {
// constructor
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
// Connecting to database
public function connect() {
require_once 'config.php';
// connecting to mysql
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
// selecting database
mysql_select_db(DB_DATABASE);
// return database handler
return $con;
}
// Closing database connection
public function close() {
mysql_close();
}
}
config.php
define("DB_HOST", "localhost");
define("DB_USER", "db1");
define("DB_PASSWORD", "db1");
define("DB_DATABASE", "db1");