Rks Rock
Rks Rock

Reputation: 79

Using a Connection String or Variable from an Included PHP File

Description :

I have started using mysqli_* functions before that I was using mysql_* now the mysqli_* requires a variable lets say $con to be passed as aenter code heren argument to the mysqli_* function which contains this;

$con = mysqli_connect("localhost","my_user","my_password","my_db"); 

Now I have a different page at which I am connecting to the database which is just included at every php page to keep the work going like this;

--------- connect.php----------

<?php
if(!mysql_connect("localhost","root",""))
{
    echo "cannot connet to the server";
}
if(!mysql_select_db("katchup"))
{
    echo "Cannot connect to the database";
}
?>

and other pages like this

----------- get_products.php -----------

include 'connect.php';

$result = mysql_query("any query"); // this is what I have 

$result = mysqli_query($con , "any query"); // this is what I want

My question is how do I get the $con in connect.php in other pages?

Upvotes: 1

Views: 2796

Answers (2)

Aitazaz Khan
Aitazaz Khan

Reputation: 1605

put this in your connection file

<?php
//mysqli_connect("servername","mysql username","password",'database')
$con = mysqli_connect("localhost","root","",'business');

if(!$con)
{
    echo "cannot connet to the server";
}

?>

And in your get product.php etc file use mysqli like this.

<?php
 include('connection.php');
 $query=mysqli_query($con,"your query");
//for single record
 if($row=mysqli_fetch_array($query))
 {
   your data will be here
 }
//for multiple records
while($row=mysqli_fetch_array($query))
{
//your data will be fetched here
}
?>

Upvotes: 2

worldofjr
worldofjr

Reputation: 3886

Very simple.

In connect.php

$con = mysqli_connect("localhost","my_user","my_password","my_db");
if ($con->connect_errno) echo "Error - Failed to connect to database: " . $con->connect_error;

Then $con will be available in the php scripts you include connect.php in (after you include), and you can use this;

$result = mysqli_query($con , "any query");

or you can use OO instead if you want, like this;

$result = $con->query("any query");

To use the connection in functions, you can either pass as a variable, or make $con global inside the function using global $con;.

Upvotes: 1

Related Questions