结合三个查询并获得特定的错误警报

combine three query and get specific error alert

我该如何简要说明这个问题? 我想将它们结合起来,但得到特定的错误警报和不同的三个变量

<?php
    $sql = "SELECT content FROM post where title='tv'";
    $sql2 = "SELECT content FROM post where title='radio'";
    $sql3 = "SELECT content FROM post where title='net'";
    $result = $connection->query($sql);
    $result2 = $connection->query($sql2);
    $result3 = $connection->query($sql3);
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) { 
            $tvPrice = $row['content']; 
        }
    }else{
        echo "tv error";
    }
    if ($result2->num_rows > 0) {
        while($row = $result2->fetch_assoc()) { 
            $radioPrice = $row['content']; 
        }
    }else{
        echo "radio error";
    }
    if ($result3->num_rows > 0) {
        while($row = $result3->fetch_assoc()) { 
            $netPrice = $row['content']; 
        }
    }else{
        echo "net error";
    }
?>

使用 IN() 您可以 return 仅那些标题为 'tv'、'radio' 和 'net' 的行。然后将 title 添加到查询选择中,以便您知道哪个结果是哪个。

然后只需修改您的代码,将所有结果提取到一个行数组中,然后检查条目并相应地报告错误

<?php
// make a connection to the database obviously :)
$sql = "SELECT title, content 
        FROM post 
        WHERE title IN('tv', 'radio', 'net')";
$result = $connection->query($sql);
$rows = $result->fetch_all(MYSQLI_ASSOC);

// better initialise the variables in case you try using them later
$tvPrice = $radioPrice = $netPrice = 0;

foreach ($rows as $row){
    if ($row['title'] == 'tv')){
        $tvPrice = $row['content']; 
    }
    
    if ($row['title'] == 'radio') {
        $radioPrice = $row['content']; 
    }

    if ($row['title'] == 'net') {
        $netPrice = $row['content']; 
    }
}
if ( $tvPrice == 0 ) echo 'tv error';
if ( $radioPrice == 0 ) echo 'radio error';
if ( $netPrice == 0 ) echo 'net error';
?>

通常你实际上并不需要树(或更多)变量;使用数组。

<?php

$titles = ['tv', 'radio', 'net'];

// Generate the query
$sql = 
    "SELECT content, title FROM post WHERE title IN(" 
        . implode(", ", array_map(function( $title ) use( $connection ) {
            return '"' . mysqli_real_escape_string($connection, $title) . '"';
        }, $titles) ) 
    . ")";

$result = $connection->query($sql);

$prices = [];

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
            
        // Check for duplicates
        if( !empty( $prices[ $row['title'] . 'Price' ] ) )
            echo $row['title'] . " has duplicate error";
        else
            $prices[ $row['title'] . 'Price' ] = $row['content'];
    }
}

// Check if we have all desires rows 
foreach( $titles as $title )
    if( empty( $prices[ $title . 'Price' ] ) )
        echo "$title missing error";

// If you really need tree variables instead of array:
extract($prices);