Sunday, 15 February 2015

php - issue with mysqli query when I use the function to run the query -



php - issue with mysqli query when I use the function to run the query -

why error when run query using mysqli within function? works fine outside of function. when running function, error states "$db" variable undefined.

<?php $username = 'username'; $password = 'password'; $db = new mysqli('localhost', 'root', 'root', 'rocketforce_blog'); $result = $db->query("select * users user_name = '$username' , password = '$password'"); $row = $result->num_rows; $cnt = count($row); echo $cnt; //======================================================================================= function user_exists($username, $password) { $result = $db->query("select * users user_name = '$username' , password = '$password'"); $row = $result->num_rows; $cnt = count($row); homecoming $cnt; } echo user_exists($username, $password); ?>

the variable $db not known in scope of function. if want known in function, either have pass $db parameter function. eg

function user_exists($db, $username, $password) { $result = $db->query("select * users user_name = '$username' , password = '$password'"); $row = $result->num_rows; $cnt = count($row); homecoming $cnt; } echo user_exists($db, $username, $password);

or import global $db variable scope of function. that:

function user_exists($username, $password) { global $db; $result = $db->query("select * users user_name = '$username' , password = '$password'"); $row = $result->num_rows; $cnt = count($row); homecoming $cnt; } echo user_exists($username, $password);

the first 1 improve one, utilize type hints, pass different connections , on...

php mysqli

No comments:

Post a Comment