我试图添加列ID,它将是具有自动增量属性的主键.所以我执行这个SQL查询:
ALTER TABLE `user_info` ADD `id` INT NULL AUTO_INCREMENT PRIMARY KEY FIRST ;
Run Code Online (Sandbox Code Playgroud)
该列已成功创建,甚至为现有数据创建id.
但我不能再在桌子里插入任何东西了.
<?php
require "init.php";
$name=$_POST["user"];
$user_email=$_POST["user_email"];
$user_pass=$_POST["user_pass"];
$sql_query="SELECT * FROM user_info WHERE user_email='$user_email'";
$check=mysqli_fetch_array(mysqli_query($con,$sql_query));
if(isset($check)){
$response["success"]=false;
$response["message"]="Email already exists";
echo json_encode($response);
}else{
$sql_query="insert into user_info values('$name','$user_email','$user_pass');";
if(mysqli_query($con,$sql_query)){
//echo "<h3> Data Insert success</h3>";
$response["success"]=true;
$response["message"]="Registration successful";
echo json_encode($response);
}
else{
$response["success"]=false;
$response["message"]="Registration unsuccessful";
echo json_encode($response);
}
}
?>Run Code Online (Sandbox Code Playgroud)
我google了一下,发现我可以插入0或null代替我的id.
我故意读到:
为了利用列的自动递增功能,在插入行时不要为该列提供值.数据库将为您提供一个值.
当我删除列id时,代码运行良好,但是当我添加它时,我得到响应Registration unsuccessful在我的json中.
我错过了什么?
您现在在表中有四列,但是您只提供三个值.检查mysqli_error会给你一个错误信息,告诉你这个.
您可以更改SQL以为id 创建NULL,这将创建适当的id:
insert into user_info values(null, 'Foo','Foo@example.com','password');
Run Code Online (Sandbox Code Playgroud)
或者,更好的是告诉MySQL您要定位哪些列.这意味着将来如果添加列,SQL将不会中断:
insert into user_info (name,email, password)
values('Foo','Foo@example.com','password');
Run Code Online (Sandbox Code Playgroud)
注意:您的代码存在一些问题.您很容易受到SQL注入攻击 - 如果有人发送恶意值,它可能会运行您不想要的SQL命令.
另外,以纯文本格式存储密码不是一个好主意.您应该使用安全算法对它们进行散列.请参阅:http://php.net/manual/en/faq.passwords.php
| 归档时间: |
|
| 查看次数: |
137 次 |
| 最近记录: |