How to make mysqli connect function? - php

I'm having a problem with a function that connects me to the database using mysqli. What I'm aiming to have is to just type getConnected(); where I need the connection.
This is the code:
function getConnected()
{
$host = 'localhost';
$user = 'logintest';
$pass = 'logintest';
$db = 'vibo';
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
This is the error I get when I try to use $mysqli after calling getConnected():
Notice: Undefined variable: mysqli in C:\xampp\htdocs\xampp\loginsystem\index.php on line 19

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');

You don't need to create such function. The connection to mysqli is only 3 lines of code when done properly. Definition and execution of such function would add twice as much.
Remember to always follow the three steps when opening a connection:
Enable mysqli error reporting.
Create instance of mysqli class.
Set the proper charset. Recommended one is utf8mb4
If you would like to have these 3 lines wrapped in a function you could do something like this:
function getConnected(): \mysqli {
$host = 'localhost';
$user = 'logintest';
$pass = 'logintest';
$db = 'vibo';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($host, $user, $pass, $db);
$mysqli->set_charset('utf8mb4');
// return the instance of mysqli class
return $mysqli;
}
However, hardcoding the values does not make much sense. The values should be coming either from environment variables (e.g. read using getenv() function) or from config file. For example:
function getConnected(): \mysqli {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli(getenv('DB_HOST'), getenv('DB_USER'), getenv('DB_PASS'), getenv('DB_NAME'));
$mysqli->set_charset('utf8mb4');
// return the instance of mysqli class
return $mysqli;
}

Related

Php, mysql coding error

Please tell me that where is error. I am in tention due to this,
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\kalooo1\includes\db.php:2 Stack
trace: #0 C:\xampp\htdocs\kalooo1\index.php(21): include() #1 {main}
thrown in C:\xampp\htdocs\kalooo1\includes\db.php on line 2
db.php
<?php
mysql_connect("localhost","root","");``
mysql_select_db("kalooo");
?>
index.php(21)
include("includes/db.php");
You are getting that error simple because you are using a newer version of php that does not support mysql_* functions, those functions have been depreciated and completely removed from the latest version of php.
You should use mysqli prepared functions or pdo prepared statements.
using mysqli to connect to database you will use it like this:
<?php
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "yourdatabse";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
using PDO, you would connect like this:
<?php
$host = 'localhost';
$db = 'yourdb';
$user = 'yourusername';
$pass = 'yourpassword';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
?>
The are good tutorials on the net that you can use to better your understanding, I personally enjoy this site https://phpdelusions.net/pdo You should visit it you will be a pro in no time.
use mysqli_connect("localhost","root","","db_name");
or use
store this in separate php file.
include that file like this. include 'db.php';
try this....
try this
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Global database connection inside functions

Trying to global database connection in all functions in a .php file.
sql.php:
<?php
$servername = "XXXXX";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn, "utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
save.php
$conn = require_once('../path/to/sql.php');
function save()
{
global $conn;
$sql = "INSERT INTO `content` (title, text, cat)
VALUES ('".$_POST["title"]."', '".$_POST["text"]."', '".$_POST["category"]."')";
if ($conn->query($sql) === TRUE) {
show();
}
$conn->close();
}
well i want to get sql.php with require_once and then make it global then put this in save() function.
error is:
Fatal error: Call to a member function query() on a non-object in
/homepages/3/xxxxxxxx/htdocs/xxxxxxxx/xxxxxxxx/content.php on line 37
actually i don't know this way to make it global is correct or not, so please help me to choose best way to make a global database connection inside the functions.
Try
define('DATABASE_USERNAME', 'root');
define('DATABASE_PASSWORD', 'password');
define('DATABASE_HOST', 'localhost');
define('DATABASE_DBNAME', 'db');
$conn = new mysqli(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_DBNAME);
Named constants are great for static global data.
Also you just need to do
require_once 'path/to/sql.php';
And not
$conn = require_once 'path/to/sql.php';
$conn is already being set in your require_once.

Fatal error: Call to a member function set_charset()

I am using Cpanel to develop my application. It gives the error
Fatal error: Call to a member function set_charset() on a non-object in /home/restaur /public_html/restaurant/includes/connect_database.php on line 3
when I access to "www.yyyyy.com/filename/"
And here is my connect_database script
<?php
include($_SERVER['DOCUMENT_ROOT'].'/YOUR_FOLDER/variables/variables.php');
$connect->set_charset('utf8');
?>
my close_database script
<?php
include($_SERVER['DOCUMENT_ROOT'].'/YOUR_FOLDER/variables/variables.php');
$connect->close();
?>
my variable script
<?php
// database configuration
$host ="db_host_name";
$user ="db_username";
$pass ="db_pasword";
$database = "database_name";
$connect = new mysqli($host, $user, $pass,$database) or die("Error : ".mysql_error());?>
it should be like
$host ="db_host_name";
$user ="db_username";
$pass ="db_pasword";
$database = "database_name";
// variables.php
$connect = new mysqli($host, $user, $pass, $database);
/* check connection */
if ($connect->connect_errno) {
printf("Connect failed: %s\n", $connect->connect_error);
exit();
}
Now in connect_database.php
// Make sure your included path is correct
include($_SERVER['DOCUMENT_ROOT'].'/YOUR_FOLDER/variables/variables.php');
global $connect;
$connect->set_charset('utf8');
this will help you to know more in depth global
I was having this exact issue, i was having encoding problems but adding
$connect->set_charset('utf8');
(my variable was actually $conn->set_charset('utf8');) just after
$conn = new mysqli($servername, $username, $password, $dbname);
and it worked beautifully.

mysql_* to MySQLi

I recently learned that mysql_* has been depreciated and i have a quick question on how to rewrite something.
$db = mysql_connect("localhost","root","PASSWORD");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("FormData" ,$db);
I have tried rewriting it like this...
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");
But when it posts my form i get the "Error connecting to MySQL database." error. I was able to fix it by just using this but i wanted to know how to add in the Error connecting.
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");
Any help would be great as i try to learn all of the new MySQLi stuff!
PHP website
Straight from php.net
<?php
$mysqli = new mysqli('localhost', 'fake_user', 'my_password', 'my_db');
// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
?>
Edit:
The below will also allow you to do it your way.
$mysqli = mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
Then you can:
if (!$mysqli) {
//handle the error
}
Consider PDO if possible. They are kind similar to me.
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");
should be
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");
if($mysqli->connect_error) die("Error connecting to MySQL database.");
the parameters for mysqli() are:
[ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]]
Not sure why you were trying to use the $db variable to set the port for the connection and then checking if the port variable is true...
For future reference the best place to look first, would be the docs
EDIT
As #Touch pointed out, you must check if error exists and not just that object exists. Edited code to reflect this.
Using mysqli:
define('DB_HOST', 'localhost');
define('DB_NAME', 'some_database_name');
define('DB_USER', 'some_user');
define('DB_PASS', 'some_password');
$Connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$Connection->connect_errno)
{
//do your prepared stuffs
}
else
{
die("Database Connection error:".$Connection->connect_error);
}
or using PDO
try
{
$PDOConnection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
$PDOConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//do your prepared stuffs
$PDOConnection = null;
}
catch(PDOException $e)
{
die('ERROR: ' . $e->getMessage());
}
I wrote a class called better_mysqli that extends mysqli making it easier to use.
The following example shows the answer to your question and also shows basic usage of the better_mysqli class. You can view a detailed example with lots of comments here: detailed usage of better_mysqli
<?php
include_once('better_mysqli.php'); // can be obtained from: http://pastebin.com/ATyzLUfK
// THIS NEXT PART ANSWERS YOUR QUESTION
// THIS NEXT PART ANSWERS YOUR QUESTION
// THIS NEXT PART ANSWERS YOUR QUESTION
// THE ONLY DIFFERENCE IN THE CONNECTION WHEN USING better_mysqli AND mysqli
// is $mysqli = new better_mysqli(...) and $mysqli = new mysqli(...)
// == Instantiate the mysqli database object (aka open the database) ==
$mysqli = new better_mysqli('your_server', 'your_user', 'your_pass', 'your_db_name');
if (mysqli_connect_errno()) {
error_log(sprintf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()));
exit;
}
// == select example ==
unless( $sth = $mysqli->select('select * from table1 where col1=? and col2=?', $row, array('col1_placeholder_value', 'col2_placeholder_value'), $debug_level=0, $verbose_debug_output)){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
while($sth->fetch()){
echo $row['col1'] .', '. $row['col2'] .', and '. $row['col_etc'] .' are accessed like that.<br>';
}
// == insert example ==
$statement = "insert into table1 (col1, col2, date_col, col_etc) values (?, ?, NOW(), ?)";
unless( $mysqli->insert($statement, array('col1_insert_value', 'col2_insert_value', 'col_etc_value'), $debug_level=0, $verbose_debug_output, $id_of_new_record) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// == update example ==
unless($mysqli->update("update table1 set col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// == delete example ==
unless( $mysqli->delete("delete from table1 where col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// in all cases statements are prepared just once and cached so if you reuse any statement the already prepared statement handle is automatically used
?>

PHP and MYSQLI Error, Call to a member function query() on a non-object [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I'm getting the Call to a member function query() on a non-object when I try to call my function.
My code looks like this:
function add_profile() {
$hostname = "localhost";
$dbusername = "username";
$dbname = "dbname";
$dbpassword = "password";
$link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$sql = "INSERT INTO payment_profiles(id, client_id) VALUES ( '','$profile_id')";
$result = $mysqli->query($sql);
if (!result)
{
echo 'Error: ', $mysqli->error;
}
}
add_profile();
It says my error is on the line: $result = $mysqli->query($sql);
I'm assuming I'm not calling something properly. Thanks in advance for any help
In your code you're mixing both procedural and object-oriented code. Choose either one or the other. Here's how you would solve the problem the procedural way.
$result = mysqli_query($link, $sql, MYSQLI_USE_RESULT)
I'm getting the Call to a member function query() on a non-object when
I try to call my function.
That's because the $mysqli object is not declared anywhere (or is it)? Before you can use $mysqli you should first create an instance of mysqli and assign it to your object.
$mysqli = new mysqli("localhost", "my_user", "my_password", "database");
Only then you may call the methods of the mysqli class like $mysqli->query();
The error you made depends probably on two misconceptions:
1) you pasted half of your code from the procedural-style part of the mysqli manual and half from the oop part
2) you assume $mysqli is a global object instantiated with $mysqli_connect();. It is not. You should invoke the constructor with the new keyword if you'd like to use it as an object.
$link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
/////
$result = $mysqli->query($sql);
///////

Categories