2

I am trying to create a function that gets the name and clientid. What is the proper way to return an array? so that I can have multiple values returned.

function get_client_name($conn, $clientid){
  $response = array();
  $query = "SELECT NAME, CLIENTID FROM LCCLIENT WHERE CLIENTID = '". $clientid ."'";
  $sql = oci_parse($conn, $query);
  $exec = oci_execute($sql);

  if($exec){
      $row = oci_fetch_array($sql);
      $response[] = array(
          'CLIENTID' => trim($row['CLIENTID']),
          'NAME' => trim($row['NAME'])
      );
  }

  return json_encode($response);
}

echo get_client_name($conn, '2000000800')[0]['CLIENTID'];
echo get_client_name($conn, '2000000800')[0]['NAME'];
2
  • 3
    Just return $response Commented Jun 18, 2020 at 3:30
  • You don't need to select CLIENTID, you already know it. You also may be open to SQL injections. Best to parameterize. Commented Jun 18, 2020 at 3:32

1 Answer 1

0

You just return your array, without encoding it in JSON format. Also don't call this function two times, because it's redundant to call DB two times for the same data. Second thing, you shouldn't pass $conn in this function. You should develop some structure for database connections.

function get_client_name($conn, $clientid)
{
    $response = array();
    $query = "SELECT NAME, CLIENTID FROM LCCLIENT WHERE CLIENTID = '" . $clientid . "'";
    $sql = oci_parse($conn, $query);
    $exec = oci_execute($sql);

    if ($exec) {
        $row = oci_fetch_array($sql);
        $response[] = array(
            'CLIENTID' => trim($row['CLIENTID']),
            'NAME' => trim($row['NAME'])
        );
    }

    return $response;
}

$clientName = get_client_name($conn, '2000000800');

echo $clientName[0]['CLIENTID'];
echo $clientName[0]['NAME'];
Sign up to request clarification or add additional context in comments.

3 Comments

Do I need to include my connection inside my function?
If you don't use any framework that's ok, but you will regret if system gets bigger, because it's hard to maintain this kind of functions. You should write code more object-oriented, but this is not main purpose of this question. You can read more about the concept, i.e.: stackoverflow.com/questions/8474876/…
Thank you I will consider that in the future

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.