0

Im not sure how best to phrase this, and I am a newbie, but basically I was wondering if its possible to create a function that has a dynamic variable in the code that is executed. For instance:

function getData($array)
{
    $result = mysqli_query($con, $query) or die(mysqli_error($con));                        
    $array = array();
    while ($row = mysqli_fetch_assoc($result)){
        $array[] = $row;
    }   
}

$query = "SELECT name FROM color ORDER BY name";
getData ($color_array);
$arrayCount = count($color_array);

So $array is the value i would like to be able to change each time i run the function against a new query. For instance after the above I could do:

$query = "SELECT name FROM size ORDER BY name";
getData ($size_array);
$arrayCount = count($size_array);

I guess a placeholder may be a better description of what I'm looking to use.

Cheers

2 Answers 2

2

I think the best way would be to go on like this:

function getData($query, $con)
{
    $result = mysqli_query($con, $query) or die(mysqli_error($con));                        
    $array = array();
    while ($row = mysqli_fetch_assoc($result)){
        $array[] = $row;
    }
    return $array;
}

$query = "SELECT name FROM color ORDER BY name";
$color_array = getData ($query, $con);
$arrayCount = count($color_array);

$query = "SELECT name FROM size ORDER BY name";
$size_array = getData ($query, $con);
$arrayCount = count($size_array);

Here you are sending to the function the query and the connection to use, and when you execute that function you save it in a var with the names you want, then you can do whatever you like with the value.

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

2 Comments

This. You generally want to avoid using references because: 1. References are not pointers. 2. PHP's memory management internals are quite well developed. 3. References are a great way to make your code break in ways that are very difficult to track down.
Thank you, this has solved the issue for me and cleared up where my thinking was wrong.
1

You must use & operator. More here http://php.net/manual/en/language.references.pass.php

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.