我在PHP函数中的新功能是否可以在php函数中使用mysqli_fetch_assoc?
这就是我正在做的事情。
function.php
<?php
function getinfoid($conn,$idapplicant){
$sql = "SELECT * FROM applicants WHERE id_mis = '".$idapplicant."' ";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result)) {
$prefix=$row['prefix'];
$fname1=$row['fname'];
$mname1=$row['mname'];
$lname1=$row['lname'];
$gender=$row['gender'];
$addr=$row['addr'];
}
}
?>
view.php
<?php
require('connection.php');
include ('function.php');
getinfoid($conn,'2');
?>
I'm <?php echo $fname1 ?>
如何回显$ fname1?
答案 0 :(得分:1)
您的函数不返回任何内容,这些赋值变量保留在函数范围内。如果总是只有一行要提取,你可以这样做:
function getinfoid($conn,$idapplicant){
$sql = "SELECT * FROM applicants WHERE id_mis = '".$idapplicant."' ";
$result = mysqli_query($conn,$sql);
return mysqli_fetch_assoc($result);
}
然后你可以调用这个函数并回显你的变量:
$row = getinfoid($conn,'2');
?>
I'm <?php echo $row['fname'] ?>
答案 1 :(得分:0)
假设您只需打印$fname1
,以下是我建议的解决方案:
您需要从函数返回$fname1
。
<?php
function getinfoid($conn,$idapplicant){
$sql = "SELECT * FROM applicants WHERE id_mis = '".$idapplicant."' ";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
return $row['fname'];
}
require('connection.php');
include ('function.php');
$fname1 = getinfoid($conn,'2');
?>
I'm <?php echo $fname1 ?>
或者,您可以像这样从函数返回整行:
function getinfoid($conn,$idapplicant){
$sql = "SELECT * FROM applicants WHERE id_mis = '".$idapplicant."' ";
$result = mysqli_query($conn,$sql);
return mysqli_fetch_assoc($result);
}
require('connection.php');
include ('function.php');
$useDetails = getinfoid($conn,'2');
?>
I'm <?php echo $useDetails['fname'] ?>
答案 2 :(得分:0)
您可以将变量$ fname1声明为全局并访问该变量。假设只返回单个记录。
function.php
<?php
$fname1 = "";
function getinfoid($conn,$idapplicant){
global $fname1;
$sql = "SELECT * FROM applicants WHERE id_mis = '".$idapplicant."' ";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result)) {
$prefix=$row['prefix'];
$fname1=$row['fname'];
$mname1=$row['mname'];
$lname1=$row['lname'];
$gender=$row['gender'];
$addr=$row['addr'];
}
}
?>
view.php
<?php
require('connection.php');
include ('function.php');
getinfoid($conn,'2');
?>
I'm <?php echo $fname1 ?>
答案 3 :(得分:0)
<?php
function getinfoid($conn,$idapplicant){
$sql = "SELECT * FROM applicants WHERE id_mis = '".$idapplicant."' ";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
return $row
}
?>
<?php
require('connection.php');
include ('function.php');
$data = getinfoid($conn,'2');
?>
I'm <?php echo $data['firstname'] ?>