Вопрос

In the project that I am creating, I have a mysql column that is an array of different pieces of data from the database. These pieces of data have info that I want to display. In order to separate these items in the array I used,

$get_query = mysql_query('Select array FROM data');
while($dataRow = mysql_fetch_assoc($getfrnd_query)) {
    $array = $dataRow['array'];
    if($array != "") {
        $data_from_array_column = explode("," $array);
        $getdata = mysql_query("SELECT * FROM info WHERE item = $data_from_array_column");
        //Then I used a mysql_fetch_assoc to get data based on the item.
    }
}

When I run this code, I get an error "Array to string conversion on the line with $getdata". Is there any way to get this to work?

Thank you.

Это было полезно?

Решение

The problem is that explode returns an array containing the strings in between the character(s) you used as a delimiter (, in your case), not a string.

PHP is getting mad because it doesn't know how to convert your array to a string automatically. So, you will need to convert it yourself. The options are:

  1. You want to select the row where item is equal to the nth element in the array, $data_from_array_column. If this is the case, you need to insert the following line of code after your explode:

    $data_from_array_column = $data_from_array_column[0];

  2. If you want to select where it matches any of the elements in the $data_from_array_column array, it will get more complicated. You would need to add this line after the explode:

    $data_from_array_column = implode("' OR item='",$data_from_array_column);

    and change your query on the next line to:

    $getdata = mysql_query("SELECT * FROM info WHERE item='$data_from_array_column'");

    This will create a MySQL query that looks some thing like this:

    SELECT * FROM info WHERE item='foo' OR item='bar' OR item='bla'

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top