在PHP函数中包装MySQL查询
我正在尝试将MySQL查询包装到php函数中 我有两个问题 1.)下面的代码可以工作,但我需要在每个函数中包含数据库连接。我可以全局调用db.php而不必添加在PHP函数中包装MySQL查询,php,mysql,function,mysqli,Php,Mysql,Function,Mysqli,我正在尝试将MySQL查询包装到php函数中 我有两个问题 1.)下面的代码可以工作,但我需要在每个函数中包含数据库连接。我可以全局调用db.php而不必添加require(“db.php”) functions.php function GetUsers($id, $active){ require("db.php"); $result = $mysqli->query("SELECT * FROM users WHERE id = '$id' and active = '$ac
require(“db.php”)代码>
functions.php
function GetUsers($id, $active){
require("db.php");
$result = $mysqli->query("SELECT * FROM users WHERE id = '$id' and active = '$active' ") or trigger_error(mysql_error());
return $result;
}
function GetAccounts($id, $active){
require("db.php");
$result = $mysqli->prepare("SELECT * FROM users WHERE id = ? and active = ? ") or trigger_error(mysql_error());
$result->bind_param('ii', $id, $active);
$result->execute();
$result->close();
return $result;
}
index.php
include("functions.php");
$id = 2;
$active = 1;
$row = GetGetUsers ($id, $active);
foreach($row as $users) {
echo '<h1>'. $users['username']. '</h1>';
echo '<p>'. $users['email']. '</p>';
}
db.php
$mysqli = new mysqli(); $mysqli->connect('localhost', 'root', 'mysql', 'function_test');
非常感谢您对我的两个问题的解答。这是我在整个项目中使用的一个课程。
试试这个
在php代码中,将这一行添加到所有其他require_once'../class/db_fn_class.php'之上代码>根据放置类文件的位置更改类文件的路径,然后将其实例化为类似以下内容$access\u db=new access\u db()代码>。下面是一个实例化后如何使用它的示例。
$data=$access\u db->get\u table\u data(“用户”、“字段1、字段2”、NULL、“id=”和active=?”、数组($id、$active));
它将返回对象数组中的数据,因此下面介绍如何提取数据
foreach($val数据){
$f1=$val[“field2”];//使用放置在get_table_数据上的每个表字段的名称作为$val的数组id。$val是user_define,因此是$data
$f2=$val[“字段2”]
}
您可以使用类(OOP)和自动加载(like)来代替。您的db.php
中的代码是什么?@MarkVincentManjac这里是db代码$mysqli=new mysqli()$mysqli->connect('localhost','root','mysql','function_test')//主机名-normaly localhost//DBusername-您的mysql用户名//DBpassword-您的mysql密码//DBname-如果($mysqli->connect\u errno){echo“无法连接到mysql:(“$mysqli->connect\u errno.”“$mysqli->connect\u error;”您的mysql数据库名称
为什么在mysqli中使用mysql\u error?您介意在代码中添加一个精选示例吗。我尝试过,但没有在php代码中添加require_once'../class/db_fn_class.php'代码>然后实例化它$access\u db=new access\u db()代码>然后您可以像这样使用它$data=$access\u db->get\u table\u data(“users”,“field1,field2”,NULL,“id=?AND active=?”,array($id,$active))
这将返回一个数据数组并提取数据foreach($val形式的数据){$f1=$val[“field2”];$f2=$val[“field2”]}