我正在使用eclipse kepler进行编码。我使用java servlet和MySQL来存储数据(分配要求的一部分)。我遇到了add.php文件的问题,我创建该文件是为了使用JavaScript将数据插入到数据库中,并将其引导到servlet。我还在页面上有PHP代码,用于显示数据库中的数据。问题是,PHP代码正在显示但未执行。如果我通过http://localhost/e-RMS/WebContent/add.php运行它,PHP将执行但servlet不会执行(不将数据添加到DB)。它反过来了。如果我使用http://localhost:8080/e-RMS/add.php(从eclipse运行Apache tomcat v7)它将运行servlet但只打印出PHP代码而不执行它。我安装了PHP PDT,解释器设置为5.4版,但仍无效。
add.php代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add table</title>
</head>
<body>
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'resto';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT table_No, pax_No FROM reserve";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while ($row = $result ->fetch_assoc()) {
echo "tableNo.: ".$row["table_No"]. " paxNo.: " .$row["pax_No"]." <br>" ;
}
} else {
echo "no result";
}
$conn->close();
?>
<form method="post" action="add">
<label for="studentName">Table No.</label>
<input type="text" id="tableNo" name="tableNo"/>
<br/>
<label for="studentID">pax amount:</label>
<input type="text" id="paxNo" name="paxNo"/>
<br/>
<input type="submit" />
</form>
</body>
</html>
请注意,我不允许使用PHP来插入我的数据。我必须使用servlet。是否可以使用Jscript从我的数据库中检索数据?
编辑:INSERT语句在servlet中
//connect to DB
Connection conn = null;
String db = "jdbc:mysql://localhost:3306/resto";
String db_driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try {
Class.forName(db_driver);
conn = DriverManager.getConnection(db, user, pass);
PreparedStatement stmt = conn.prepareStatement("insert into reserve(table_No, pax_No) values(?,?)");
stmt.setInt(1, tableNo);
stmt.setInt(2, paxNo);
stmt.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}