我有一个PHP表单,我在其中添加条目到mysql数据库。我试图让php表单上的数字字段自动编号。因此,不必为每个条目自己输入数字,它将自动显示在数字字段框中,然后自动增加到下一个条目的下一个数字。我已将phpmyadmin中的number字段设置为自动增量。如果有人能告诉我如何编码,我真的很感激。
这是我正在使用的php代码和html。
php代码
<html>
<head>
<title>Add Data</title>
</head>
<body>
<?php
//including the database connection file
include_once("config.php");
if(isset($_POST['Submit'])) {
$Number = $_POST['Number'];
$Link = $_POST['Link'];
$Article = $_POST['Article'];
$Date = $_POST['Date'];
$Name = $_POST['Name'];
// checking empty fields
if(empty($Number) || empty($Link) || empty($Article) || empty($Date) || empty($Name)) {
if(empty($Number)) {
echo "<font color='red'>Number field is empty.</font><br/>";
}
if(empty($Link)) {
echo "<font color='red'>Link field is empty.</font><br/>";
}
if(empty($Article)) {
echo "<font color='red'>Article field is empty.</font><br/>";
}
if(empty($Date)) {
echo "<font color='red'>Date field is empty.</font><br/>";
}
if(empty($Name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
//link to the previous page
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} else {
// if all the fields are filled (not empty)
//insert data to database
$sql = "INSERT INTO crypto(Number, Link, Article, Date, Name) VALUES(:Number, :Link, :Article, :Date, :Name)";
$query = $dbConn->prepare($sql);
$query->bindparam(':Number', $Number);
$query->bindparam(':Link', $Link);
$query->bindparam(':Article', $Article);
$query->bindparam(':Date', $Date);
$query->bindparam(':Name', $Name);
$query->execute();
// Alternative to above bindparam and execute
// $query->execute(array(':Number' => $Number, ':Date' => $Date, ':Name' => $Name, ':Link' => $Link, ':Article' => $Article));
//display success message
echo "<font color='green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}
?>
</body>
</html>
html代码
<html>
<head>
<title>Add Data</title>
<!-- append ?v=2 to icon url -->
<link rel="shortcut icon" href="/logo.jpg">
<link rel="apple-touch-icon" href="/logo.jpg" />
</head>
<body>
<a href="index.php">Home</a>
<br/><br/>
<form action="add.php" method="post" name="form1">
<table width="25%" border="0">
<tr>
<td>Number</td>
<td><input type="text" name="Number"></td>
</tr>
<tr>
<td>Link</td>
<td><input type="text" name="Link" style="width: 450px;" /></td>
</tr>
<tr>
<td>Article</td>
<td><input type="text" name="Article" style="width: 800px;" /></td>
</tr>
<tr>
<td>Date</td>
<td><input type="text" name="Date"></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="Name"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Add"></td>
</tr>
</table>
</form>
</body>
</html>
答案 0 :(得分:2)
您没有自动增量的主键,您可以创建一个(或直接在create table中创建)
ALTER TABLE crypto CHANGE Number Number INT(10) AUTO_INCREMENT PRIMARY KEY;
然后你插入不需要这个列)因为是自动管理的,但只是
$sql = "INSERT INTO crypto(Link, Article, Date, Name)
VALUES(:Link, :Article, :Date, :Name)";