来自另一个文件中的函数的SELECT查询的echo结果

时间:2017-09-15 11:24:45

标签: php mysql function

第一次在这里询问所以请耐心等待。如果在其他地方询问这些问题我会道歉,如果是这样,请链接答案。

我有两个文件,一个名为profile.php,另一个名为functions.php,函数文件已链接且工作正常。

我的问题是/是否可以将结果作为数组从functions.php返回并在profiles.php中使用它们以及如何执行此操作。我看起来又高又低,可能已经阅读了答案,但却没理解。

//functions.php
function playerSQL($memberid) {
if (isset($memberid)) {
    global $connect_db;
    $playerSQL = "SELECT memberID AS memberID, membershipType AS membershipType, firstName AS firstName, lastName AS lastName, DOB AS DOB, profileImage AS profileImage, shortBio AS shortBio, background AS background, battingStyle AS battingStyle, bowlingStyle AS bowlingStyle, playCricketID AS playCricketID, sponsor.sponsorImage AS personalSponsor, sponsor.sponsorURL AS personalSponsorURL FROM members LEFT JOIN sponsors AS sponsor ON (sponsor.sponsorID = members.personalSponsor) WHERE memberID = " . $memberid;
    print_r($playerSQL); // Check sql is correct
    $result = mysqli_query($connect_db,$playerSQL);

       $player = mysqli_fetch_array($result,MYSQLI_ASSOC);)
// print_f works from here and returns as expected
       printf ("%s %s\n",$player["lastName"],$player["firstName"]);
}// CLOSE IF 
} // CLOSE FUNC

这将在调用函数时正确打印姓氏和名字。

// profile.php
require_once('includes/dbfixtures_conn.php');
include_once('includes/functions.php');

if (isset($_GET['mid'])) {
    $memberid = (int)$_GET['mid'];
}

playerSQL($memberid);
echo 'The Members first name is ' . $player['firstName'];
echo 'The Members last name is ' . $player['lastName']; 

是否可以这样使用。

2 个答案:

答案 0 :(得分:1)

您需要返回数据并存储在另一个变量中,以便稍后可以访问

function playerSQL($memberid) {
    if (isset($memberid)) {
        global $connect_db;
        $playerSQL = "SELECT memberID AS memberID, membershipType AS membershipType, firstName AS firstName, lastName AS lastName, DOB AS DOB, profileImage AS profileImage, shortBio AS shortBio, background AS background, battingStyle AS battingStyle, bowlingStyle AS bowlingStyle, playCricketID AS playCricketID, sponsor.sponsorImage AS personalSponsor, sponsor.sponsorURL AS personalSponsorURL FROM members LEFT JOIN sponsors AS sponsor ON (sponsor.sponsorID = members.personalSponsor) WHERE memberID = " . $memberid;
        print_r($playerSQL); 
        $result = mysqli_query($connect_db,$playerSQL); // resolved syntax error

        $player = mysqli_fetch_array($result,MYSQLI_ASSOC);
        return $player; // returned data

    }
}
$player = playerSQL($memberid);

if ($player) { // check whether data is present or not  
    echo 'The Members first name is ' . $player['firstName'];
    echo 'The Members last name is ' . $player['lastName']; 
}
else {
    echo 'no data available';
}

此外,您在线上有语法错误:

$player = mysqli_fetch_array($result,MYSQLI_ASSOC);)

答案 1 :(得分:0)

在函数中使用return而不是printf。

ex:return $ player;

在profile.php文件中

更新函数调用并返回变量,如下所述。

$urvariable_name=playerSQL($memberid);
echo 'The Members first name is ' . $urvariable_name['firstName'];
echo 'The Members last name is ' . $urvariable_name['lastName'];