Warning: Missing argument 1 for getConnection() - php

function getConnection($con)
{
$con = mysqli_connect('localhost', 'root', '','test') or die(mysqli_connect_error());
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "ID FROM Student";
$result = mysqli_query($con, $query);
}
Is the error caused due to $con used in the function ? Any help please.

It means you're omitting to pass an argument to the function when invoking it, i.e.
getConnection(); //<-- no arg passed

First of all, why do you use $kon as parameter and override it then?
But i would define $con to be null if no parameter is passed and if you need it.
like
function getConnection($con = null){[..]}
If possible I would remove the parameter.

If you want to create the db-connection ($con) inside your function, remove the parameter from the function declaration:
function getConnection() {
...

Related

PHP: Can not use global variable in function to connect mysqli

I've been searching stack to get my answer, but nothing fixed my problem. So here's my shot:
$conn = mysqli_connect('localhost', 'username', 'pass', 'db');
function GetArticle() {
global $conn;
$sql = "sql query";
$getresult = mysqli_query($conn, $sql);
..
}
This doesn't seem to work. If I put $conn inside the function, it works fine.
Any ideas?
I don't know your exact situation, but in general I do not see the benefit to using $conn as global. Your function depends on a mysqli connection in order to work, so just make the connection a function parameter.
function GetArticle($conn) {
$sql = "sql query";
$getresult = mysqli_query($conn, $sql);
..
}
Then after you have established your connection, you can call the function with your connection object as its argument.
$conn = mysqli_connect('localhost', 'username', 'pass', 'db');
$article = GetArticle($conn);
I think this is a more manageable approach than trying to keep track of whether $conn is available in global scope before calling the function.

problem with "real_escape_string"

i am having some troubles my the "real_escape_string" and i need some help
login.php
<?php include('Connections/local.php'); ?>
<?php
function GetSQLValueString($sql) {
$sql = $mysqli->real_escape_string($sql);
return $sql;
}
?>
local.php
<?php
$hostname_local = "xxx";
$database_local = "xxx";
$username_local = "xxx";
$password_local = "xxx";
$mysqli = new mysqli($hostname_local, $username_local, $password_local, $database_local);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
the error is
Undefined variable: mysqli
i've tried some things ( like moving the content of the local.php inside the login.php ) but nothing works
You can't access $mysqli inside your function.
If you want to, add global $mysqli; in your function to make it accessible. Alternatively, you could pass the $mysqli as a parameter.
Why not just use the function call directly.
My suggestion, just create a simpler (and easier to read function) called "esc" and use that anytime you need to escape anything sql related.
function esc($string, $mysqli = false) {
if (!$mysqli) global $mysqli;
return mysqli_real_escape_string($mysqli,$string);
}
And then just use this by doing the following:
$sql = esc($string); //if $mysqli is already set globally, and thus will be inherited by the function
OR
$sql = esc($string,$mysqli); //if $mysqli is to be passed into each func call

How do I make $con available as a parameter of $Query?

I can get by with editing procedural PHP (just), but OOP is a different thing. So I'm not that experienced with what I'm doing here, but I'm trying my best...
I have a file called Quote.object.php containing the following:
$Query = new DbQuery( "INSERT", "quotes", $array );
$this->id = mysqli_insert_id();
mysqli_insert_id needs to be fed a DB connection parameter, but I'm not sure how to do it. There is another file called Mysql.handler.php containing the database connection variable - is there a way that I can make $con available as a parameter of $Query above?
class DbQuery extends DbConnectionInfo{
// file: includes/classes/MysqlQuery.php
// contains functions needed to perform queries on mysql database and functions for necessary data processing for application
// SELECT = new DbQuery("select", table,cols[$value] ,where[$col=$value],order[$value],limit);
// INSERT = new DbQuery("insert", table, data[$col=$value]);
// UPDATE = new DbQuery("update", table, data[$col=$value],where[$col=$value],limit);
// set testing as true for SQL reports in page
var $results;
var $sql;
function __construct($mode,$table = '',$var1 = '',$var2 = '',$var3 = '',$var4='')
//connects to database according to info in DbConnectInfo, runs query, closes connection
{
$temp = '';
$con = mysqli_connect($this->host, $this->user, $this->pass) or die ('There was a problem connecting to the database ' . (ENVIRONMENT == 'Development' ? mysqli_error() . "$this->user, $this->pass, $this->host" : ''));
mysqli_select_db($con,$this->db) or die ('There was a problem connecting to the database' . (ENVIRONMENT == 'Development' ? mysqli_error() : ''));
I'm trying to get $con from DbQuery so I can put it into mysqli_insert_id(). I assume that's what I need? Is there a way to get $con from DbQuery and put into mysqli_insert_id()? Or do you need more information to know this?
NB I've tried to be concise in trying to show just relevant information, apologies if I've missed other helpful info.
You're defining an object, so make $con a class variable, e.g.
function __construct() {
$this->con = mysqli_connect(...);
^^^^^^^----store in object
}
function foo() {
$result = mysqli_query($sql, $this->con);
^^^^^^^^---retrieve from object
}

Get a database connection error in a class

I didn't realize there was an OO way to use mysqli, so I built a class called DB. During __construct it takes the hostname, username, password, and database name. Given the following code:
$myDB = new DB("localhost", "user", "password", "database");
$myDBConnect = $myDB->connect();
if(!$myDBConnect) {
echo "<strong>The following error has occurred: " . $myDB->getError();
}
The variable obviously contains FALSE because this if statement is currently returning TRUE. Here is the method from the DB class:
public function connect() {
// Create connection
$this->dbConnx = mysqli_connect($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if(mysqli_connect_errno($this->dbConnx)) {
$this->dbError = mysqli_error($this->dbConnx);
return false;
}
}
I'm not getting any error detail. I tried adding or die(mysqli_error()); in the connect method, but it always just outputs the text from the file that $myDB is instantiated in. I also tried variations on the error reporting code, including having no argument in mysqli_connect_errno() and using $this->dbError = mysqli_connect_error() with and without the connection argument.
Is this needlessly complicating the OO way to use mysqli? or am I missing something simple that will allow me to move on using the code I've already got?
Thanks in advance for your time.
if is not variable
if(!$myDBConnect) {
^--remove variable sign here
EDIT:
your connection should be
$myDB = new mysqli("localhost", "user", "password", "database");
Maybe you forgot the return true statement in the "connect" method?
Also you should use PDO.
Your connect() function is returning false on failure and nothing on success, so it will always fail the if. Try adding return true; at the end of that function.

PHP Function Accessing Database Connection

How do I allow a function to access a database connection without using GLOBAL?
config.php
DEFINE ('DB_HOSTNAME', 'hostname');
DEFINE ('DB_DATABASE', 'database');
DEFINE ('DB_USERNAME', 'username');
DEFINE ('DB_PASSWORD', 'password');
$dbc = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(!$dbc) die("Unable to connect to MySQL: " . mysqli_error($dbc));
functions.php
function something()
{
$info = mysqli_query($dbc, "SELECT info FROM text") or die("Error: ".mysqli_error($dbc));
}
The above gives me the following error:
mysqli_query() expects parameter 1 to be mysqli, null given in
Use function parameters
function something ($dbc) {
// your db code here
}
function arguments
Either pass the database handle to your function, as #KingCrunch and others have said, or call a function that returns the handle:
In config.php:
function get_dbc() {
$dbc = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(!$dbc) die("Unable to connect to MySQL: " . mysqli_error($dbc));
return $dbc;
}
In functions.php:
require_once('config.php');
function something()
{
$dbc = get_dbc();
$info = mysqli_query($dbc, "SELECT info FROM text") or die("Error: ".mysqli_error($dbc));
}
You may wish to look at The mysqli Extension and Persistent Connections for details on how you can prevent the connection from being re-established on each call to get_dbc(). There are alternative approaches to this, such as creating a singleton class for your database connection.
There are two ways one is by passing arguments and the other by using function closure like #Ondrej said. But I wonder both of these require you to modify the code if that is the case, then I would suggest you to use global keyword.
You can use global keyword to get the scope of variable $dbc
Try this..
function something()
{
global $dbc;
$info = mysqli_query($dbc, "SELECT info FROM text") or die("Error: ".mysqli_error($dbc));
}
(OR)
Try this...
function something()
{
$dbc = func_get_arg(0);
$info = mysqli_query($dbc, "SELECT info FROM text") or die("Error: ".mysqli_error($dbc));
}
& do this ....
$query = something($dbc);
There are more ways. You could use classic procedural style:
function something($dbc)
or anonymous function (if you use PHP5.3):
$fn = function() using ($dbc)
its so simple just pass your $conn variable into another calling function(instead of making new connection) like
yourpage.php
$conn = new mysqli($servername, $username, $password, $dbname);
someFunction ($conn)//you can add other parameters if you like
function someFunction ($conn) {
$result = mysqli_query ($conn, "SELECT * FROM examples);
}
Note:This is not good practice to always make new connection for database access.so always make connection once and use it every where.(but if your requirement different and require multiples connections then you can make multiples connections)

Categories