Separate a string between comas

Hi everyone,

I am trying to pick the information of a cell from a database and work with that information as it is a string. For example, I charge the following from the database:

The Telltale Games Collection,alien

The code I have written for this:

        $busqueda = trim($_GET['busqueda']);
        $busqueda = htmlspecialchars($busqueda);

        $busqueda_partes = explode(",",$busqueda);

        echo count($busqueda_partes);

        echo $busqueda_partes[0]; // The Telltale Games Collection
        echo $busqueda_partes[1]; // doesn´t exist

I don´t know what I am doing wrong, if I try with a text it´s ok the code:

    $text = "Hello, this is a trial";


    $busqueda_partes = explode(",",$text);

    echo count($busqueda_partes);

    echo $busqueda_partes[0]; // Hello
    echo $busqueda_partes[1]; // this is a trial

I suppose that it´s something related to the database.

Thanks in advice.

Looks pretty much OK but where are you getting the data from? You say it’s from a database but your code is using $_GET[‘busqueda’].

If ever I don’t get the output I was expecting I’ll always output the variables, so try this:

print_r($busqueda);
print_r($busqueda_partes);

And see what you get.

Thanks for your response,

I am taking the information from phpmyadmin. The cell type is “varchar”. I have tried what you told me and this is what I get:

print_r($busqueda); // The Telltale Games Collection
print_r($busqueda_partes); // Array ( [0] => The Telltale Games Collection )

Can I set to string or something similar?

Varchar is a string so that’s fine. Where does $_GET['busqueda'] come into it then? If you’re getting data from a database then you shouldn’t need $_GET.

Can you post the whole script?

If you’re passing the string through from another script as part of the URL, are you properly encoding it so that spaces and commas don’t cause confusion?

This two lines:

        $busqueda = trim($_GET['busqueda']);
        $busqueda = htmlspecialchars($busqueda);

Are to take the information the users writes in the search bar, and now I have realized that I was messing my-self. I have tried now and It works. Sorry, I didn´t realized.

//Introducing in the search bar: The Walking Dead: The Complete First Season

        $busqueda = trim($_GET['busqueda']);
        $busqueda = htmlspecialchars($busqueda);

        $statement = $conexion->prepare('SELECT  * FROM listado_precios WHERE titulo LIKE :busqueda');
        $statement->execute(array(':busqueda' => "%$busqueda%"));
        $juegos = $statement->fetchAll();

        $busqueda_partes = explode(";", $juegos[0]['pertenece']);

        echo $busqueda_partes[0]; //The Telltale Games Collection
        echo $busqueda_partes[1]; //alien

Thanks!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.