2

It must be Monday, the heat or me being stupid (prob the latter), but for the life of me I cannot get a simple php function to work.

I have a simple query

$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");

Which I want to run through a function: say:

function functionname($input){

    global $field1;
    global $field2;
    $sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
    while($row = mysql_fetch_array($sql)) :
    $field1[] = $row['field1'];
    $field2[] = $row['field2'];
    endwhile;   
    mysql_free_result($sql);

}

So that I can call the function in numerious places with differeing "inputs". Then loop through the results with a foreach loop.

Works fine the first time the function is called, but always gives errors there after.

As said "It must be Monday, the heat or me being stupid (prob the latter)".

Suggestions please as I really only want 1 function to call rather than rewrite the query each and every time.

This is the error message

Fatal error: [] operator not supported for strings in C:\xampp\htdocs\functions.php on line 270
5
  • 1
    It would be helpful if you posted the text of the error messages. Commented Aug 23, 2010 at 9:40
  • Try adding var_dump() function calls to the end of your function, to see what happens to the global variables. Commented Aug 23, 2010 at 9:48
  • Which line of code is line 270? It's likely that you're doing something with $field1 and/or $field2 between calls that changes them from array to another datatype. Use of globals here isn't a good idea, why not simply initialise an array in your function, populate that with the database data, then return the array Commented Aug 23, 2010 at 9:49
  • 1
    Avoid globals, they have many nasty quirks, such as you can see here: $field1 or $field2 is not an array (it was made a string somewhere; as it's a global, good luck figuring out where exactly), and the attempt to use it as an array gives you the error. Commented Aug 23, 2010 at 9:51
  • 1
    Also, what happens when $input = "Mr. O'Hara"? Sanitize your mysql code, or even better, use mysqli with parametrized queries. Commented Aug 23, 2010 at 9:53

6 Answers 6

1
function functionname($input){ 
    $sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$input'"); 
    $result = array('field1' => array()
                    'field2' => array()
                   );
    while($row = mysql_fetch_array($sql)) : 
       $result['field1'][] = $row['field1']; 
       $result['field2'][] = $row['field2']; 
    endwhile;    
    mysql_free_result($sql); 
    return $result;
} 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Mark, like this way it's easy to anoted (see my comment to Col Shrapnel) hence you get my "vote" as they say.
Sorry, Noob here: what does the empty array index do in $result['field1'][] = $row['field1']; ? Is that assigning an entire row to that array so it's like [field1][row element 1,row element 2]?
$result['field1'] is a "subarray" or nested array... the [] is appending a new entry to that subarray
1

it seems that somewhere the $field1 or $field2 are converted to strings and you cant apply the [] to a string... i'd say that you have to do:

$field1 = array();
$field2 = array();

before the WHILE loop

2 Comments

then that would make globalization pointless, he might aswell define them inside the function.
yeap.. it's better to return the values and manage the global variable outside this function
1

The problem is that you so called arrays are strings!

global $field1;
global $field2;
var_dump($feild1,$feild2); //Will tell you that there strings

Read the error properly !

[] operator not supported for strings

And the only place your using the [] is withing the $feild - X values

GLOBAL must work because the error is telling you a data-type, i.e string so they must have been imported into scope.


another thing, why you selecting all columns when your only using 2 of them, change your query to so:

$sql = mysql_query("SELECT feild1,feild2 FROM table WHERE field_name = '$input'");

another thing is that your using mysql_fetch_array witch returns an integer indexed array, where as you want mysql_fetch_assoc to get the keys.

while($row = mysql_fetch_assoc($sql)) :
    $field1[] = $row['field1'];
    $field2[] = $row['field2'];
endwhile;

What I would do

function SomeFunction($variable,&$array_a,&$array_b)
{
    $sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$variable'");
    while($row = mysql_fetch_assoc($sql))
    {
        $array_a[] = $row['field1'];
        $array_b[] = $row['field2'];
    }
    mysql_free_result($sql);
}

Then use like so.

$a = array();
$b = array();
SomeFunction('Hello World',&$a,&$b);

6 Comments

They have to be "arrays" to be able to run a loop - any suggestions then on how to get the array/s out of the function as global doesn't work
when you use globalization on variables inside a function any edits done on the values affect the variables outside directly, so aslong as the variables are in the root scope, you should be able to call the global in there!
i know there strings because of this !! [] operator not supported for strings
Updated with another error for the arrays witch might be causing it !
So explain to me why php tells the user that [] operator not supported for strings?
|
1

In my opinion, it's pretty unusual and even useless approach at all.
This function is too localized.
To make a general purpose function would be a way better.

<?
function dbgetarr(){
  $a = array();
  $query = array_shift($args);
  foreach ($args as $key => $val) {
    $args[$key] = "'".mysql_real_escape_string($val)."'";
  }
  $query = vsprintf($query, $args);

  $res = mysql_query($query);
  if (!$res) {
    trigger_error("dbgetarr: ".mysql_error()." in ".$query);
    return FALSE;
  } else {
    while($row = mysql_fetch_assoc($res)) $a[]=$row;
  }
  return $a;
}

and then call it like this

$data = dbgetarr("SELECT field1,field2 FROM table WHERE field_name = %s",$input);
foreach ($data as $row) {
  echo $row['field1']." ".$row['field1']."<br>\n";
}

1 Comment

Shrapnel - I totally agree with your comments "it's pretty unusual and even useless approach" but .. (there's always a but) this is a small project (8 tables) and must be "properly anoted" in a way that people with NO knowledge can read the notes & understand. hence the "individual" function route described above. Like your idea/approach one I would normally use (when not too hot or Monday :) ) Thanks for you more practical solution, much appreciated.
0

To understand your issue, we need the error, however, are you sure you are going about this in the right way?

Why do you need to call the function multiple times if you are just changing the value of the input field?

You could improve your SQL statement to return the complete result set that you need the first time.. i.e. SELECT * FROM table GROUP BY field_name;

Not sure if that approach works in your scenario, but in general you should aim to reduce the number of round trips to your database.

Comments

0

I don't know, i right or not. But i advise to try this:

function functionname($input){

    global $field1;
    global $field2;
    $sql = mysql_query("SELECT * FROM `table` WHERE `field_name` = '" . $input . "'");
    while($row = mysql_fetch_assoc($sql)) :
    $field1[] = $row['field1'];
    $field2[] = $row['field2'];
    endwhile;   
    mysql_free_result($sql);

}

2 Comments

Thanks Alex, but same result cannot loop through the arrays other than once ; e.g. <?php foreach($field1 as $field1): echo field1; endforeach; ?>
<?php foreach($field1 as $field) { echo $field; } ?>

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.