PHP changing fetch_field() to mysqli

早过忘川 提交于 2020-05-23 11:58:12

问题


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 most of the mysql references to mysqli etc and get things working correctly, however there is one page that makes use of a calendar and I'm really struggling with this section and the fetch_field part in particular as any examples I have found don't seem to be in a similar format.

The code I need to update is below;

require_once('Connections/connAsh.php');
mysql_select_db($database_connAsh, $connAsh);

function selectonerow($fieldsarray, $table, $uniquefield, $uniquevalue)
{
    //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
    $result = mysql_query("SELECT $fields FROM $table WHERE $uniquefield = '$uniquevalue'") or die("Could not perform select query - " . mysql_error());

    $num_rows = mysql_num_rows($result);

    //if query result is empty, returns NULL, otherwise, returns an array containing the selected fields and their values
    if ($num_rows == NULL) {
        return NULL;
    } else {
        $queryresult = array();
        $num_fields = mysql_num_fields($result);
        $i = 0;
        while ($i < $num_fields) {
            $currfield = mysql_fetch_field($result, $i);
            $queryresult[$currfield->name] = mysql_result($result, 0, $currfield->name);
            $i++;
        }
        return $queryresult;
    }
}

My attempts at editing this are;

require_once('../Connections/connAsh.php')
$connAsh->select_db($database_connAsh);
function selectonerow($fieldsarray, $table, $uniquefield, $uniquevalue)
{
    //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
    $result = $connAsh->query("SELECT $fields FROM $table WHERE $uniquefield = '$uniquevalue'") or die("Could not perform select query - " . mysqli_error());
    $num_rows = mysqli_num_rows($result);
    //if query result is empty, returns NULL, otherwise, returns an array containing the selected fields and their values
    if ($num_rows == NULL) {
        return NULL;
    } else {
        $queryresult = array();
        $num_fields = mysqli_num_fields($result);
        $i = 0;
        while ($i < $num_fields) {
            $currfield = mysqli_fetch_field($result);
            $queryresult[$currfield->name] = mysqli_fetch_array($result, MYSQLI_BOTH);
            $i++;
        }
        return $queryresult;
    }
}

回答1:


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.




回答2:


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!



来源:https://stackoverflow.com/questions/59630282/php-changing-fetch-field-to-mysqli

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!