0

This is my table

CREATE TABLE room ( room_ID VARCHAR(8), room_name TEXT(50), room_capacity INT(3), room_building VARCHAR(20), room_type VARCHAR(20), room_desc TEXT(100), PRIMARY KEY (room_ID) );

and this is my insert code.

<?php
//Start session
session_start();

//Import connection
include('conn.php');

$room_ID = $_POST["room_ID"];
$room_type = $_POST["room_type"];
$room_name = $_POST["room_name"];
$room_capacity = $_POST["room_capacity"];
$room_building = $_POST["room_building"];
$room_desc = $_POST["room_desc"];

//echo $room_ID;
//echo $room_type;
//echo $room_name;
//echo $room_capacity;
//echo $room_building;
//echo $room_desc;

//Check for duplicate room ID
//if($room_ID != '') {
    $qry = "SELECT room_ID FROM room WHERE room_ID = '".$room_ID."'";
    $result = mysql_query($qry);
    if($result) {
        if(mysql_num_rows($result) > 0) { 
            header("location: duplicateID.php");
            exit();
        }
        @mysql_free_result($result);
    }
    else {
        die("Yang ini lah failed");
    }
}

//Create INSERT query
$qry = "INSERT INTO room (room_ID, room_name, room_capacity, room_building, room_type, room_desc)
        VALUES('$room_ID', '$room_name', '$room_capacity', '$room_building', '$room_type', '$room_desc')";
$result = @mysql_query($qry);

//Check whether the query was successful or not
if($result) {
    header("location: addroomsuccess.php");
    exit();
} else {
    die("Query failed");
}?>

But the problem is, the process stuck in the first if else. But when i delete those if else, the query still failed. Why did this happen? Is it because im using varchar as the data type for the primary key?

4

1 回答 1

0

这有很多错误。

1)如果您有PK,您将不会得到重复,因此您的检查毫无意义。

2)只需插入它。如果失败,则说明您有重复或其他问题。首先检查只会缩小机会,但在多用户环境中仍然可能出错。

3)SQL注入 - 阅读它,在实现避免它的SQL(参数)时理解它。

但是要回答您的问题,它与 VARCHAR 作为 PK 无关 - 如果有意义的话,那很好。@AlexandreLavoie 的建议不好或不相关(对不起!)。

于 2013-05-28T10:37:12.957 回答