MySQL connect on PHP - php

what is the best way to connect PHP application on MySQL.
So far I had the below connection classes.
class Connection{
private static $server = "127.0.0.1";
private static $catalog = "schemadb";
private static $username = "rootuser";
private static $password = "password";
public static $current = null;
public static function Open(){
self::$current = mysqli_init();
if(!self::$current){
die("Failed to initialize connection");
}
if(!self::$current->real_connect(self::$server,self::$username,self::$password,self::$catalog)){
die("Cannot connect to server");
}
return self::$current;
}
public static function Close(){
self::$current->close();
}
}
and also I have
abstract class abstractDAO
{
protected function getConnection()
{
$mysqli = new mysqli("127.0.0.1","rootuser","password","schemadb");
return $mysqli;
}
}
or if there's any other best approach to connect PHP application on MySQL. Please advise thanks..

You can try using the PDO object:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Have a look at PHP PDO documentation page

Try to use php frameworks like codeigniter, Yii, cake php. If you implement in any one of this framework no need to write php mysql query It will automatically generate.
You just need to enter your database configuration like give in below
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'sample';

You can connect through data using PDO, here is an example
<?php
$servername = "localhost";
$username = "root";
$password = "nopass";
try {
$conn = new PDO("mysql:host=$servername;dbname=wireframe", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
$stmt = $conn->prepare("SELECT * FROM todolist");
$stmt->execute();
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<table border="1" align="center">
<tr>
<th>name</th>
<th>type</th>
<th>status</th>
</tr>
<?php
foreach($stmt->fetchAll() as $k=>$v){
echo
"<tr>
<td>{$v['name']}</td>
<td>{$v['type']}</td>
<td>{$v['status']}</td>
</tr>\n";
}
?>
</table>
</body>
</html>

try this
<?php
$user = $_POST["username"];//if this doesnt work try the next line
$user = (isset($_POST["username"]) ? $_POST["username"] : "");
$host = "localhost";//mysql password
$username = "";//mysql username
$password = "";//mysql password
$db_name = "database";//database name
$tbl_name ="test";//table name
//make the connection
$con = mysql_connect("$host","username","password")or die("Could not connect.");
$conn = mysql_select_db("$db_name")or die("Could not select database.");
$sql = "SELECT * FROM $tbl_name WHERE username='$username'";
//query mysql
$result = mysql_query($sql);
if($result){
//if it works show this
}else{
//if it doesnt work show this
}
?>
ive tryed a lot of times to make a connection to a database and i finaly found one.

Related

How to connect MySQL db using new XAMPP

Old connection method mysql_connect maybe deprecated from PHP7 so what is the best way to connect and query in mysql using XAMPP or how I implement PDO in my bellow script.
<?php
$key = $_GET['key'];
$array = array();
$con = mysql_connect("localhost", "root", "");
$db = mysql_select_db("search", $con);
$query = mysql_query("select * from ajax_example where name LIKE '%{$key}%'");
while ($row = mysql_fetch_assoc($query)) {
$array[] = $row['name'];
}
echo json_encode($array);
?>
Database connection using mysqli_* :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
For further mysqli_* statement syntax refer: Mysqli_* Manual
Database connection using PDO_* :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
For further PDO_* statement syntax refer PDO_* Manual
$conn = new Connection();
$query = "select * from ajax_example where name LIKE '%{$key}%'";
$res = $conn->execute_query($query)->fetchall(PDO::FETCH_ASSOC);
if (!empty($res))
{
$result['data'] = $res;
echo json_encode($result);
}

How to connect to MySQL database in PHP using mysqli extension?

I have code like this to connect my server database:
<?php
$con = mysqli_connect("", "username", "password", "databasename");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
But it displayed "Failed to connect to MySQL", what is wrong with this code? First time I am trying it in web server, whereas my localhost worked perfectly.
mysqli_connect("","username" ,"password","databasename");//Server name cannot be NULL
use loaclhost for server name(In Loacl)
<?php
$con = mysqli_connect("localhost","username" ,"password","databasename");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Or can use MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$con = mysqli_connect($servername, $username, $password);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
EDIT 01
$servername = "localhost";
$username = "root";
$password = "";
To connect to the MySQL database using mysqli you need to execute 3 lines of code. You need to enable error reporting, create instance of mysqli class and set the correct charset.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname', 3307);
$mysqli->set_charset('utf8mb4'); // always set the charset
The parameters in the mysqli constructor are all optional, but most of the time you would want to pass at least 4 of them. In the correct order they are:
MySQL Host. Most of the time it is localhost, but if you connect to a remote host it will be some other IP address. Make sure this does not contain the http protocol part. It should either be an IP address or the URL without protocol.
Username. This is the username of your MySQL user. To connect to the MySQL server you need to have a valid user with the right privileges.
Password.
Database name. This is the MySQL database name you want to connect to.
Port. Most of the time the default port is the correct one, but if you use for example wampserver with MariaDB, you might want to change it to 3307.
Socket name. Specifies the socket or named pipe that should be used.
Unfortunately the charset is not one of these parameters, so you must use a dedicated function to set this very important parameter.
Please beware never to display the connection errors manually. Doing so is completely unnecessary and it will leak your credentials.
On unrelated note: I do not recommend to use MySQLi in a new project. Please consider using PDO, which is overall a much better API for connecting to MySQL.
Why use mysqli? Just use PDO for safer mysql connection just use:
$hostname='localhost';
$username='root';
$password='';
$dbh = new PDO("mysql:host=$hostname;dbname=dbname",$username,$password);
You should specify hostname
$con = mysqli_connect("localhost","username" ,"password","databasename");
If it returns an error like
Failed to connect to MySQL: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'
Replace localhost with 127.0.0.1.
If still you cant connect check if mysql server is actually running.
service mysqld start
Then, try the one of the following following:
(if you have not set password for mysql)
mysql -u root
if you have set password already
mysql -u root -p
$localhost = "localhost";
$root = "root";
$password = "";
$con = mysql_connect($localhost,$root,$password) or die('Could not connect to database');
mysql_select_db("db_name",$con);
<?php
$servername="";
$username="";
$password="";
$db="";
$conn=mysqli_connect($servername,$username,$password,$db);
//mysql_select_db($db);
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno($conn) . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error($conn) . PHP_EOL;
exit;
}
#session_start();
$event_name = $_POST['first_name'];
$first_name = $_POST['last_name'];
$sql = "INSERT INTO customer(first_name, last_name,) VALUES ('$first_name', '$last_name')";
$conn->query($sql);
$lastInsertId = mysqli_insert_id($conn);
?>
A better method is to keep the connection and the login parameters apart.
<?php
class Database{
protected $url;
protected $user;
protected $passw;
protected $db;
protected $connection = null;
public function __construct($url,$user,$passw,$db){
$this->url = $url;
$this->user = $user;
$this->passw = $passw;
$this->db = $db;
}
public function __destruct() {
if ($this->connection != null) {
$this->closeConnection();
}
}
protected function makeConnection(){
//Make a connection
$this->connection = new mysqli($this->url,$this->user,$this->passw,$this->db);
if ($this->connection->connect_error) {
echo "FAIL:" . $this->connection->connect_error;
}
}
protected function closeConnection() {
//Close the DB connection
if ($this->connection != null) {
$this->connection->close();
$this->connection = null;
}
}
protected function cleanParameters($p) {
//prevent SQL injection
$result = $this->connection->real_escape_string($p);
return $result;
}
public function executeQuery($q, $params = null){
$this->makeConnection();
if ($params != null) {
$queryParts = preg_split("/\?/", $q);
if (count($queryParts) != count($params) + 1) {
return false;
}
$finalQuery = $queryParts[0];
for ($i = 0; $i < count($params); $i++) {
$finalQuery = $finalQuery . $this->cleanParameters($params[$i]) . $queryParts[$i + 1];
}
$q = $finalQuery;
}
$results = $this->connection->query($q);
return $results;
}
}?>
This in combination with a database factory keeps the data separated and clean.
<?php
include_once 'database/Database.php';
class DatabaseFactory {
private static $connection;
public static function getDatabase(){
if (self::$connection == null) {
$url = "URL";
$user = "LOGIN";
$passw = "PASSW";
$db = "DB NAME";
self::$connection = new Database($url, $user, $passw, $db);
}
return self::$connection;
}
}
?>
After that you can easily make your (class based) your CRUD classes (objectname+DB)
<?php
include_once "//CLASS";
include_once "//DatabaseFactory";
class CLASSDB
{
private static function getConnection(){
return DatabaseFactory::getDatabase();
}
public static function getById($Id){
$results = self::getConnection()->executeQuery("SELECT * from DB WHERE Id = '?'", array(Id));
if ($results){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
return $obj;
} else {
return false;
}
}
public static function getAll(){
$query = 'SELECT * from DB';
$results = self::getConnection()->executeQuery($query);
$resultsArray = array();
for ($i = 0; $i < $results->num_rows; $i++){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
$resultsArray[$i] = $obj;
}
return $resultsArray;
}
public static function getName($Id){
$results = self::getConnection()->executeQuery("SELECT column from DB WHERE Id = '?'", array($Id));
$row = $results->fetch_array();
return $row['column'];
}
public static function convertRowToObject($row){
return new CLASSNAME(
$row['prop'],
$row['prop'],
$row['prop'],
$row['prop']
);
}
public static function insert ($obj){
self::getConnection()->executeQuery("INSERT INTO DB VALUES (null, '?', '?', '?')",
array($obj->prop, $obj->prop, $obj->prop));
}
public static function update ($propToUpdate, $Id){
self::getConnection()->executeQuery("UPDATE User SET COLTOUPDATE = ? WHERE Id = ?",
array($propToUpdate, $Id));
}
}
And with this fine coding it's a piece of cake to select items in frontend:
include 'CLASSDB';
<php
$results = CLASSDB::getFunction();
foreach ($results as $class) {
?>
<li><?php echo $class->prop ?><li>
<php } ?>
The easiest way to connect to MySQL server using php.
$conn=new mysqli("localhost", "Username", "Password", "DbName");
if($conn->connect_error)
{
die("connection faild:".$conn->connect_error);
}
echo "Connection Successfully..!";
localhost like this (MySQLi Procedural)
<?php
$servername ="localhost";
$username="username";//username like (root)
$password="password";//your database no password. (" ")
$database="database";
$con=mysqli_connect($servername,$username,$password,$database);
if (!$con) {
die("Connection failed: " . MySQL_connect_error());
}
else{
echo "Connected successfully";
}

PDO MSSQL error query on null

I am trying to select rows from my database table, and I am getting an error stating that
Fatal error: Call to a member function query() on null in..
Our connection to the database shows successful. Below is my php code:
<?php
require_once("dbconn.php");
$db = getConnection();
$input_pid = "870104-07-5448";
$sql = "SELECT * FROM Pat WHERE PID ='$input_pid'";
$stmt = $db->query($sql);
$row = $stmt->fetchObject();
echo $row->PID;
echo $row->Name;
?>
This is the dbconn.php code:
function getConnection(){
try {
$hostname = "busctrlctr-pc";
$dbname = "DispenserSystem";
$username = "sa";
$password = "123456";
$db = new PDO ("sqlsrv:Server=$hostname;Database=$dbname", $username, $password);
echo 'We are succesful to connect the database !!'.'<br>'; // successful word
} catch (PDOException $e){
echo "connection failed problem is >> ". $e -> getMessage()."\n";
exit;
}
}
Can i know why I am getting this error. Thank you.
You never return $db in your funtion getConnection();
change the funtion to:
function getConnection(){
try {
$hostname = "busctrlctr-pc";
$dbname = "DispenserSystem";
$username = "sa";
$password = "123456";
$db = new PDO ("sqlsrv:Server=$hostname;Database=$dbname", $username, $password);
echo 'We are succesful to connect the database !!'.'<br>'; // successful word
return $db;
} catch (PDOException $e){
echo "connection failed problem is >> ". $e -> getMessage()."\n";
exit;
}
}

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

How to connect to MySQLi server

I have a login-script, but when i proceed it there com a error:
Undefined property: Users::$host in C:\wamp\www\userlogin\classes\class.database.php on line 8
There is 4 files:
<?php
session_start();
include "classes/class.users.php";
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$users->login($username, $password);
}
?>
<!DOCTYPE html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<form method="POST" action="" name="login">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
<?php
class Database
{
public function __construct()
{
$host = 'localhost';
$user = 'root';
$pass = 'password';
$name = 'usersystem';
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($mysqli->connect_errno)
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
echo $mysqli->host_info . "\n";
}
} ?>
<?php
include "class.database.php";
class Users extends Database
{
public function login($username, $password)
{
$stmt = $this->mysqli->prepare("SELECT username, password FROM users WHERE username = ? and password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) {
while($stmt->fetch()) {
$_SESSION['username'] == $username;
header("Location: dashboard.php");
}
}
else
return false;
$stmt->close();
$stmt->free_result();
}
}
$users = new users(); ?>
//dashboard
<?php echo "error"; ?>
I use localhost/index.php to run and the 3 files class.database.php and class.users.php dahsboard.php is in the directory: classes
Mybe it is a syntax-error, but i can not locate it.
I have created a database in phpmyadmin and inserted the data.
Can anybody help me?
You can't use $this for local variable, they will need to be property of the class, and you need a public one for the connection, like this:
<?php
class Database {
public $mysqli;
private $host = 'localhost';
private $user = 'root';
private $pass = 'password';
private $name = 'usersystem';
public function __construct() {
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($this->mysqli->connect_errno) {
echo "Failed to connect to MySQL: (". $this->mysqli->connect_errno . ") ";
}else{
echo $this->mysqli->host_info . "\n";
}
}
}
?>
Other thing I notice is you don't start a session before setting it.
You should also exit after redirecting
if($stmt->fetch()) {
session_start();
$_SESSION['username'] == $username;
header("Location: dashboard.php");
exit;
}
Try changing your database connection to this:
class Database
{
// Since you are calling this variable in other methods
// you need to make it available.
public $mysqli;
public function __construct()
{
$host = 'localhost';
$user = 'root';
$pass = 'password';
$name = 'usersystem';
$this->mysqli = new mysqli($host, $user, $pass, $name);
// You are mixing local with class-wide variables. Should all conform.
if ($this->mysqli->connect_errno)
echo "Failed to connect to MySQL: (".$this->mysqli->connect_errno.")".$this->mysqli->connect_error;
echo $this->mysqli->host_info."\n";
}
}
in the __construct method for Database change $user to $this->user, $host to $this->host etc..

Categories