PHP changing fetch_field() to mysqli

后端 未结 2 1212
情歌与酒
情歌与酒 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:58

    I would recommend to get rid of this function or replace it with a function suggested by YCS.

    If you really want to continue using this function consider the following fixes. You made the code inside extremely complicated and you forgot to pass the connection variable into the function. I have simplified it:

    // open the DB connection properly inside Connections/connAsh.php
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $connAsh = new mysqli('host', 'user', 'pass', $database_connAsh);
    $connAsh->set_charset('utf8mb4');
    
    // your function:
    function selectonerow(mysqli $connAsh, $fieldsarray, $table, $uniquefield, $uniquevalue): array
    {
        //The required fields can be passed as an array with the field names or as a comma separated value string
        if (is_array($fieldsarray)) {
            $fields = implode(", ", $fieldsarray);
        } else {
            $fields = $fieldsarray;
        }
    
        //performs the query
        $stmt = $connAsh->prepare("SELECT $fields FROM $table WHERE $uniquefield = ?");
        $stmt->bind_param('s', $uniquevalue);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc();
    }
    

    This is your function, but with a lot of noise removed. I added $connAsh in the function's signature, so you must pass it in every time you call this function. The function will always return an array; if no records are fetched the array will be empty. This is the recommended way. Also remember to always use prepared statements!

提交回复
热议问题