Input my php in mysql without repeat?

2019-03-06 23:37发布

问题:

I create this code to add some data in my db without repeat.
but that is not work and I can't add data create by this php to my table.
what's the problem ?
P.S: I have no error!
P.P.S:I do this on wamp server.

<?php

    $con=mysqli_connect("localhost","root","","kosar");
    // Check connection
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    for ($i=0;$i<10;$i++) {
        $n1 = rand(100000,999999);
        $n2 = rand(100000,999999);

        $pincode = (string)$n1;
        echo $pincode;
        echo nl2br("$pincode\n");


        mysql_query ("INSERT IGNORE INTO kosar(ID, Code, Type, Used) VALUES('', '".$pincode."','1', '0')");
        if(mysql_affected_rows() == 0)
        {
            // Duplicates found
        }else{
            // No duplicates were found
        }
    }
    for ($i=0;$i<10;$i++) {
        $n1 = rand(100000,999999);
        $n2 = rand(100000,999999);

        $pincode = (string)$n1; 
        echo $pincode;  
        echo nl2br("$pincode\n");
        mysql_query("INSERT IGNORE INTO kosar(ID, Code, Type, Used) VALUES('', '".$pincode."','2', '0')");
        if(mysql_affected_rows() == 0)
        {
            // Duplicates found
        }else{
            // No duplicates were found
        }
    }
    for ($i=0;$i<10;$i++) {
        $n1 = rand(100000,999999);
        $n2 = rand(100000,999999);

        $pincode = (string)$n1;
        echo $pincode;
        echo nl2br("$pincode\n");
        mysql_query("INSERT IGNORE INTO kosar(ID, Code, Type, Used) VALUES('', '".$pincode."','3', '0')");
        if(mysql_affected_rows() == 0)
        {
            // Duplicates found
        }else{
            // No duplicates were found
        }
    }

    mysqli_close($con);
?>

回答1:

I am surprised that this does not throw any errors. One as Barmar mentioned, you cannot mix sqli and sql functions.

Also logically, I do not see you select any database.

Try this first

$con=mysqli_connect("localhost","my_user","my_password","my_db") or die('error message');

then use

mysqli_query($con,"your query here");

let me know the results.