1

编辑:更新!让第一部分工作。但是,我不确定如何检查同一 IF() 语句中的其他变量。任何人都可以帮助我吗?单个 if 语句将拒绝名称与输入完全相同的类。但是,我还需要它拒绝相等的天数和时间。

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Register Diver</title>
    <link rel="stylesheet" href="php_styles.css" type="text/css" />
    <meta http-equiv="content-type"
    content="text/html; charset=iso-8859-1" />
    </head>
    <body>
    <h1>Aqua Don's Scuba School</h1>
    <h2>Registration Confirmation</h2>
    <?php
    $DiverID = $_GET['diverID'];
    if (empty($DiverID))
        exit("<p>You must enter a diver ID! Click your browser's Back button to return to the previous page.</p>");
    $DBConnect = @mysqli_connect("localhost", "students", "password")
        Or die("<p>Unable to connect to the database server.</p>"
        . "<p>Error code " . mysqli_connect_errno()
        . ": " . mysqli_connect_error()) . "</p>";
    $DBName = "scuba_school";
    @mysqli_select_db($DBConnect, $DBName)
        Or die("<p>Unable to select the database.</p>"
        . "<p>Error code " . mysqli_errno($DBConnect)
        . ": " . mysqli_error($DBConnect)) . "</p>";

    $TableName = "registration";
    $SQLstring = "SELECT * FROM $TableName";
    $QueryResult = @mysqli_query($DBConnect, $SQLstring);
    if (!$QueryResult) {
        $SQLstring = "CREATE TABLE registration (diverID SMALLINT, class VARCHAR(40), days VARCHAR(40), time VARCHAR(40))";
        $QueryResult = @mysqli_query($DBConnect, $SQLstring)
            Or die("<p>Unable to create the registration table.</p>"
            . "<p>Error code " . mysqli_errno($DBConnect)
            . ": " . mysqli_error($DBConnect)) . "</p>";
        echo "<p>Successfully created the registration table.</p>";
    }
    ?>

    <?php
    $Class = $_GET['class'];
    $Days = $_GET['days'];
    $Time = $_GET['time'];
    $DiverID = $_GET['diverID'];

    $DBConnect = mysqli_connect("localhost", "students", "password");
    $DBName = "scuba_school";
    @mysqli_select_db($DBConnect, $DBName)
        Or die("<p>Unable to select the database.</p>"
        . "<p>Error code " . mysqli_errno($DBConnect)
        . ": " . mysqli_error($DBConnect)) . "</p>";


    $sqlString= "SELECT * FROM `registration` WHERE `diverID` = $DiverID AND `class` = '$Class' AND `days` = '$Days' AND `time` = '$Time'";
    $QueryResult = mysqli_query($DBConnect, $sqlString) or die("MySQL error: " . mysqli_error($DBConnect) . "<hr>\nQuery: $QueryResult");  
    $row = mysqli_fetch_assoc($QueryResult);

    if ($row["class"] == $Class)
    {

    echo "<p>You are already registered for $Class</p>";
        }

        elseif($row["days"] == $Days && $row["time"] == $Time)
        {
            echo "<p>There is a conflict with $Days or $Time</p>";
            }
    else
    {
     $SQLstring = "INSERT INTO $TableName VALUES('$DiverID', '$Class', '$Days', '$Time')";
        $QueryResult = @mysqli_query($DBConnect, $SQLstring);
        echo "<p>You are registered for $Class on $Days, $Time. Click your browser's Back button to register for another course or review your schedule.</p>";
    }


    mysqli_close($DBConnect);
    ?>

    </body>
    </html>
4

3 回答 3

1

笔记

顺便说一句,在 PHP 中,按照惯例,变量以小写字符开头,而类和接口以大写字符开头。此外,如果您愿意,请阅读这些标准 (PSR)。这些是我采用的标准


编辑:我刚刚用模拟 mysql 表测试了这段代码,它可以按需要工作。按照提供的模式创建 MYSQL 表。您可以使用 PHPMyAdmin 导入架构。将完整代码复制到新文件并在浏览器中运行。将按预期工作,自己测试。

MYSQL 表:

登记

-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Nov 16, 2012 at 11:14 AM
-- Server version: 5.5.24
-- PHP Version: 5.3.15

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;


-- --------------------------------------------------------

--
-- Table structure for table `registration`
--

CREATE TABLE IF NOT EXISTS `registration` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `diverID` int(11) NOT NULL,
  `class` int(11) NOT NULL,
  `time` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `class` (`class`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=14 ;

--
-- Dumping data for table `registration`
--

INSERT INTO `registration` (`id`, `diverID`, `class`, `time`) VALUES
(3, 1, 1, '2012-11-18 11:30:00'),
(4, 1, 3, '2012-11-19 17:00:00'),
(13, 2, 1, '2012-11-19 17:00:00');

--
-- Constraints for dumped tables
--

--
-- Constraints for table `registration`
--
ALTER TABLE `registration`
  ADD CONSTRAINT `registration_ibfk_2` FOREIGN KEY (`class`) REFERENCES `classes` (`cid`);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

类:

-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Nov 16, 2012 at 11:16 AM
-- Server version: 5.5.24
-- PHP Version: 5.3.15

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

-- --------------------------------------------------------

--
-- Table structure for table `classes`
--

CREATE TABLE IF NOT EXISTS `classes` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `className` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`cid`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ;

--
-- Dumping data for table `classes`
--

INSERT INTO `classes` (`cid`, `className`) VALUES
(1, 'diving 101'),
(2, 'diving 102'),
(3, 'breathing exercices'),
(4, 'fish hunting');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

PHP代码

<?php
$html = '<!DOCTYPE HTML>
<html>
<head></head>
<body>';

//MYSQL Connection (change accordingly)
$mysqli = new mysqli("127.0.0.1", "root", null, "test");

// Classes list
$classList = getClassList($mysqli);

if (!isset($_GET['submit'])) {
    $html .= '<form method="get">
        diverID: <input name="diverID"/><br/>
        class: <select name="class">';

    foreach ($classList as $key => $val) {
        $html .= '<option value="'. $key .'">'.$val.'</option>';
    }

    $html .= '</select><br/>
        time: <input type="datetime" name="time"/><br/>
        <input type="submit" name="submit" value ="submit"/>
    </form>';
} else {
    // Retrieve results from POST and parse them
    $diverID = $mysqli->escape_string($_GET['diverID']);
    $class = $mysqli->escape_string($_GET['class']);
    $time = $mysqli->escape_string($_GET['time']);

    if (canDiverRegisterForClass($mysqli, $diverID, $class, $time)) {
        if (registerDiverInClass($mysqli, $diverID, $class, $time)) {
            $html .= "<p>You were successfully registered for $classList[$class] at $time</p>";
        } else {
            var_dump(mysqli_error($mysqli));
            $html .= "<p>An error ocurred while registering you. Please contact the administrator!</p>";
        }
    } else {
        $html .= "<p>You can't register for '$classList[$class]' at $time!</p>";
    }
}
$html .= '</body></html>';
print $html;



function getClassList($mysqli)
{
    $list = array();
    $result = $mysqli->query("SELECT * FROM classes");
    foreach ($result->fetch_all() as $r) {
        $list[$r[0]] = $r[1];
    }
    return $list;
}

function canDiverRegisterForClass($mysqli, $diverID, $class, $time)
{
    $canRegister = true;
    $query = "SELECT class, time FROM registration WHERE diverID = '$diverID'";

    $result = $mysqli->query($query);

    if ($result && $result instanceof mysqli_result) {
        foreach ($result->fetch_all() as $r) {
            if ($r[0] == $class) {
                return false;
            }
            if ($r[1] == $time) {
                return false;
            }
        }
        return true;
    } else {
        throw new Exception("Error retrieveng results from database!");
    }
}

function registerDiverInClass($mysqli, $diverID, $class, $time)
{
    $query = "INSERT INTO registration (diverID, class, time) VALUES ('$diverID', '$class', '$time')";
    if ($mysqli->query($query)) {
        return true;
    } else {
        return false;
    }
}
于 2012-11-13T18:40:51.290 回答
0

首先让您的选择语句检查重复值,然后插入您的数据,例如:

$duplicateResult=$mysqli->query("SELECT `time`,`user`,`class` FROM `table` WHERE `time`='$time' AND `user`='$user' AND `class`='$class'");
if($duplicateResult->num_rows>=1) {
 //DUPLICATE FOUND
} else {
 //INSERT HERE
}

对不起,如果我没有完全使用你的表结构和查询,但原理是一样的。

于 2012-11-13T18:42:39.797 回答
0

看来,您INSERTING首先是行,然后检查它是否重复。您的插入查询首先出现在代码中,然后执行该检查。取而代之的是,您可以触发类似这样的查询,

$sql = sprintf("SELECT `class` FROM $DBName WHERE `class` = '%s' OR 'time' = '%s'", mysqli_real_escape_string($DiverID,$YouSecondParam)); 
$QueryResult = @mysqli_query($DBConnect, $SQLstring);

然后计算mysql_num_rows()返回的行数

if(mysql_num_rows($QueryResult)>=1){
     //dont insert. 
}else{
    // insert 
}

编辑

好奇,这不是两个查询吗,

$SQLstring = "INSERT INTO $TableName VALUES('$DiverID', '$Class', '$Days', '$Time')";

mysqli_query("INSERT INTO $TableName (`class`, `days`, `time`) VALUES ('".$Class.", ".$Days.", ".$Time."')");

除了带有 sprintf 和其他普通查询的一个之外是相同的吗?

更新

我读了你的代码。该行If ($result = $QueryResult LIKE $Class)必须抛出错误,因为LIKEphp 中没有可以用来比较的东西。取而代之的是,您应该使用

if(mysql_num_rows($QueryResult)>=1){
     //dont insert. 
}else{
    // insert 
}

除此之外,您的代码似乎还可以。还有一件事,您应该$_GET在触发数据库查询之前清理参数。我看到你已经删除了sprintfand mysqli_real_escape_string。最好使用它们。像,

 $Class = mysqli_real_escape_string($DBConnect,$_GET['class']);
 $Days = mysqli_real_escape_string($DBConnect,$_GET['days']);
 $Time = mysqli_real_escape_string($DBConnect,$_GET['time']);
 $diverID = mysqli_real_escape_string($DBConnect,$_GET['diverID']);
于 2012-11-13T18:44:38.743 回答