编辑:更新!第一部分工作了。但是,我不确定如何在同一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>
答案 0 :(得分:1)
请注意
只是旁注,在PHP中,按惯例,变量以小写字母开头,而不是以大写字母char开头的类和接口。另外,如果您愿意,请阅读这些标准(PSR)。 those are the standards I adopt
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;
}
}
答案 1 :(得分:0)
首先让你的select语句检查重复值然后插入你的数据,例如:
$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
}
很抱歉,如果我没有使用你的表结构和查询,但原理是一样的。
答案 2 :(得分: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)
必须抛出错误,因为在php中没有可用于比较的LIKE
。而不是那样,你应该使用
if(mysql_num_rows($QueryResult)>=1){
//dont insert.
}else{
// insert
}
除此之外你的代码似乎没问题。还有一件事,您应该在触发数据库查询之前清除$_GET
个参数。我发现您已删除sprintf
和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']);