-1

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;
    }
}
hullguy
  • 11
  • 1
  • have a look to example #2 here: https://www.php.net/manual/en/mysqli-result.fetch-field.php it is the same of your case... – DaFois Jan 07 '20 at 14:26
  • 1
    Fastest way to do that is search for functions on php.net like `mysql_select_db` will show you new alternate function and you might want to use prepare statement to prevent from sql injections. https://www.php.net/manual/tr/mysqli.quickstart.prepared-statements.php –  Jan 07 '20 at 14:27
  • 1
    [`mysqli_fetch_assoc`](http://php.net/mysqli_fetch_assoc) instead of that field-by-field query loop. – mario Jan 07 '20 at 15:24
  • Does this answer your question? [How to change mysql to mysqli?](https://stackoverflow.com/questions/1390607/how-to-change-mysql-to-mysqli) – Dharman Jan 07 '20 at 16:58
  • 1
    See how to use mysqli here: https://phpdelusions.net/ – Dharman Jan 07 '20 at 16:59
  • FYI this code in mysqli would be 4 lines long. Don't overthink it. – Dharman Jan 07 '20 at 17:00
  • Show us what you tried so far. If you are stuck and the links don't help maybe we can help you further. – Dharman Jan 07 '20 at 17:05
  • @Dharman many thanks for your help and also the other contributors. I've been trying to work through the different options the last few days and I'm just making myself more confused I think! So far I'd tried the code below; – hullguy Jan 10 '20 at 13:58
  • @Dharman I've edited it in now – hullguy Jan 10 '20 at 14:11
  • First thing is that `$connAsh` is undefined. Where do you open the DB connection and how do you pass it into the function? – Dharman Jan 10 '20 at 14:15
  • I'd not copied the first line across in the new version which define $connAsh and includes the connection to the database. This is used across the rest of the website and all seems to be working fine. – hullguy Jan 10 '20 at 14:21
  • The original function is wrong on so many levels but the only question I have to ask is *why didn't you use just a single line with mysql_fetch_assoc* instead of that monster loop? – Your Common Sense Jan 10 '20 at 14:22

2 Answers2

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0

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!

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Thanks so much for your time with this, I'll try to use the mysql_fetch_assoc function suggested but if I can't get that working I'll give this a try. I didn't write the original code so no idea why it was written this way, but was recently given the unfortunate task of trying to get the website working while having very limited php knowledge myself. – hullguy Jan 10 '20 at 15:30