用于动态绑定问号的PHP函数/过程

时间:2015-12-15 09:24:40

标签: php pdo

我对PHP很新。我需要通过编写自定义函数来绑定PDO中的参数。

说这些是我的2平方英尺。

sample_sql_1="select f_name, age, address from table1 where l_name=? and dob >= ? and cty =?"

sample_sql_2="select * from table2 where cty=?"

我想编写一个接受有问题的sql查询的函数。绑定要绑定到问号的参数,不管我传递了多少参数。

示例:我想打电话说,

bind_params(sample_sql_1,array($name,$dob,$cty));
bind_params(sample_sql_2,array($cty));

这是我到目前为止所写的功能,只是连接到数据库

function pdo_db_query($query) {
    try {
    # MySQL with PDO_MYSQL
    $DBH = new dbconn(); // Create DB connection

    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $DBH->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
    $STH = $DBH->prepare($query);

    // Please help to create a dynamic function to bind
     bind_params(sample_sql_1,array($name,$dob,$cty));
     bind_params(sample_sql_2,array($cty));

    / Execute the query
    $STH->execute();

    # setting the fetch mode
    $STH->setFetchMode(PDO::FETCH_ASSOC);

    // Create temporary array variable
    $json_arr = array();

    while ($row = $STH->fetch()) {
        $json_arr[] = $row;
    }

    # Close the connection
    $DBH = null;

    // Return the result set as a json
    echo json_encode($json_arr);
    } catch (PDOException $e) {
    echo $e->getMessage();
    var_dump($e->getMessage());
    }
}

我需要帮助编写函数“bind_params”。任何帮助都会让我受益匪浅。

2 个答案:

答案 0 :(得分:1)

您不一定需要bind_params(),您只需将值作为数组提供给execute()

请参阅documentation

中的此示例
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));

特别针对您的情况:

// add a parameter for the values
function pdo_db_query($query, $params = array()) {
    try {
    # MySQL with PDO_MYSQL
    $DBH = new dbconn(); // Create DB connection

    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $DBH->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
    $STH = $DBH->prepare($query);

    // Execute the query with the given params
    $STH->execute($params);

    # setting the fetch mode
    $STH->setFetchMode(PDO::FETCH_ASSOC);

    // Create temporary array variable
    $json_arr = array();

    while ($row = $STH->fetch()) {
        $json_arr[] = $row;
    }

    # Close the connection
    $DBH = null;

    // Return the result set as a json
    echo json_encode($json_arr);
    } catch (PDOException $e) {
    echo $e->getMessage();
    var_dump($e->getMessage());
    }
}

要将其与LIKE查询一起使用:

$query = "SELECT * FROM table WHERE field LIKE ?";
$params = array( '%' . $searchvalue . '%' );
$result = pdo_db_query( $query, $params );

答案 1 :(得分:1)

以下代码使用&#34; Lazy&#34;绑定将数据传递到执行数组。它能够实现吗?要插入的占位符和要插入的 ANDs ,具体取决于$ columnArray中传递的列数。 我已经注释掉了一些特定于数据库的代码,以便您了解如何形成查询。您需要在 WHERE 子句之前传递一个列名数组以及sql语句的第一部分。

我添加了用于测试的示例数据和显示查询的代码以及execute()的参数。应删除这些并恢复注释代码以使用数据库进行测试。

示例结果

public partial class MyControl : Label
{

    #region fields

    private IComponentChangeService _changeService;
    private bool canResetText = false;

    #endregion

    #region properties

    protected override Size DefaultSize
    {
        get { return new Size(200, 132); }
    }

    [Browsable(false)]
    public override bool AutoSize
    {
        get { return false; }
        set { base.AutoSize = false; }
    }

    public override ISite Site
    {
        get { return base.Site; }
        set
        {
            base.Site = value;

            if (!base.DesignMode)
                return;

            this._changeService = (IComponentChangeService)base.GetService(typeof(IComponentChangeService));

            if (this._changeService != null)
                this._changeService.ComponentChanged += new ComponentChangedEventHandler(this.OnComponentChanged);
        }
    }

    #endregion

    #region constructors

    public MyControl()
    {
        base.BackColor = Color.LightCoral;
        base.BorderStyle = BorderStyle.FixedSingle;
    }

    #endregion

    #region methods

    protected override void InitLayout()
    {
        base.InitLayout();

        this.canResetText = true;
    }

    private void OnComponentChanged(object sender, ComponentChangedEventArgs ce)
    {
        if (ce.Component != null &&
            ce.Component == this &&
            ce.Member.Name == "Text" &&
            base.DesignMode &&
            this.canResetText)
        {
            ((MyControl)ce.Component).Text = string.Empty;

            this.canResetText = false;

            if (this._changeService != null)
                this._changeService.ComponentChanged -= new ComponentChangedEventHandler(this.OnComponentChanged);
        }
    }

    #endregion

}

数组([0] =&gt;汤姆[1] =&gt; 2014-11-11 [2] =&gt;伦敦)

select f_name, age, address from table1 WHERE name = ? AND dob = ? AND cty = ?