在mysql和php中如何从单个列中获取不同的数据

在mysql和php中如何从单个列中获取不同的数据,php,mysql,Php,Mysql,我想用逗号分隔在一列中存储多个数据,并在php的帮助下以不同的行返回数据 就像在列视图中,它看起来是这样的——牙刷-1234,玻璃-1234, 上面的1234是产品id 我想在php中获得这些数据,每行都有单独的值和所有细节。 像 因此,是否有可能获取数据并将其从单个列中按和分隔。您希望将逗号分隔的数据显示到单独的行中。你可以试试这个 <? //Here is the complete example of your code by using MYSQLi Object Orient

我想用逗号分隔在一列中存储多个数据,并在php的帮助下以不同的行返回数据 就像在列视图中,它看起来是这样的——牙刷-1234,玻璃-1234, 上面的1234是产品id 我想在php中获得这些数据,每行都有单独的值和所有细节。 像



因此,是否有可能获取数据并将其从单个列中按和分隔。

您希望将逗号分隔的数据显示到单独的行中。你可以试试这个

<?
//Here is the complete example of your code by using MYSQLi Object Oriented:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "select product_id,product_name form products where product_id=1234";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    $yourData = array();
    while($row = $result->fetch_assoc()) {
        $yourData[$row['product_id']] = explode(",",$row['product_name']);
    }

    if(count($yourData) > 0){
        foreach ($yourData as $key => $value) {
            foreach ($value as $productname) {
                echo "Product ID >> ".$key. " -- Product Name >> ".$productname;
            }
        }
    }
} 
else 
{
    echo "0 results";
}
$conn->close();

?>


旁注:如果您在应用程序中使用
mysql.*
,我建议您使用
mysqli.*
PDO
,因为
mysql.*
已被弃用,在PHP7中不可用。

对于逗号分隔的值,使用
FIND.\u-in.
我存储数据的方法是错误的,我发现了后来
<?
//Here is the complete example of your code by using MYSQLi Object Oriented:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "select product_id,product_name form products where product_id=1234";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    $yourData = array();
    while($row = $result->fetch_assoc()) {
        $yourData[$row['product_id']] = explode(",",$row['product_name']);
    }

    if(count($yourData) > 0){
        foreach ($yourData as $key => $value) {
            foreach ($value as $productname) {
                echo "Product ID >> ".$key. " -- Product Name >> ".$productname;
            }
        }
    }
} 
else 
{
    echo "0 results";
}
$conn->close();

?>