使用包含的PHP文件中的连接字符串或变量


Using a Connection String or Variable from an Included PHP File

描述:

在我使用mysql_*之前,我已经开始使用mysqli_*函数了。现在,mysqli_*需要一个变量,比如$con,作为enter code heren参数传递给包含它的mysqli_*功能;

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

现在我有了一个不同的页面,我在这个页面上连接到每个php页面上都包含的数据库,以保持工作的正常进行;

---------连接.php--------

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

和其他类似的页面

-----------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

我的问题是,如何在其他页面的connect.php中获取$con

将其放入连接文件中

<?php
//mysqli_connect("servername","mysql username","password",'database')
$con = mysqli_connect("localhost","root","",'business');
if(!$con)
{
    echo "cannot connet to the server";
}
?>

在你的getproduct.php等文件中,像这样使用mysqli。

<?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
}
?>

非常简单。

在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;

然后$con将在包含connect.php的php脚本中可用(在包含之后),您可以使用它;

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

或者,如果您愿意,也可以使用OO,比如这样;

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

要在函数中使用连接,可以将其作为变量传递,也可以使用global $con;在函数内使$con全局化。