1

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 ?

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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++;         
    }
}

Comments

1

How about insert if table is empty as below?

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

Comments

1

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++;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.