php - Getting Fatal error: Call to a member function query() on a non object error while including database details twice -
i have 3 files in program database.php ,index.php,functions.php when click next button of dashboard.php file shows these 2 errors.
notice: undefined variable: conn in c:\wamp\www\quiz\functions.php on line 144
fatal error: call member function query() on non-object in c:\wamp\www\quiz\functions.php on line 41
line number 144 $result = $conn->query($sql);
when replace include_once('database.php');
line of getquizes_answer1()
function content of database.php file works fine. there can clarify why happening this?
this how functions.php file looks like
function getquizes($quizno) { if($quizno==null) { $quizno=0; } require('database.php'); $sql = "select * quiz limit ".$quizno.",1"; $result = $conn->query($sql); while($row=$result->fetch_assoc()) { echo $row['question']; } $quizno++; $sql = "select * quiz"; $result = $conn->query($sql); $rowcount=mysqli_num_rows($result); if($quizno>=$rowcount) { $quizno=0; } return $quizno; } function getquizes_answer1($quizno) { include_once('database.php'); if($quizno!=0) { $quizno--; } $sql = "select * quiz limit ".$quizno.",1"; $result = $conn->query($sql); while($row=$result->fetch_assoc()) { echo $row['answer1']; } $sql = "select * quiz"; $result = $conn->query($sql); $rowcount=mysqli_num_rows($result); if($quizno>=$rowcount) { $quizno=0; } $conn->close(); }
this how dashboard.php file looks like
<?php $i = isset($_session['next']) ? $_session['next'] : null; if(isset($_post['next'])) { $i = getquizes($i); $_session['next'] = $i; ?> <div class="answers_block"> <table> <tr> <td><?php getquizes_answer1($i);?></td> </tr> </table> </div> <?php } ?> <form method="post" action="<?php echo $_server['php_self']; ?>"> <input name="next" value="next" type="submit" /> </form>
my database.php file looks this
<?php $servername = "localhost"; $username = "root"; $password = ""; $database="quiz_db"; // create connection $conn = new mysqli($servername, $username, $password, $database); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); }
the problem is, connection handler $conn
not available in scope of function. either use global
or pass connection handler argument function.
method(1):
function getquizes($quizno){ global $conn; // code } function getquizes_answer1($quizno){ global $conn; // code }
method(2):
function getquizes($conn, $quizno){ // code } function getquizes_answer1($conn, $quizno){ // code }
Comments
Post a Comment