php - How to select first 3 values from a mysql concetenated column

one text

Solution:

You simply fetch the data using then split it and loop through the array.

Database class (Provided this class so you can see how I am fetching the data)

<?php

class Database
{
    //Instance of connection
    private static $_instance = null;

    //database connection variables
    private $servernane;
    private $username;
    private $password;
    private $dbname;
    private $options;
    private $dsn;

    // database operation variables
    private $_pdo;

    public function __construct()
    {
        $this->servername = "localhost";
        $this->username = "root";
        $this->password = "";
        $this->dbname = "crud";
        $this->options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_CASE => PDO::CASE_NATURAL,
            PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING,
        ];

        try 
        {
            $this->dsn = "mysql:host={$this->servername};dbname={$this->dbname}";
            $this->_pdo = new PDO($this->dsn, $this->username, $this->password);
            echo "Connected sucessfully to the database";
        } catch (PDOExeption $e) 
        {
            echo "connection failed: " . $e->getMessage();
        }
    }

    public static function getInstance()
    {
        if (!isset(self::$_instance)) {
  

      self::$_instance = new Database();
    }
    return self::$_instance;
}
public function query($sql, $params = array())
{
    $stmt = $this->_pdo->prepare($sql);
    $stmt->execute($params);

    return $stmt;
}

}

Now here is the solution.

<?php

require_once './classes/Database.class.php';

$db = Database::getInstance();

$stmt = $db->query('select multi_values from example WHERE id = :id', 
        array('id' => 1));

$data = $stmt->fetch()['multi_values'];

$data_arr = explode("+", $data);


if (count($data_arr) === 1 ) {
    echo $data_arr[0]; 
}elseif (count($data_arr) === 2 ) {
    for ($x = 0; $x <= 1; $x++) {
        echo $data_arr[$x];
    }
}elseif (count($data_arr) === 3 ) {
    for ($x = 0; $x <= 2; $x++) {
        echo $data_arr[$x];
    }
}
elseif (count($data_arr) === 4 ) {
    for ($x = 0; $x <= count($data_arr) - 2; $x++) {
        echo $data_arr[$x];
    }
}

Source