将字符串和变量传递给php函数

时间:2015-10-19 00:43:43

标签: php mysql function variables

我有一个脚本来管理我的表并包含获取列表或通过id获取某些数据的函数。 现在我的一个功能看起来像这个

//Returns a Series Object matching the given series id
public static function getById( $WHERE, $id ){
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "SELECT * FROM series $WHERE $id";
    $st = $conn->prepare( $sql );
    $st->execute();
    $row = $st->fetch();
    $conn = null;
    if( $row ) return new Series( $row );
}

但我希望它像这样

//Returns a Series Object matching the given series id
public static function getById( $statement ){
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "SELECT * FROM series $statement";
    $st = $conn->prepare( $sql );
    $st->execute();
    $row = $st->fetch();
    $conn = null;
    if( $row ) return new Series( $row );
}

所以不必这样做

$series = Series::getById( ( string ) "WHERE id=", (int) $_POST['seriesId'] ); 

我可以这样做

$series = Series::getById( ( string ) "WHERE id=$_POST['seriesId']" ); 

1 个答案:

答案 0 :(得分:1)

将该值传递给函数的正确方法如下:

$series = Series::getById("WHERE id=".$_POST['seriesId']);