douni1396 2014-12-14 12:14
浏览 31

PHP创建2行而不检查输入

What I'm trying to do is make a username (just username) get sent to a MySQL database, if it isn't already there.

Basically, I'm getting the input, checking it against all other rows in my username column, and, if the input is not the same as any of them, then add the input to the database. Here is my code:

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}



if( isset( $_POST["submit"] ) ) {
    $sql="INSERT INTO users (username)
    VALUES('$_POST[username]')";


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

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        if ($row["username"] == $_POST[username]) {
            die("Username is already in use!");
        }
    }
}


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    die("Error, please consult an admin: " . $sql . "<br>" . $conn->error);
    }
$conn->close();

No error is reported, but it simply creates the data twice, and doesn't check the input. I can't see how. This is how I've tried. It looks logical that is should work, but it's not. Why?

I'm using MySqli Object-Orientated

  • 写回答

2条回答 默认 最新

  • dongshaidu2456 2014-12-14 12:18
    关注

    You are executing the $conn->query($sql) twice. The first one is in $result = $conn->query($sql); and the second if ($conn->query($sql) === TRUE). That is why you get 2 entries in the for one request.

    First check for the user you are prepering to insert and if it returns 0 statements then go with the second if you have wrote.

    Edit 2:

    Try use PDO:

    The code will look something like this:

    if( isset( $_POST["submit"] ) ) {
        $stmt = $pdo->prepare("SELECT username FROM users WHERE username LIKE ?");
        $stmt->execute( array( $_POST["username"] ) );
        $_results = $stmt->get_result();
    
        if( count( $_results ) > 0 ) {
            die("Error, please consult an admin!");
        } else {
            $stmt = $pdo->prepare('INSERT INTO users (username) VALUES( ? )' );
            $stmt->bindParam( 1, $_POST['username'] );
    
            if( $stmt->execute() ) {
              echo 'Success';
            } else {
              echo 'Whoops, you have an error mate!';
            }
        }
    }
    

    Hope it helps

    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序