条件结果绑定

时间:2014-11-26 17:16:48

标签: php mysql

我正在将我的数据库查询转换为预准备语句。鉴于以下情况,我将如何完成结果绑定?

function getRecord($type = 1)
{
    $sql = "select field1, field2, field3";

    if ($type == 2) $sql .= ", field4, field5";

    $sql .= " from table";
    $sql .= " where field1 = 'somevalue'";

    $result = mysqli_query($conn, $sql) or die(mysqli_error());

    if ($record = mysqli_fetch_assoc($result))
    {
        $val1 = $record['field1'];
        $val2 = $record['field2'];
        $val3 = $record['field2'];

        if ($type == 2)
        {
            $val4 = $record['field4'];
            $val5 = $record['field5'];
        }
    }
}

换句话说:

function getRecord($type = 1)
{
    $stmt = mysqli_stmt_init($conn);

    $sql = "select field1, field2, field3";

    if ($type == 2) $sql .= ", field4, field5";

    $sql .= " from table";
    $sql .= " where field1 = ?";

    if (mysqli_stmt_prepare($stmt, $sql))
    {
        mysqli_stmt_bind_param($stmt, 's', 'somevalue');            
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt,  $record['field1'],
                                        $record['field2'],
                                        $record['field3']);
        if ($type == 2)
        {
            // How do I bind the rest of the results?
        }

        if (mysqli_stmt_fetch($stmt))
        {
            // Do something
        }

        mysqli_stmt_close($stmt);
    }
}

如果($ type = 2)?

,如何绑定其余结果?

1 个答案:

答案 0 :(得分:0)

很简单:

if ($type == 2) {
  mysqli_stmt_bind_result(
    $stmt,  
    $record['field1'],
    $record['field2'],
    $record['field3'],
    $record['field4'],
    $record['field5']
  );
} else {
  mysqli_stmt_bind_result(
    $stmt,  
    $record['field1'],
    $record['field2'],
    $record['field3']
  );
}

但为什么你甚至需要这个?