如何使用单独的connection.php文件使用mysqli查询? [英] How to use mysqli query using a separate connection.php file?

查看:76
本文介绍了如何使用单独的connection.php文件使用mysqli查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用mysqli时遇到问题.我们知道mysqli需要两个参数来执行.一个是查询",另一个是"php连接行代码".现在,我想制作一个单独的连接文件,并希望在每个文件中写入该单独的连接文件",这样我就不需要在每个文件中编写连接代码,或者如果我更改连接文件,则所有文件都将更新.

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.

但是在那种情况下,我不会在每个文件中都有连接行代码,所以我只有一个参数可以执行mysqli查询,所以我将无法执行它.有什么建议?我忽略了代码,因为Stack-overflow.com对它的限制太多.

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.

推荐答案

Mark B确实回答了这个问题,尽管他的答案是针对mysql的-已弃用且不应使用

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

顺便说一句,它是mysqli而不是mysquli

by the way it is mysqli and not mysquli

程序样式
假设连接文件为:

Procedural style
let's say the connection file was:

conn.php

conn.php

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

和其他文件:

other_file.php

other_file.php

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

OOP风格

conn.php

conn.php

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

和其他文件:

other_file.php

other_file.php

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

在这里,我使用了普通的mysqli::querymysqli_query(它们是相同的),但是 我也建议使用预备语句而不是mysqli::query ,因为它对于SQL注入更安全.

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.

这篇关于如何使用单独的connection.php文件使用mysqli查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆