0

Let say that we are going to add some array to a multidimensional array. I can select the number of arrays which should be added to the main array but what about 99 array? Here is my code that I can change $howmany to add the number of arrays that I need (up to 4 arrays):

function DB_SINGLE_EXE($query, array  $array_par, $howmany = 0 ,$column1 = "null", $column2 = "null", $column3 = "null", $column4 = "null"){
global $host;
global $dbname;
global $username;
global $password;
global $db;
try {
    $stmt = $db->prepare($query);
    $stmt->execute($array_par);
}catch(PDOException $e)
    {
    echo "ERROR: " . $query . "<br>" . $e->getMessage();
    }

if ($howmany > 0){
$rowF = $stmt->fetchAll();

if($rowF){ 
$hell = count($rowF);
$stack = array(array("true" , $hell));
    foreach ($rowF as $row) {
        switch ($howmany) {
        case 1:
            array_push($stack, array($row[$column1]));
            break;
        case 2:
            array_push($stack, array($row[$column1], $row[$column2]));
            break;
        case 3:
            array_push($stack, array($row[$column1], $row[$column2], $row[$column3]));
            break;
        case 4:
            array_push($stack, array($row[$column1], $row[$column2], $row[$column3], $row[$column4]));
            break;
        }
    }
}else{
$stack = array(array("false" , "0"));
}  

return $stack;
}
}


How I call the function:

$temp_query = "SELECT * FROM users WHERE status=:one";
$temp_array = array(":one" => "OK");
$results =DB_SINGLE_EXE($temp_query, $temp_array, 4, "user", "pw", "a_succ", "m_succ");
if ($results[0][0]="true"){
$username = $results[1][0];
$password = $results[1][1];
$suc = $results[1][2];
$m_suc = $results[1][3];
// Here I want to get more results but in function I just limited to 4 outputs. It might be 99 or even more and I don't want to use "select case" for 99 cases!
}
12
  • Where are the $column1, $column2, etc. variables coming from? Are they preset to some textual keys? Will they be preset all the way to 99? Or you just need to add all values from the $row array to the $stack? Commented Aug 4, 2015 at 16:44
  • @martynasma This is a function in fact. and each of these variables are come as a function parameter. I also want to push them by an array but I think I can handle it myself (I just think!!) Commented Aug 4, 2015 at 16:47
  • I have updated my answer with examples for both php 5.6 and before. Commented Aug 4, 2015 at 17:43
  • @Bablod For what do you need this code? Your function makes absolutely no sense and I can't imagine for what you ever could need something like this. Commented Aug 4, 2015 at 18:10
  • 1
    After reading your full code, I believe you are contracted a curable disease: Abutor asteriscus. By simply not using asterisk in you query and ordering columns to your liking, you can get the same result: SELECT user, pw, a_succ, m_succ FROM .... Works faster and gives more understandable errors. Commented Aug 7, 2015 at 18:15

3 Answers 3

3

If you are using PHP 5.6 you may use ellipses (...) syntax. If not jump to the end. Example from php.net:

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

Then your function will become two loops inside each other.

EDIT: To make things simpler, here is your transformed code

function DB_SINGLE_EXE(...$columns){
    $stack = array(array("foo" , "bar"));
    foreach ($rowF as $row) {
        $arr=array();
        foreach($columns as $col) {
            $arr[]=$row[col];
        }
        array_push($stack, $arr);
    }
    return $stack;
}

DB_SINGLE_EXE("id", "name", "age");

You can do the same without using ellipses, simply pass an array of columns:

function DB_SINGLE_EXE($columns){
    $stack = array(array("foo" , "bar"));
    foreach ($rowF as $row) {
        $arr=array();
        foreach($columns as $col) {
            $arr[]=$row[col];
        }
        array_push($stack, $arr);
    }
    return $stack;
}

DB_SINGLE_EXE(array("id", "name", "age"));

Not as pretty but still works.

Sign up to request clarification or add additional context in comments.

1 Comment

Passing an array is definitely the correct method. If OP needed two things to be dynamic (e.g. tables to union and columns to return) then there would be no other way.
2

I had a hard time interpreting what you're trying to do, so this may or may not work since the provided code isn't actually functional for comparison. It looks like you're needing to take certain columns out of a SELECT * result set, or something like that. Assuming so, it would be better to just modify your query to only get what you need, then use a basic fetchAll() approach.

However, assuming you can't do that for some reason, see if this works for you. I initialized a $rowF variable here with something like I am expecting it to be when your code runs. If that's incorrect, this may be way off, but here it is:

function DB_SINGLE_EXE(array $columnsToPush) {
    $rowF = array(array('col1' => 'col1val', 'col2' => 'col2val', 'cola' => 'colaval', 'colb' => 'colbval'));

    $stack = array(array('foo', 'bar'));
    foreach ($rowF as $row) {
        $toBePushed = array();
        foreach ($columnsToPush as $columnName) {
            $toBePushed[] = $row[$columnName];
        }
        $stack[] = $toBePushed;
    }
    return $stack;
}

DB_SINGLE_EXE(array('col1', 'cola'));

Some sanity checking to make sure the column names exist in the row is in order, among other hardening, of course.

EDIT

After seeing the full function, while I have concerns about the design, I think you could simplify things greatly with:

function DB_SINGLE_EXE($query, array  $array_par){
    global $host;
    global $dbname;
    global $username;
    global $password;
    global $db;
    try {
        $stmt = $db->prepare($query);
        $stmt->execute($array_par);
    } catch (PDOException $e) {
        echo "ERROR: " . $query . "<br>" . $e->getMessage();
        // should probably return here, or do something to halt further execution
    }

    return $stmt->fetchAll();
}

...

$results = DB_SINGLE_EXE($temp_query, $temp_array);
if (!empty($results)) {

    // wrap in foreach if appropriate
    $username = $results[0]['user'];
    $password = $results[0]['pw'];
    $suc      = $results[0]['a_succ'];
    $m_suc    = $results[0]['m_succ'];
}

Comments

1

Passing in 99 parameters to function seems like an overhead. Why can't your pass in the columns as array. This will allow you to pass in any number of column keys (even more than 99) ;)

function DB_SINGLE_EXE( $rowF, $columns ){
  $columns = array_flip( $columns );
  $stack = array( array( "foo" , "bar" ) );
  foreach ($rowF as $row) {
    array_push( $stack, array_intersect_key( $row, $columns ) );
  }
  return $stack;
}

$result = DB_SINGLE_EXE(array(
    array(
      'col1' => 'aaa1',
      'col2' => 'bbb1'
    ),
    array(
      'col2' => 'bbb2',
      'col3' => 'ccc2'
    ),
    array(
      'col1' => 'aaa3',
      'col2' => 'bbb3',
      'col3' => 'ccc3'
    ),
    array(
      'col1' => 'aaa3',
      'col5' => 'eee3',
      'col6' => 'fff3'
    )
  ), array('col1', 'col2', 'col3'));

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.