2016-03-18 68 views
1

我试图添加列ID将是一个主键与自动递增属性。所以我执行这个SQL查询:添加列ID到现有的表

ALTER TABLE `user_info` ADD `id` INT NULL AUTO_INCREMENT PRIMARY KEY FIRST ; 

该列已成功创建,甚至为已存在的数据创建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)){ 
 
\t $response["success"]=false; 
 
\t $response["message"]="Email already exists"; 
 
\t echo json_encode($response); 
 
}else{ 
 

 
\t $sql_query="insert into user_info values('$name','$user_email','$user_pass');"; 
 

 
if(mysqli_query($con,$sql_query)){ 
 
\t //echo "<h3> Data Insert success</h3>"; 
 
    $response["success"]=true; 
 
\t $response["message"]="Registration successful"; 
 
\t echo json_encode($response); 
 
} 
 
else{ 
 
\t $response["success"]=false; 
 
\t $response["message"]="Registration unsuccessful"; 
 
\t echo json_encode($response); 
 
} 
 

 
} 
 

 

 

 

 
?>

我用Google搜索了一圈,发现了,我可以在我的地方身份证插入0或空的。

我故意阅读:

为了利用该列的自动递增的能力优势,将排在该列不提供值。数据库将为您提供一个值。

代码运行良好,当我放弃列ID,但是当我添加它,我得到响应作为Registration unsuccessful在我的JSON。

herehere解决方法似乎没有解决我的问题。

我在想什么?

+1

我不知道我正在读取sql,但不应该为ID列允许NULL值。 – jeroen

回答

6

现在表格中有四列,但您只提供了三个值。检查mysqli_error会给你一个错误消息告诉你这一点。

你可以改变你的SQL发送NULL为其创建一个适当的ID与id:

insert into user_info values(null, 'Foo','[email protected]','password'); 

,或者甚至更好是告诉MySQL你的目标的列。这意味着在未来,如果你添加列的SQL不会打破:

insert into user_info (name,email, password) 
values('Foo','[email protected]','password'); 

注:有一些问题与您的代码。你很容易被SQL注入 - 如果有人发送恶意值,它可能会运行你不打算的SQL命令。
另外以明文形式存储密码不是一个好主意。您应该使用安全算法对它们进行哈希处理。请参阅:http://php.net/manual/en/faq.passwords.php

+0

我只是想了解php-mysql整合,因为我刚开始。谢谢你的帮助。 –

+0

我要处理哈希密码,但是sql注入呢? –

+0

通过使用[mysqli_real_escape_string](http://php.net/manual/en/mysqli.real-escape-string.php)或使用[Prepared Statements](http://php.net/manual/en/) mysqli.quickstart.prepared-statements.php)。 – Jim

1

INSERT语法是正确的,你加在首位的ID列前:

$sql_query="insert into user_info values('$name','$user_email','$user_pass');"; 

但现在你应该到VALUES事先指定列:

$sql_query="insert into user_info (name,email, password) values('$name','$user_email','$user_pass');";