How to Make MySQLi Connect Function

How to make mysqli connect function?

As some users have suggested (and is the best way), return the mysqli instance

function getConnected($host,$user,$pass,$db) {

$mysqli = new mysqli($host, $user, $pass, $db);

if($mysqli->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

return $mysqli;
}

Example:

$mysqli = getConnected('localhost','user','password','database');

php function with mysqli

It should be,

<?php
function connect(){

$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
return $conn;
}

}
?>

Your query should be,

    <?php

if (isset($_POST['valider'])){

$titre=$_POST['xxx'];
$auteur=$_POST['xxx'];

$connection = connect();

if($connection != false){
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
$result=$connection->query($sql);

if($result){
echo "done";
}else{
echo "faild";
}

}

}
?>

You should take a tour/learn the basics of OOP

Mysqli connection in function PHP

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

PHP : Make other functions access the $conn variable inside my database connection function

Your Desired Solution: This should work, and you'll only make one connection.

function db () {
static $conn;
if ($conn===NULL){
$conn = mysqli_connect ("localhost", "root", "", "database");
}
return $conn;
}

function someFunction () {
$conn = db();
$result = mysqli_query ($conn, "SELECT * FROM examples);
}

If you used the function someFunction($conn), that would make your code much messier, since you wouldn't actually have universal access to $conn from anywhere.

You should go with Solution B IMO. That way, you can have simple access to it Database::$conn which will be consistent throughout your script. You could should have an initialize function (you could use a different name if you want) that will initialize Database::$conn, and you can then use that to initialize other things on the Database class later, if desired.

Solution A is terrible. I did that for a long time (globalizing things), and it was a horrible idea. I should have never done that. But I did. And I learned. It just made code get progressively sloppier and sloppier.

Solution B: Database::$conn should be public if you want to be able to access it by Database::$conn from anywhere. If it's private, then you would always need to call Database::getObject();

Solution C: You're right. That would be very impractical.

Solution B rewrite:

class Database
{
/** TRUE if static variables have been initialized. FALSE otherwise
*/
private static $init = FALSE;
/** The mysqli connection object
*/
public static $conn;
/** initializes the static class variables. Only runs initialization once.
* does not return anything.
*/
public static function initialize()
{
if (self::$init===TRUE)return;
self::$init = TRUE;
self::$conn = new mysqli("localhost", "root", "", "database");
}
}

Then... call Database::initialize() at least once before it gets used.

<?php
Database::initialize();
$result = mysqli_query (Database::$conn, "SELECT * FROM examples);
?>

EDIT

  • You can also call Database::initialize() immediately after the declaration of the class, in that PHP file. Then initializing is handled.
  • I'm now far more fond of something like Database::getDb() than accessing the $conn property directly. Then initialize can be called from the getDb() function. Basically like the Desired Solution but inside a class. The class really isn't necessary, but it can be nice if you like classes, like I do.

mysqli connection not working inside function?

The problem is with PHP variable scoping. Add this line inside of allServers() function before you refer to the $link variable for the first time:

global $link;

See more here:
http://php.net/manual/en/language.variables.scope.php

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

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


Related Topics



Leave a reply



Submit