从可用于函数的 MySQL 数据库中获取数据


Getting data from MySQL database thats usable for functions

我创建了一个能够在屏幕上打印信息的函数。但是,我无法使用此功能将此数据存储在$variable中。我也无法将其调用到 if 比较器中(它直接在屏幕上打印)。

下面是我如何存储数据的示例:

$usertype = getusertype();
or using it in an if statement:
if(getusertype==1){
something}

这是我的函数

function getusertype() {
    global $con;
    /* getting the needed data for the query */
    $myusername = $_SESSION['myusername'];
    /* defining the query */
    $sql3 = "SELECT usertype FROM person WHERE person_id='$myusername'";
    if ($result = mysqli_query($con,$sql3)) {
        /* fetch object array */
         while ($row = $result->fetch_row()) {
            printf ("%s  ", $row[0]);
        }
        /* free result set */
        $result->close();
    }
}

您没有从函数返回值。

相反,您正在打印它,因此,它不起作用。

而不是

printf ("%s  ", $row[0]);

做:

return $row[0];

使用 If 代替 while 和 return $row[0]; 代替 printf