Functions, SQL Connects and Global Variable - php

Is there anything wrong with connecting and closing to a database by calling the function below with the mysql_query and mysql_fetch_array commands between the two
<?php
function dbconnect()
{
$sql = "localhost";
$username = "------";
$password = "-----";
$connection = mysql_connect($sql, $username, $password) or
die("unwable to cct");
$databse = mysql_select_db("-------", $connection);
global $connection;
}
function close()
{
global $connection;
mysql_close($connection);
}
dbconnect();
$query = "Some SQL Statement";
$data = mysql_query($query, $connection); - L1
while (mysql_fetch_assoc($data))
{
//echo something
}
close();
?>
At present, I am getting an error saying that $connection at L1 needs to be a resource but is a BOOL. If I give a die statement there, the same is triggered. I have no idea what is wrong. Please spot any errors you can. I have to take a sabbatical from coding and I am back after a while.
Thanks & regards

You must use the global keyword before assigning the $connection variable. Otherwise, you declare a local $connection inside the function and then call a reference to the yet non-existent global $connection. In the other functions, that non-existent global is used.
function dbconnect()
{
// Global first to be sure the subsequent $connection is the global
// rather than a new one local to this function
global $connection;
$sql = "localhost";
$username = "------";
$password = "-----";
// Now this modifies the global $connection
$connection = mysql_connect($sql, $username, $password) or die("unwable to cct");
$databse = mysql_select_db("-------", $connection);
}
More readable would be to use the $GLOBALS array:
function dbconnect()
{
$sql = "localhost";
$username = "------";
$password = "-----";
// Using the $GLOBALS superglobal array
$GLOBALS['connection'] = mysql_connect($sql, $username, $password) or die("unwable to cct");
$databse = mysql_select_db("-------", $GLOBALS['connection']);
}
Best of all would be to return $connection from dbconnect() and use that value in other functions:
function dbconnect()
{
$sql = "localhost";
$username = "------";
$password = "-----";
$connection = mysql_connect($sql, $username, $password) or
die("unwable to cct");
$databse = mysql_select_db("-------", $connection);
// Return from the function
return $connection;
}
// call as
$connection = dbconnect();
// and define your other functions to accept $connection as a parameter

declare global $connection before calling mysql_connect()
function dbconnect()
{
global $connection;
$sql = "localhost";
$username = "------";
$password = "-----";
$connection = mysql_connect($sql, $username, $password) or
die("unwable to cct");
$databse = mysql_select_db("-------", $connection);
}

Not too sure but try closing it by using
mysql_Close($Connection);
everything else looks good

Just put the global $connection; line in the beginning of the function instead and it should work. Using global keyword at the end of the function implies that you want to use the global variable $connection. But the thing you will be doing now is, assingning global variable $connection "the actual connection resourceID".

Related

linking my database to my server on xampp for the first time [duplicate]

I'm working on streamlining a bit our db helpers and utilities and I see that each of our functions such as for example findAllUsers(){....} or findCustomerById($id) {...} have their own connection details for example :
function findAllUsers() {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
die("Connection to DB failed: " . $con->connect_error);
} else {
sql = "SELECT * FROM customers..."
.....
.....
}
}
and so on for each helper/function. SO I thought about using a function that returns the connection object such as :
function dbConnection ($env = null) {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
return false;
} else {
return $con;
}
}
Then I could just do
function findAllUsers() {
$con = dbConnection();
if ($con === false) {
echo "db connection error";
} else {
$sql = "SELECT ....
...
}
Is there any advantages at using a function like this compared to a Class system such as $con = new dbConnection() ?
You should open the connection only once. Once you realize that you only need to open the connection once, your function dbConnection becomes useless. You can instantiate the mysqli class at the start of your script and then pass it as an argument to all your functions/classes.
The connection is always the same three lines:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli($srv, $usr, $pwd, $db, $port);
$con->set_charset('utf8mb4');
Then simply pass it as an argument and do not perform any more checks with if statements.
function findAllUsers(\mysqli $con) {
$sql = "SELECT ....";
$stmt = $con->prepare($sql);
/* ... */
}
It looks like your code was some sort of spaghetti code. I would therefore strongly recommend to rewrite it and use OOP with PSR-4.

Best practices / most practical ways to implement mysqli connections

I'm working on streamlining a bit our db helpers and utilities and I see that each of our functions such as for example findAllUsers(){....} or findCustomerById($id) {...} have their own connection details for example :
function findAllUsers() {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
die("Connection to DB failed: " . $con->connect_error);
} else {
sql = "SELECT * FROM customers..."
.....
.....
}
}
and so on for each helper/function. SO I thought about using a function that returns the connection object such as :
function dbConnection ($env = null) {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
return false;
} else {
return $con;
}
}
Then I could just do
function findAllUsers() {
$con = dbConnection();
if ($con === false) {
echo "db connection error";
} else {
$sql = "SELECT ....
...
}
Is there any advantages at using a function like this compared to a Class system such as $con = new dbConnection() ?
You should open the connection only once. Once you realize that you only need to open the connection once, your function dbConnection becomes useless. You can instantiate the mysqli class at the start of your script and then pass it as an argument to all your functions/classes.
The connection is always the same three lines:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli($srv, $usr, $pwd, $db, $port);
$con->set_charset('utf8mb4');
Then simply pass it as an argument and do not perform any more checks with if statements.
function findAllUsers(\mysqli $con) {
$sql = "SELECT ....";
$stmt = $con->prepare($sql);
/* ... */
}
It looks like your code was some sort of spaghetti code. I would therefore strongly recommend to rewrite it and use OOP with PSR-4.

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

ADODB mySQLi Connection

I am using mysql with adodb and what changes i have to do if i want to shift to mysqli.
this is my connection file and i need to make changes in this file only or i have to update all my query files.
include_once("adodblib/adodb.inc.php");
class ADb {
function ADb()
{
global $dbserver;
global $dbuser;
global $dbpass;
global $database;
$dbuser = "root";
$dbpass = "asdasdasd";
$dbserver = "localhost";
$database = "DB_NAME";
$this->conn1 = &ADONewConnection('mysql');
$this->conn1->PConnect($dbserver, $dbuser, $dbpass, $database);
}
function query($sql){
$Result = $this->conn1->Execute($sql);
return $Result;
}
function ExecuteQuery($sql){
$Result = $this->conn1->Execute($sql);
return $Result;
}
function ExecuteQuery1($sql){
return $this->query($sql);
}
function Execute($sql){
return $this->query($sql);
}
}
You just need to change the parameter of ADONewConnection to mysqli.
Change the line
$this->conn1 = &ADONewConnection('mysql');
to
$this->conn1 = &ADONewConnection('mysqli');

"Undefined Variable" notice

Im new to php so im sure this is an easy one. Im getting this error
Notice: Undefined variable: conn in C:\Dev\Webserver\Apache2.2\htdocs\EclipsePHP\thecock\php\db.php on line 23
for this code
<?php
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
$conn = new mysqli($host, $username, $password, $database);
if (! $conn) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo("all ok!");
}
function getContent($id) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) { # line 23
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
?>
How do I fix the notice?
Change your function to:
function getContent($id, $conn) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
You don't declare the "original" $conn in the scope of the function. Inside the function you only have access to variables declared inside the function or provided via parameters.
Another way would be to declare the variable as global in your function:
function getContent($id) {
global $conn;
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
But you should only do this, if there is no other way. Globals make it hard to debug and maintain the code.
See also Variable scope and why global variables are bad.
Edit:
Yes e.g. you can have a DB class:
class DB {
private static $conn = null;
public static function getConnection() {
if (is_null(DB::$conn)) {
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
DB::$conn = new mysqli($host, $username, $password, $database);
}
return DB::$conn;
}
}
Of course this is not the best implementation ;) But it should give you the right idea. Then you can get the the connection:
DB::getConnection()
conn is a global variable. To access it within a function:
function getContent($id) {
global $conn;
...
}
Otherwise the function can't see it.

Categories