[英]Php & mysql if table is empty
I have this section of cod: 我有鳕鱼的这一部分:
how i can stop this section 我如何才能停止本节
for($i=0; $i<$n-1 ; $i++) {
mysqli_query($con,"INSERT INTO text (ID, TXT)
VALUES ('$id', '$sir[$i]')");
$id++;
}
if table isn't empty ? 如果表不为空?
Do a 做一个
SELECT COUNT(*) AS cnt FROM text
and check how many entries you have. 并检查您有多少条目。 If cnt>0 place a break at the beginning of loop.
如果cnt> 0,则在循环开始处放置一个中断。
You need to add before the specific block: 您需要在特定块之前添加:
// 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++;
}
}
How about insert if table is empty as below? 如果表为空,如何插入,如下所示?
INSERT INTO my_table (colname)
SELECT 'foo'
WHERE NOT EXISTS (SELECT * FROM my_table)
Just a select a row and see what happens... 只需选择一行,看看会发生什么...
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.