简体   繁体   English

php html 中的呼叫 ID 号(AUTO_INCREMENT 和自动生成)

[英]Call ID number (AUTO_INCREMENT and Auto Generate) in php html

I just started to learn php and in this code i want to auto generate an id number and call it我刚开始学习 php 并且在这段代码中我想自动生成一个 ID 号并调用它

Here is my code for creating table:这是我创建表的代码:

<?php
$link = mysqli_connect("localhost","root","","demo");
$sql="CREATE TABLE persons(first_name VARCHAR(30) NOT NULL, id INT (1) NOT NULL PRIMARY KEY 
AUTO_INCREMENT)";
if(mysqli_query($link,$sql))
        { echo "Table created successfully.";}
mysqli_close($link);
?>

Code for adding values and i want to call the value of my id number and display it here but i dont know how.添加值的代码,我想调用我的 id 号码的值并在此处显示它,但我不知道如何。

<!DOCTYPE html>
<html>
<body>
<form action="insert.php" method="post">
First name: <input type="text" name="first_name">
ID no: <name="id">
<input type="submit" value="Submit Form">
</body>
</html>

Code for inserting the values:插入值的代码:

<html>
<?php 
$link = mysqli_connect("localhost", "root", "", "demo"); 
$first_name = mysqli_real_escape_string($link, $_REQUEST['first_name']); 
$id = mysqli_real_escape_string($link, $_REQUEST['id']); 
$sql = "INSERT INTO persons (first_name,id)
VALUES('$first_name','$id')";
mysqli_close($link); ?>
</html>

your code is vulnerable to sql injection, but if you want auto increment an id manually by php or add automatic unique value you can do checking the last id that given and add + 1 to last id.您的代码容易受到 sql 注入的攻击,但是如果您想通过 php 手动自动增加 id 或添加自动唯一值,您可以检查给定的最后一个 id 并将 + 1 添加到最后一个 id。

it will be like它会像

    <?php
       $link = mysqli_connect("localhost", "root", "", "demo"); 
       $idGet = "SELECT * FROM persons ORDER BY id DESC LIMIT 1";
       $idVal = mysqli_query($link,$idGet);
       if(mysqli_num_rows($idVal)>0){
         $id = mysqli_fecth_assoc($idVal);
         $lastid = $id["id"]+1;
         
       }else{
         $lastid  = 0;
       };

       $first_name = mysqli_real_escape_string($link,htmlspecialchars($_REQUEST['first_name']));
       $insertGet = "INSERT INTO persons (first_name,id) VALUE('$first_name','$lastid')";
       $insertVal = mysqli_query($link, $insertGet);
    ?>

you can modified the code as you need您可以根据需要修改代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM