How to get database in php using class & function oops concepts - php

I am new developer in php. I'm writing below code a class and functions to connect to the database. but code was not working how to create class and function oops concept help me.
code:
class database {
#code
var $host = "localhost";
var $username ="root";
var $password ="";
var $dbase ="blue";
var $myconnect;
function connectTodata()
{
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
die("Cannot Connect to the datagase");
}
else
{
$his->myconnect = $conn;
echo "Connect Established";
}
return $myconnect;
}
function selectDatabase() // selecting the database.
{
mysql_select_db($this->database); //use php inbuild functions for select database
if(mysql_error()) // if error occured display the error message
{
echo "Cannot find the database ".$this->database;
}
echo "Database selected..";
}
function closeConnection() // close the connection
{
mysql_close($this->myconn);
echo "Connection closed";
}
}

Just to make it work:
class database
{
#code
var $host = "localhost";
var $username ="root";
var $password ="";
var $dbase ="blue";
var $myconnect;
function connectTodata()
{
$this->myconnect = mysql_connect($this->host, $this->username, $this->password);
if(!$this->myconnect) die("Cannot Connect to the datagase");
echo "Connect Established";
return $this->myconnect;
}
function selectDatabase() // selecting the database.
{
mysql_select_db($this->database); //use php inbuild functions for select database
if(mysql_error()) // if error occured display the error message
{
echo "Cannot find the database ".$this->database;
}
echo "Database selected..";
}
function closeConnection() // close the connection
{
mysql_close($this->myconnect);
echo "Connection closed";
}
}

Fix the errors as described by the previous posters, then try this to start:
$database_connection=new database();
$database_handle=$database_connection->connectTodata();
$database_connection->selectDatabase();
$database_connection->closeConnection();
unset($database_connection);
exit();
and in the space between the chunks of code, you can add your mysql queries and use $database_handle as the second parameter.

you can use constructor so that you don't need to call class function everytime :
class database {
var $host = "localhost";
var $username ="root";
var $password ="";
var $dbase ="blue";
var $myconnect;
function __construct() {
$this->myconnect = mysql_connect($this->host, $this->username, $this->password);
if( !$this->myconnect ) {
$msg = "could not connect to mysql database <Br/>";
$msg .= mysql_error();
die($msg);
}
$db_connect = mysql_select_db($this->dbase, $this->myconnect);
if( !$db_connect ) {
die(" can not select database \n".mysql_error());
}
}
function __destruct() {
mysql_close($this->myconnect);
}
}
// call database
$con = new database();

You can do it with the help of Defining them something like
define("DB_SERVER_NAME","your host");
define("DB_USER_NAME","your user name");
define("DB_USER_PASSWORD","your password");
define("DB_DATABASE_NAME","your database");
now the connection file:
class DBClass{
public $DB_LINK;
public $DB_DATABASE_NAME;
function DBClass($Main_DB = FALSE){
$this->DB_LINK = #mysqli_connect(DB_SERVER_NAME,DB_USER_NAME,DB_USER_PASSWORD,DB_DATABASE_NAME);
if(! $this->DB_LINK){
die("<h2>Could not connect to Database.</h2>");
}
}
function __destruct(){
mysqli_close($this->DB_LINK);
}
}
This works perfectly for me

Related

Database Connection Issue

I cannot connect to my database and I do not understand why.
I've run my php in a php checker with no errors.
I'm watching an online course and following the instructions to the letter, yet I'm getting the 'http 500 error' when I try to test and see if it works.
Heres my php:
<?php
//STEP 1. Declare params of user information
$email = htmlentities($_REQUEST["email"]);
$password = htmlentities($_REQUEST["password"]);
$test = "test";
if (empty($email) || empty($password)) {
$returnArray["status"] = "400";
$returnArray["message"] = "Missing required information";
echo json_encode($returnArray);
return;
}
//secure password
$salt = openssl_random_pseudo_bytes(20);
$secured_password = sha1($password . $salt);
//build connection
//secure way to build connection
$file = parse_ini_file("../caps.ini");
//store in php var info from ini var
$host = trim($file["dbhost"]);
$user = trim($file["dbuser"]);
$pass = trim($file["dbpass"]);
$name = trim($file["dbname"]);
// include access.php to call func from access.php file
require("secure/access.php");
$access = new access($host, $user, $pass, $name);
$access->connect();
?>
And here is the caps.ini file I made in a text editor, I've omitted the information here:
; Connection information
[section]
dbhost = omitted
dbuser = omitted
dbpass = omitted
dbname = omitted
And finally this is my php file where I reference my connection function:
<?php
//Declare class to access this php file
class access {
//connection global variables
var $host = null;
var $user = null;
var $pass = null;
var $name = null;
var $conn = null;
var $result = null;
// constructing class
function __construct($dbhost, $dbuser, $dbpass, $dbname) {
$this->host = $dbhost;
$this->user = $dbuser;
$this->pass = $dbpass;
$this->name = $dbname;
}
// Connection Function
public function connect() {
//establish connection and store it in $conn
$this->conn = new msqli($this->host, $this->user, $this->pass, $this->name);
//if error
if (mysqli_connect_errno()) {
echo 'Could not connect to database';
} else {
echo "Connected";
}
//support all languages
$this->conn->set_charset("utf8");
}
//disconnection function
public function disconnect() {
if ($this->conn != null) {
$this->conn->close();
}
}
}
Here is my folder structure as well:
My assumption is this typo around msqli vs mysqli
$this->conn = new msqli($this->host, $this->user, $this->pass, $this->name);
should be
$this->conn = new mysqli($this->host, $this->user, $this->pass, $this->name);

Can't connect to the database with my class?

I'm trying to connect to my database but it won't connect. I tried but won't connect. the error I'm getting is Parse error: syntax error, unexpected 'connect' (T_STRING) in C:\htdocs\www\dating\index.php on line 3. I called the tried new Database connect(); and tried connect(); I get this message Fatal error: Call to undefined function connect() in C:\htdocs\www\dating\index.php on line 3. What's wrong?
class Database{
private $db_host = "localhost";
private $db_user = "123346";
private $db_pass = "12345";
private $db_name = "1234";
public $conn;
// Create connection
public function connect(){
if(!isset($this->conn)){
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);
if($this->conn){
$this->conn = true;
return true;
}else{
$this->conn = false;
return false;
}
}
}
public function disconnect(){
if(isset($this->conn)){
if(mysqli_close($this->conn)){
$this->myconn = false;
echo "connection closed";
return true;
} else{
echo "failed to close connection";
return false;
}
}else{
echo "no connection prescent";
}
}
}
I'm trying to get use query now but it won't get the results. Here is the code
include("functions/connect.php");
$db = new Database("localhost", "12345", "1234", "123");
$db->connectdb();
$db->select('rpg');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT id, username FROM users ORDER by ID DESC ";
if ($result = $db->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
/* free result set */
$result->close();
}
/* close connection */
$db->close();`
Please change this line
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);
to this
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
You will notice you used $this->pass but it should be $this->db_pass.
To call the function of Database class you have to write your code like this;
<?php
include("functions/connect.php");
$db_conn = new Database();
if($db_conn->connect()) {
echo "Database connected";
}

Mysqli connection in function PHP

I'm facing a PHP problem. I've searched the web but couldn't find the answer. This is my code so far:
<?php
$db_host = 'db_host';
$db_user = 'db_user';
$db_password = 'db_password';
$db_name = 'db_name';
//not showing you the real db login ofcourse
$conn = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if($conn) {
echo 'We are connected!';
}
Up to here, everyting goes well. The connection is established and 'We are connected!' appears on the screen.
function login($username, $password, $conn) {
$result = $conn->query("SELECT * FROM users");
echo mysqli_errno($conn) . mysqli_error($conn);
}
When I run this function however, the mysqli error 'No database selected pops up. So I added the following piece of code the the file before and in the function, so the total code becomes:
<?php
$db_host = 'db_host';
$db_user = 'db_user';
$db_password = 'db_password';
$db_name = 'db_name';
//not showing you the real db login ofcourse
$conn = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if($conn) {
echo 'We are connected!';
}
if (!mysqli_select_db($conn, $db_name)) {
die("1st time failed");
}
function login($username, $password, $conn, $db_name) {
if (!mysqli_select_db($conn, $db_name)) {
die("2nd time failed");
}
$result = $conn->query("SELECT * FROM users");
echo mysqli_errno($conn) . mysqli_error($conn);
}
$username = 'test';
$password = 'test';
login($username, $password, $conn, $db_name);
?>
The first time adding the database name works fine, however, in the function it doesn't work. I've also tried using global $conn inside the function but that didn't work either. Changing mysqli_connect() to new mysqli() also doesn't have any effect.
Thanks in advance!
Please be aware, this code is refactored based on your code, and the login logic is NOT RECOMMENDED. Please try this code and make the changes that you think you need.
Make sure that your Database information is also updated as needed.
MyDB Class
Class MyDB {
protected $_DB_HOST = 'localhost';
protected $_DB_USER = 'user';
protected $_DB_PASS = 'password';
protected $_DB_NAME = 'table_name';
protected $_conn;
public function __construct() {
$this->_conn = mysqli_connect($this->_DB_HOST, $this->_DB_USER, $this->_DB_PASS);
if($this->_conn) {
echo 'We are connected!<br>';
}
}
public function connect() {
if(!mysqli_select_db($this->_conn, $this->_DB_NAME)) {
die("1st time failed<br>");
}
return $this->_conn;
}
}
Login Class
Class Login {
protected $_conn;
public function __construct() {
$db = new MyDB();
$this->_conn = $db->connect();
}
//This is a HORRIBLE way to check your login. Please change your logic here. I am just kind of re-using what you got
public function login($username, $password) {
$result = $this->_conn->query("SELECT * FROM user WHERE username ='$username' AND password='$password'");
if(!$result) {
echo mysqli_errno($this->_conn) . mysqli_error($this->_conn);
return false;
}
return $result->fetch_row() > 0;
}
}
Usage
$login = new Login();
$logged = $login->login('username', 'password');
if ($logged) {
echo "yeah!! you are IN";
} else {
echo "boo!! . Wrong username and password";
}

Prepared statement database connection must be instansiated first?

The parts in bold are what I am questioning. Inside the search_for_new_user function, if I change $conn->prepare to $this->db_connection()->prepare. I receive a lost connection error. However in the function right above it db_conn_test I can use this syntax. In both cases I am returning the $connection so I don't understand why there must be a difference in syntax.
class Database {
function db_connection() {
$server = "localhost";
$user = "user";
$password = "password";
$database = "database";
return $connection = new mysqli($server, $user, $password, $database);
}
function db_conn_test() {
if (**$this->db_connection()->connect_errno**) {
die($this->db_connection()->connect_errno . ": " . $this->db_connection()->connect_error);
} else {
echo "connected to mysql database";
}
}
function search_for_new_user($email) {
**$conn = $this->db_connection();**
if ($stmt = **$conn->prepare**("SELECT email FROM users where email = ?")) {
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
echo $result;
$stmt->close();
$conn->close();
}
}
}
In db_conn_test you call db_connection twice only if you got connection error during first db_connection call, so in this case connection to DB is not created.
But in search_for_new_user you create connection twice.
I.e.:
in db_conn_test:
// if connection not created, because you got error
if ($this->db_connection()->connect_errno) {
// therefore each time you call db_connection(),
// you again try create connection, and got same error
// and return it in die text
die($this->db_connection()->connect_errno . ": " . $this->db_connection()->connect_error);
} else {
echo "connected to mysql database";
}
but in search_for_new_user: you call db_connection() and create connection(if all is ok). And then if you call db_connection in second try, first connection is gone away and you got error.
Your class should looks like this:
class Database {
protected $connection;
function db_connection() {
if ($this->connection !== null) {
return $this->connection;
}
$server = "localhost";
$user = "user";
$password = "password";
$database = "database";
return $this->connection = new mysqli($server, $user, $password, $database);
}
}

php mysql script not working

I got my script working for one column of data but I am trying to send it other data to a second column in mysql table. Here's my php code:
<?php
function db_connect()
{
$hostname = '127.0.0.1';
$db_user = 'root';
$db_password = '';
$db_name = 'hit';
mysql_connect ($hostname, $db_user, $db_password) or die (mysql_error());
echo "Success.. Connected to MySQL...<br />";
mysql_select_db($db_name) or die(mysql_error());
echo "Success.. Connected to Database...<br /> ";
}
function insertData($DATA)
{
function insterData($DATA2)
{
db_connect();
$requete = "INSERT INTO data SET col_Data='".$DATA."'";
if(!mysql_query($requete))
echo mysql_error();
else
echo 'data accepted.';
$requete2 = "INSERT INTO data SET col_Data2='".$DATA2."'";
if(!mysql_query($requete2))
echo mysql_error();
else
echo 'data accepted.';
}
if(isset($_GET['DATA']))
if(isset($_GET['DATA2']))
}
insertData($_GET['DATA']);
insertData($_GET['DATA2']);
}
else
{
echo 'Nop';
}
?>
This is how I send the post data
http://localhost/hit.php?DATA=iamwicked&DATA2=iamcool
This then suppose to send DATA=iamwicked goes into database hit table data column col_data
This then suppose to send DATA2=iamcool goes into database hit table data column col_data2
But I get this error,
but there are errors can someone help me debug.
Here is a working script:
<?php
function db_connect()
{
$hostname = '127.0.0.1';
$db_user = 'root';
$db_password = '';
$db_name = 'hit';
mysql_connect ($hostname, $db_user, $db_password) or die (mysql_error());
echo "Success.. Connected to MySQL...<br />";
mysql_select_db($db_name) or die(mysql_error());
echo "Success.. Connected to Database...<br /> ";
}
function insertData($DATA)
{
db_connect();
$requete = "INSERT INTO data SET col_Data='".$DATA."'";
if(!mysql_query($requete))
echo mysql_error();
else
echo 'data accepted.';
}
if(isset($_GET['DATA']))
{
insertData($_GET['DATA']);
}
else
{
echo 'Nop';
}
?>
this is a working script when I use this url to post data
localhost/hit.php?DATA=iamwicked
When I use this it save iamwicked in database hit table data column col_data
so how do I fix my script to send more data to col_data2 and so forth
Return $conn connection resource #id from function
<?php
function db_connect()
{
$hostname = '127.0.0.1';
$db_user = 'root';
$db_password = '';
$db_name = 'hit';
$conn = mysql_connect ($hostname, $db_user, $db_password) or
die (mysql_error());
echo "Success.. Connected to MySQL...<br />";
mysql_select_db($db_name) or die(mysql_error());
echo "Success.. Connected to Database...<br /> ";
return $conn;
}
$conn = db_connect();
To insert single field
function insertData($DATA)
{
$requete = "INSERT INTO data SET col_Data='".$DATA."'";
mysql_query($requete) or die(mysql_error());
}
if(isset($_GET['DATA'])) {
insertData($_GET['DATA']);
}
if(isset($_GET['DATA2'])) {
insertData($_GET['DATA2']);
}
UPDATE
To insert multiple fields
function insertData($DATA, $DATA2)
{
$requete = "INSERT INTO data SET col_Data='".$DATA."', col_Data2='".$DATA2."'";
mysql_query($requete) or die(mysql_error());
}
if(isset($_GET['DATA']) && isset($_GET['DATA2'])) {
insertData($_GET['DATA'], $_GET['DATA2']);
}
?>
I think you have an wrong spelling here:
function insertData($DATA2) instead of function insterData($DATA2);
There are indeed two problems here.
function insertData($DATA)
{
function insterData($DATA2)
{
What are you trying to achieve here? Declaring a function inside another function is totally useless (and generates errors since it's not allowed). If you want to call a function inside another one you must declare them separately and then call them, f.e.
function insertData($DATA)
{
insterData($somevariable);
//Rest of the operations
}
This should be clear enough. There is another error though.
if(isset($_GET['DATA']))
if(isset($_GET['DATA2']))
}
insertData($_GET['DATA']);
insertData($_GET['DATA2']);
}
else
{
echo 'Nop';
}
I suppose there is a typo here, and you meant
if(isset($_GET['DATA2']))
{

Categories