【问题标题】:Passing string and variable to php function将字符串和变量传递给php函数
【发布时间】:2016-01-17 05:48:03
【问题描述】:

我有一个脚本来管理我的表并包含获取列表或通过 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']" ); 

【问题讨论】:

  • 你应该使用准备好的语句。

标签: php mysql function variables


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多