PHP script to connect to SQL - php

I am at learning stage of PHP. I am using a php file to process form data for sql table and it has server name, user, password and dbname to perform sql-connect query. And of course it is in public directory of website. Is it a safe way or any suggestion is appreciated. example is as follow:
$name = $_POST['name'];
$phn = $_POST['phn'] ;
$servername = "localhost";
$username = "abc";
$password = "abc";
$dbname = "abc";
// Create connection
$conn = mysqli($servername, $username, $password, $dbname);

Connecting using the mysqli extension gives you the ability to use newer MySQL features such as transactional queries and parameterised queries which aren't available using the older mysql extension.
Have a look at MySQL Improved Extension # php.net

Your mysql should be mysqli_connect ()

You forgot new before instantiating the MySQLi connection.
Try this instead:
$conn = new mysqli($servername, $username, $password, $dbname);

You can store database credentials anywhere, but better store them somewhere OUTSIDE of your main PHP folder, using this approach:
/config/db.config.php
<?php
define('DB_USER', 'root');
define('DB_PASS', 'pass');
define('DB_DATABASE', 'database');
define('DB_HOST', 'host');
If you will store it INSIDE of your php folder, each time, when you copy your code from local to web, you will override your configurations. Also, such file is safe (if you will accss it from web, you will see nothing), but I stil advice to put here .htaccess file with deny for all content.
Also, I can advice DO NOT USE mysqli_connect without any wrapper. (better use PDO with parametrised queries). But, if you want to work with mysqli, better search in web for good wrapper, or write it by self. From my experience, most better way to work with mysqli is create class with static functions:
class DB {
public static function init($dbHost, $dbUser, $dbPass, $db);
public static function getTable($query);//get array of arrays
public static function getRow($query);//get array (one database row)
public static function getCell($query);//get single value
public static function getColumn($query);//get array (column)
public static function query($query);//update, delete, insert
}
because with this class you will be able to get data in any place of your script using something:
$list = DB::getTable("select * from table");

please try this
<?php
$servername = "localhost";
$username = "abc";
$password = "abc";
$dbname = "abc";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$name = $_POST['name'];
$phn = $_POST['phn'] ;
?>

Related

MySQL <= 5.2 - OOP connect to database in class

I CAN'T USE MYSQLI OR PDO
I'm currently working on a legacy project (5.2) where I can't use fancy extensions like MySQLi or PDO - Only MySQL - How would I connect to a database and use that connection in a class?
Basically this
public function __construct($pdo) {
$this->db = $pdo;
}
As 5.2 MySQL / PHP
I just need a simple example to get started.
Thanks!
PDO Connection through PHP
I highly recommend to use PDO rather than mysqli.. pdo is faster and use prepared statements to avoid sql injection, and Filter, Sanitize the user inputs.
<?php
session_start();
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
You can use the above code for PHP 5.2.9 and 5.3.0

Database connection in parent constructor not working in child method

I have a parent class page, and in it I have a constructor that connects to the database successfully. Here is the code for that:
//establish database connection
function __construct() {
require('db_conn.php');
$this->conn = new mysqli($servername, $username, $password);
}
I want to be able to access the database in the subclass pages- for example the register page class.
I have a function login() in that register subclass that needs to access the database connection variable. Here is the code for that:
private function Register() {
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
//check data is valid i.e. not in database already
$query = mysqli_query($this->conn,'SELECT * FROM users');
if (mysqli_fetch_assoc($query)) {
echo "That email or username already exists!";
} else {
//store data
}
The variable is being detected but seems to not hold a connection, which is strange because I've tried testing it with mysqli_ping() in the same function and it returned true.
If i require the db connection inside the function the query works.
This is my first time using OOP, could be I've missed something straightforward. any help would be great. thanks
I'm aware the queries are wrong- I just wanted to simplify them for the sake of debugging
List item
The first and most obvious issue is that you dont seem to have selected the database you want to use. Remember MySQL manages multiple database.
Note parameter 4 of the mysqli class instantiation should contain a database name
new mysqli('localhost', 'my_user', 'my_password', 'my_db');
whereas yours does not
$this->conn = new mysqli($servername, $username, $password,'MISSING DATABASE NAME');
Can I suggest that while developing you add these lines to the top of all your scripts so that you see any errors in the browser.
<?php
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

PHP. How can I create a functions' library?

I've got not too much experience programing but I've done a little application with a few PHP files and I'd like to optimize it.
I want to extract all the repeated code and place it inside a folder as a PHP file, that I will call later, when I need the code.
For example this lines are repeated in all my files:
$servername = "ejemplo.es";
$username = "ramon";
$dbname = "bbdd";
$password = "loquesea";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
first of all, you should read a php tutorial about functions and object orientated programming.
In your case, you could have a class for your database things called Database, which would look something like this:
<?php
class Database
{
private $_connection = null;
public function __construct($host, $username, $password, $database)
{
// connect to database and store the connection for further use
}
public function doThisAndThat()
{
// do some fancy database stuff
}
public function __destruct()
{
// important for databases is to disconnect from them
}
}
Then all you have to do is include your Database class file and call it like that:
$db = new Database($host, $username, $password, $database);
$db->doThisAndThat();

how to avoid the new PDO(...) line of code to appear too often?

There is something, as a newbie, that a I want to understand about About database connections.
I am starting off from a tutorial on PHP which has this structure:
Connect.php:
<?php
$username = "dbusername";
$password = "dbpassword";
$host = "localhost";
$dbname = "dbname";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
Login.php:
<?php
require("connect.php");
// some code not important for this question,
//that handles login with a session…
?>
various_file_in_the_login_system.php:
<?php
require("connect.php");
// some code that checks if user is logged in with session_ …
// some code that does need the database connection to work
?>
All other files also contain that require("connect.php"); line. It works, but I just don’t know what these connection request to the server – I may not be using the right vocabulary -- end up doing to the server. They are superfluous if the connection is not timed out, are they not?
I found a post which talked about doing a singleton for PDO, and a post which makes me feel like never using persistent connections in my life.
Does this design causes excessive connection churning?
Perhaps servers can handle very many request for connection per second, perhaps a server has its own internal persistent connection mode, or implements connection pooling…
Or the PDO object handle the problem of asking connection too often for no reason…
PDO + Singleton : Why using it?
What are the disadvantages of using persistent connection in PDO
This is what I can recommend for your database connection:
Make a class for the connection:
class Database{
private static $link = null ;
public static function getConnection ( ) {
if (self :: $link) {
return self :: $link;
}
$dsn = "mysql:dbname=social_network;host=localhost";
$user = "user";
$password = "pass";
self :: $link = new PDO($dsn, $user, $password);
return self :: $link;
}
}
Then you can get the connection like this:
Database::getConnection();
The Singleton Pattern is hard to scale - However, I think it will probably be fine for your needs. It takes a lot of load off your database.
I don't think you will be able to avoid the multiple includes.
There is a php.ini setting for prepending a file to every script -> http://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
How about you change to
require_once('connect.php');
in all locations?
Also you should probably remove session_start() and HTTP header logic from a section of code that has to do with establishing a DB connection. This simply does not make sense there.

Connecting to two databases

I have an application in which I want to authenticate a user from a first database & manage other activities from another database.
I have created two classes. An object of the classes is defined in a file:
$objdb1=new db1(),$objdb2=new db2();
But when I try to call $objdb1->fn(). It searches from the $objdb2 & is showing table1 doesnot exists?
My first file database.php
class database
{
private $hostname;
private $database;
private $username;
private $password;
private $dblinkid;
function __construct()
{
if($_SERVER['SERVER_NAME'] == 'localhost')
{
$this->hostname = "localhost";
$this->database = "aaaa";
$this->username = "xxx";
$this->password = "";
}
else
{
$this->hostname = "localhost";
$this->database = "xxx";
$this->username = "xxx";
$this->password = "xxx";
}
$this->dblinkid = $this->connect();
}
protected function connect()
{
$linkid = mysql_connect($this->hostname, $this->username, $this->password) or die("Could not Connect ".mysql_errno($linkid));
mysql_select_db($this->database, $linkid) or die("Could not select database ".mysql_errno($linkid)) ;
return $linkid;
}
Similarly second file
class database2
{
private $vhostname;
private $vdatabase;
private $vusername;
private $vpassword;
private $vdblinkid;
function __construct()
{
if($_SERVER['SERVER_NAME'] == 'localhost')
{
$this->vhostname = "xxx";
$this->vdatabase = "bbbb";
$this->vusername = "xxx";
$this->vpassword = "";
}
else
{
$this->vhostname = "localhost";
$this->vdatabase = "xxxx";
$this->vusername = "xxxx";
$this->vpassword = "xxxx";
}
$this->vdblinkid = $this->vconnect();
}
protected function vconnect()
{
$vlinkid = mysql_connect($this->vhostname, $this->vusername, $this->vpassword) or die("Could not Connect ".mysql_errno($vlinkid));
mysql_select_db($this->vdatabase, $vlinkid) or die("Could not select database ".mysql_errno($vlinkid)) ;
return $vlinkid;
}
Third file
$objdb1 = new database();
$objdb2 = new database2();
Can you help me on this?
Regards,
Pankaj
Without knowing your classes, it is difficult to help. If you are using PDO, I can guarantee you that you can create multiple instances connected to different databases without any problem. If you are using the mysql_ family of functions you probably just forgot to set the link_identifier parameter (see here).
However, having a class db1 and a class db2 sounds like a code smell to me. You probably want to have two instances of the same class with different attributes.
Each time you call mysql_connect() or the equivalent mysqli functions, if a connection already exists using those same credentials it gets reused - so anything you do to modify the state of the connection, including changing database, charsets, or other mysql session variables affects "both" connections.
Since you are using the mysql_connect() function you have the option to force a new connection each time but this is not supported on all the extensions (IIRC mysqli and PDO don't alow for this).
However IMHO this is the wrong way to solve the problem. It just becomes messy trying to keep track of what's connected where.
The right way would be to specify the database in every query:
SELECT stuff FROM aaaa.first f, aaaa.second s
WHERE f.something=s.something;
Most likely your class does not pass the appropriate connection resource to the database functions. The second argument to e.g. mysql_query() is the connection resource. Simply store this resource in an instance variable on connection, and use it every time you do something with the database.
Your problem may be in checking if the SERVER_NAME is "localhost". Seems like you may be using the same connection strings in both classes. What is $_SERVER['SERVER_NAME'] resolving to?
You're looking for the fourth parameter of mysql_connect(), which states that it shouldn't reuse existing connections:
$dbLink1 = mysql_connect($server, $user, $pass, true);
mysql_select_db($db1, $dbLink1);
$dbLink2 = mysql_connect($server, $user, $pass, true);
mysql_select_db($db2, $dbLink2);
mysql_query("SELECT * FROM table1", $dbLink1); // <-- Will work
mysql_query("SELECT * FROM table1", $dbLink2); // <-- Will fail, because table1 doesn't exists in $db2
Passing the fourth parameter as true to mysql_connect resolves the issue.
$linkid = mysql_connect($this->hostname, $this->username, $this->password,true) or die("Could not Connect ".mysql_errno($linkid));

Categories