PHP changing fetch_field() to mysqli

后端 未结 2 1210
情歌与酒
情歌与酒 2021-01-17 07:03

My php knowledge is fairly limited but I\'ve recently needed to update a number of web pages from an older version of php 5.2 to php 7.3.

I\'ve managed to update mo

2条回答
  •  走了就别回头了
    2021-01-17 07:48

    The original function is wrong on so many levels. And there is no point in recreating its functionality.

    Basically all you are bargaining for here is just a few SQL keywords. But these keywords contribute for readability.

    For some reason you decided to outsmart several generations of programmers who are pretty happy with SQL syntax, and make unreadable gibberish

    $row = selectonerow("some, foo, bar", "baz", "id", [$uniquevalue]);
    

    instead of almost natural English

    $row = selectonerow("SELECT some, foo, bar FROM baz WHERE id=?", [$uniquevalue]);
    

    Come on. It doesn't worth.

    Make your function accept a regular SQL query, not a limited unintelligible mess.

    function selectonerow(mysqli $conn, string $sql, array $params = []): array
    {
        if ($params) {
            $stmt = $conn->prepare($sql);
            $stmt = $mysqli->prepare($sql);
            $stmt->bind_param(str_repeat("s", count($params), ...$params);
            $stmt->execute();
            $result = $stmt->get_result()
        } else {
            $result = $conn->query($sql);
        }
        return $result->fetch_assoc();
    }
    

    This function will let you to use any query. For example, need a row with max price?

    $row = selectonerow("SELECT * FROM baz ORDER BY price DESC LIMIT 1");
    

    Need a more complex condition? No problem

    $sql = "SELECT * FROM baz WHERE email=? AND activated > ?";
    $row = selectonerow($sql, [$email, $date]);
    

    and so on. Any SQL. Any condition.

提交回复
热议问题