MYSQLI准备的语句具有未知数量的变量

时间:2019-02-19 06:13:27

标签: mysqli prepared-statement bindparam

用户提交的表单中,他们可能会或可能不会选择所有可用的搜索选项。

如果发布了所有搜索选项,以下代码将起作用:

$stmt = $connection->prepare("
SELECT
COUNT(id) AS totalCount,
ROUND(AVG(pushups)) AS pushups,
ROUND(AVG(crunches)) AS crunches,
ROUND(AVG(age)) AS age,
ROUND(AVG(weight)) AS weight,
ROUND(AVG(height)) AS height,
ROUND(AVG(treadtimemin)) AS treadtimemin,
ROUND(AVG(treadhr)) AS treadhr,
ROUND(AVG(treadtimesec)) AS treadtimesec,
ROUND(AVG(age)) AS age
FROM
`Fittest`
WHERE
prepost = 'pre' AND semester = ? AND course = ? AND section = ? AND 
YEAR(submitted) = ?
");  

    $stmt->bind_param( "ssss", $semester,$CourseNumber, 
$SectionNumber, $year);
    $stmt->execute();

这是我正在使用的代码,用于处理数量未知的变量,但我对类的理解不够,无法正确地将其组合在一起。我知道我很近,但是没有雪茄。

$bindParam = new BindParam(); 
$qArray = array(); 

$query = 'COUNT(id) AS totalCount,
ROUND(AVG(pushups)) AS pushups,
ROUND(AVG(crunches)) AS crunches,
ROUND(AVG(age)) AS age,
ROUND(AVG(weight)) AS weight,
ROUND(AVG(height)) AS height,
ROUND(AVG(treadtimemin)) AS treadtimemin,
ROUND(AVG(treadhr)) AS treadhr,
ROUND(AVG(treadtimesec)) AS treadtimesec,
ROUND(AVG(age)) AS age
FROM
`Fittest` WHERE  prepost = pre  AND   '; 
if($_POST['SectionNumber']){ 
$qArray[] = 'SectionNumber = ?'; 
$bindParam->add('s', $_POST['SectionNumber']); 
} 
if($_POST[ 'semester' ]){ 
$qArray[] = 'semester = ?'; 
$bindParam->add('s', $_POST[ 'semester' ]); 
} 
if($_POST[ 'CourseNumber' ]){ 
$qArray[] = 'CourseNumber = ?'; 
$bindParam->add('s', $_POST[ 'CourseNumber' ]); 
} 
if($_POST[ 'year' ]){ 
$qArray[] = 'YEAR(submitted) = ?'; 
$bindParam->add('s', $_POST[ 'year' ]); 
} 

$query .= implode(' AND ', $qArray); 

call_user_func_array( array($stm, 'bind_param'), $bindParam->get()); 
$stmt->execute();

//echo $query . '<br/>'; 
//var_dump($bindParam->get()); 

class BindParam{ 
private $values = array(), $types = ''; 

public function add( $type, &$value ){ 
    $this->values[] = $value; 
    $this->types .= $type; 
} 

public function get(){ 
    return array_merge(array($this->types), $this->values); 
} 
} 

这是我回显查询并执行var_dump时的输出:

COUNT(id) AS totalCount, ROUND(AVG(pushups)) AS pushups, 
ROUND(AVG(crunches)) AS crunches, ROUND(AVG(age)) AS age, 
ROUND(AVG(weight)) AS weight, ROUND(AVG(height)) AS height, 
ROUND(AVG(treadtimemin)) AS treadtimemin, ROUND(AVG(treadhr)) AS treadhr, 
ROUND(AVG(treadtimesec)) AS treadtimesec, ROUND(AVG(age)) AS age FROM 
`Fittest` WHERE prepost = pre AND SectionNumber = ? AND semester = ? AND 
CourseNumber = ? AND YEAR(submitted) = ?
array(5) { [0]=> string(4) "ssss" [1]=> string(4) "5015" [2]=> string(4) 
"Fall" [3]=> string(9) "PHED 1164" [4]=> string(4) "2018" }

它看起来很正确,但是我不知道如何集成它。例如,当我集成连接部分时,我的最后一段代码是什么样的: $ stmt = $ connection-> prepare(“ ....

我试图找到有关此的教程,但找不到完整的示例。

预先感谢

蒂姆

0 个答案:

没有答案