How to use mysqli query using a separate connectio

2020-08-09 04:24发布

I am having a problem with mysqli. We know mysqli needs two parameter to execute. One is the "query" and other is the "php connection line code". Now, I want to make a separate connection file and want to write include "that separate connection file" in each file so that I do not need to write the connection code in each file or if I change the connection file, all files get the update.

But in that case, I will not have the connection line code in every file so I will have only one parameter to execute mysqli query so I will not be able to execute it. Any suggestions? I ignored code because Stack-overflow.com has too many restrictions on it.

标签: php mysql
2条回答
冷血范
2楼-- · 2020-08-09 04:49

IN simplified psuedo-code:

connection.php:

<?php

$con = mysql_connect(...) or die(mysql_error());

any other script:

<?php

require('connection.php');

$stmt = mysql_query("SELECT ...", $con);

require() and include() act is if you'd literally cut & paste the included file into the file doing the including. There's no functional difference between

<?php
    $con = mysql_connect();
    mysql_query($sql, $con);

and

<?php
   include('file_that_connects_to_mysql.php');
   mysql_query($sql, $con);

As long as the file exists and can be included/required, it'll be as if you had its contents stuffed directly into the parent file.

查看更多
Root(大扎)
3楼-- · 2020-08-09 05:09

Mark B did answer the question although his answer was for mysql -which is deprecated and shouldn't be used

by the way it is mysqli and not mysquli

Procedural style
let's say the connection file was:

conn.php

<?php
    $mysqli=mysqli_connect($host,$user,$password,$db);
    if($mysqli_connect_error())
        die('Connect Error');
?>

and the other file:

other_file.php

<?php
    require 'conn.php';
    $res=mysqli_query($mysqli,$query);    #yes $mysqli is available here although it is in another file
?>

OOP style

conn.php

<?php
    $mysqli=new mysqli($host,$user,$password,$db);
    if($mysqli->connect_error)
        die('Connect Error');
?>

and the other file:

other_file.php

<?php
    require 'conn.php';
    $res=$mysqli->query($query);
?>

Here I used the normal mysqli::query and mysqli_query (which are the same), but I would also recommend using prepared statements rather than mysqli::query because it is safer for SQL injection.

查看更多
登录 后发表回答