我通过一个函数传递一个sql查询,该函数返回SELECT查询的结果数。结果是mysqli_num_rows()方法的正确计数,但不将计数器变量设置为等于该数字,而是将计数器保持等于其原始值。
public function getNum($sql){
$count = 0; //set the count variable
if($result = $this->query($sql)){
//echo 'No results for criteria';
$count = mysqli_num_rows($result); //count is properly set to number
} //does not modify outside count variable
return $count; //returning 0 or whatever count was originaly set to
} //count does not change despite $count inside the if statement being changed
以下是$ this->查询的内容
public function __construct(){
$this->mysqli = new mysqli('localhost', 'root', '', 'mydb');
}
public function query($sql){
return $this->mysqli->query($sql);
}
我确定查询正在执行。问题是变量没有被改变。
答案 0 :(得分:-1)
据我了解你的问题,你想在函数内部设置变量$count
,但你应该知道函数内的变量不能在外部访问,反之亦然,这是因为variable scope in PHP。
你可以试试这个:
var $count;
function set_count($new_value) {
$this->count = $new_value;
}
function get_count() {
return $this->count;
}
public function getNum($sql){
$count = 0; //set the count variable
if($result = $this->query($sql)){
$count = mysqli_num_rows($result);
}
//set `$count`
$this->set_count($new_value);
return $count;
}
//and if you want to get the count
echo $this->get_count();