说明:
我开始使用mysqli_ *函数之前我正在使用mysql_ *现在mysqli_ *需要一个变量让我们说$con
作为enter code here
n参数传递给mysqli_ *函数,其中包含这;
$con = mysqli_connect("localhost","my_user","my_password","my_db");
现在我有一个不同的页面,我将连接到数据库,该数据库只包含在每个php页面中,以保持工作正常进行;
--------- 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";
}
?>
和其他类似的页面
----------- 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
?
答案 0 :(得分:2)
将其放入您的连接文件
<?php
//mysqli_connect("servername","mysql username","password",'database')
$con = mysqli_connect("localhost","root","",'business');
if(!$con)
{
echo "cannot connet to the server";
}
?>
在你的get product.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
}
?>
答案 1 :(得分:1)
很简单。
在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;
然后{include}包含connect.php的php脚本中将提供$con
,你可以使用它;
$result = mysqli_query($con , "any query");
或者如果你愿意,你可以使用OO,就像这样;
$result = $con->query("any query");
要在函数中使用连接,您可以使用$con
作为变量传递,或在函数内部使global $con;
全局。