我有一个表单,其中有一个名为索引的字段。我想要做的是自动生成索引号,如下所示。
ex: option1_01 , option2_01 , option1_02 .. etc
option1
基于下拉选择。 _01
来自数据库,使用表 option1
的最后一个 id 号。
这是我的form.php
<body>
<form id="" method="post" action="send.php">
<select name="name" id="name">
<option value="">please select</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
</select><br>
<label for="index">Index</label>
<input type="text" id="index" name="index" readonly="readonly" value=""/><br>
<label for="fname">fname</label>
<input type="text" name="fname"/><br>
<label for="lname">lname</label>
<input type="text" name="lname"/><br>
<label for="age">age</label>
<input type="text" name="age"/>
<button name="submit">sumit</button>
</form>
</body>
我还有两个表来插入数据。当我们选择option1
时,其余详细信息应进入option1
表。
db.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "testing01";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully <br/>";
?>
这是我的 jquery 代码
$(document).ready(function() {
$("#name option").filter(function() {
return $(this).val() == $("#index").val();
}).attr('selected', true);
var index1 = $("#index").val();
$("#name").on("change", function() {
$.ajax({
url:'table.php',
type:'post',
data:{index1:index2},
success:function(){
$("#index").val($(this).find("option:selected").attr("value"));
}
});
});
});
table.php
<?php
$index2 = $_POST['index2'];
include("db.php");
$sql = "SELECT MAX(id) FROM ".$index2." ";
$res = mysqli_query($conn,$sql);
$get = mysqli_fetch_array($res);
$next_id = $get['MAX(id)'] + 1;
}
?>
send.php
<?php
if(isset($_POST['submit'])){
$option=$_POST['name'];
$index=$_POST['index'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$age=$_POST['age'];
include('db.php');
if($option=="option1"){
$result1=mysqli_query($conn,"INSERT INTO option1(options,fname,lname,age) VALUES('$option','$fname','$lname','$age');");
if($result1){
echo "data inserted to option1 table";
}
}
if($option=="option2"){
$result2=mysqli_query($conn,"INSERT INTO option2(options,fname,lname,age) VALUES('$option','$fname','$lname','$age');");
if($result2){
echo "data inserted to option2 table";
}
}
}
?>
我认为我在 $ajax 代码片段中遇到了问题。它将 index2
变量传递到 table.php
中。但我无法返回 $next_id
因为我是 jquery 新手。
有人帮我解决这个问题吗?
最佳答案
在查询中使用别名MAX(id)作为maxId
来获取记录。
Table.php
<?php
$index2 = $_POST['index2'];
include("db.php");
$sql = "SELECT MAX(id) as maxId FROM ".$index2." ";
$res = mysqli_query($conn,$sql);
$get = mysqli_fetch_array($res);
$next_id = $get['maxId'] + 1;
}
?>
关于php - 如何根据数据库中最后一个ID的下拉选择自动生成ID号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40603569/