簡體   English   中英

PHP和MySQL如果表為空

[英]Php & mysql if table is empty

我有鱈魚的這一部分:

我如何才能停止本節

for($i=0; $i<$n-1 ; $i++) {
    mysqli_query($con,"INSERT INTO text (ID, TXT) 
        VALUES ('$id', '$sir[$i]')");
            $id++;         
}

如果表不為空?

做一個

SELECT COUNT(*) AS cnt FROM text

並檢查您有多少條目。 如果cnt> 0,則在循環開始處放置一個中斷。

您需要在特定塊之前添加:

// count the rows
$res = mysqli_query($con, "SELECT COUNT(ID) as numrows FROM text");
// fetch the result
$data=mysql_fetch_assoc($res);
// check if count = 0
if($data['numrows'] == 0) {
    // execute the codeblock
    for($i=0; $i<$n-1 ; $i++) {
        mysqli_query($con,"INSERT INTO text (ID, TXT) 
        VALUES ('$id', '$sir[$i]')");
            $id++;         
    }
}

如果表為空,如何插入,如下所示?

INSERT INTO my_table (colname)
SELECT 'foo'
WHERE NOT EXISTS (SELECT * FROM my_table)

只需選擇一行,看看會發生什么...

if (!($result = mysqli_query($con, "SELECT ID FROM text LIMIT 1")) || $result->num_rows < 1) {
    if($result) {
        $result->close();
    }
    for ($i = 0; $i < $n - 1; $i++) {
        mysqli_query($con, "INSERT INTO text (ID, TXT)
            VALUES ('$id', '$sir[$i]')");
        $id++;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM