Reputation: 577
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
Upvotes: 0
Views: 63
Reputation: 378
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.
Upvotes: 2
Reputation: 2848
You must use &
operator. More here http://php.net/manual/en/language.references.pass.php
Upvotes: 1