php - Why do I need to reconnect to my database everytime when I use a custom function in the same file? -
this question has answer here:
i have normal php file , main program code above several functions below it. included connect file @ top once. of custom made functions below have queries, , these functions called in program above. there not understand: if not include connect file in function query in function won't work, if does. why need include connect file within each function?
i explain below:
this not work throws boolean mysqli_fetch , query errors though connected above in file outside function. why not work?
function queryprofileinfo($iduser){ $iduser=$_session['logged_in']['iduser']; $query ="select fnlname, username, gender, email, emailconfirmed, bio, avatar, followercount, followingcount, privatepublic profile iduser='$iduser' "; $response=mysqli_query($dbc, $query); while($row =mysqli_fetch_array($response)){ $username= $row['username']; } } /*the next example works throws following errors because connected above in file
notice: constant db_user defined in c:\xampp\htdocs\theproject\connect.php on line 8
notice: constant db_password defined in c:\xampp\htdocs\theproject\connect.php on line 9
notice: constant db_host defined in c:\xampp\htdocs\theproject\connect.php on line 10
notice: constant db_name defined in c:\xampp\htdocs\theproject\connect.php on line 11
*/
function queryprofileinfo($iduser){ include('connect.php'); $iduser=$_session['logged_in']['iduser']; $query ="select fnlname, username, gender, email, emailconfirmed, bio, avatar, followercount, followingcount, privatepublic profile iduser='$iduser' "; $response=mysqli_query($dbc, $query); while($row =mysqli_fetch_array($response)){ $username= $row['username']; } }
you need pass variable $dbc each function uses it, or declare using global variable writing global $dbc; in each function. latter solution not recommended, since later on may want have more 1 database connection.
see manual page: http://php.net/manual/en/language.variables.scope.php
Comments
Post a Comment