2017-02-07 66 views
0

好吧,我很抱歉 - 我已经花了最后几天的工作,并且Im卡住了......所以我要求提供建议或新的眼睛来帮我在这里...PHP中的Mysql运行一个查询,然后失败第二,

这里的代码已经工作,或者已经在phpMyAdmin的sql部分进行了测试...一些背景,我有一个数据库与两个表,用户和角色。我试图插入一个用户到用户数据库(工作99%的时间...),然后在创建用户后,只要没有错误之前,然后在角色表中创建一个行并设置角色基于用户....似乎很简单,但即使查询工作在phpmyadmin中,并且不会导致问题,每次运行PHP代码都会失败...用户被创建...并且无法访问其余的该网站,除非我手动将它们添加到角色表......我确信你能理解我为什么要当用户创建登录有这种前进...

@ $query = "INSERT INTO users 
(
    Username , Password , pwsecret , emailAddress , Fname , Lname , Joined_Date 
) 
VALUES 
(
    '$uName' , '$encoded', '$salt' , '$email' , '$firstName' , '$lastName', CURRENT_TIMESTAMP 
)"; 

ini_set('display_errors', 'On'); 

if (!mysqli_query($db,$query)){ 
$error_message = "There was a problem when attempting to add you as a user, please try again and if the issue persists please contact the webadmin."; 
//clear vars for reuse:: 
$_POST = array(); //should stop data from persisting. 
$uName = ""; 
$pw1 = ""; 
$pw2 = ""; 
$encoded = ""; 
$email = ""; 
$firstName = ""; 
$lastName = ""; 
include("partial/user/_register.php"); 
exit(); //jic something goes wrong we do not want to have the script resume. 
}else{ 
//the following should add a newly generated user to the roles table. 
$select="(SELECT userID FROM users WHERE Username = $uName)"; //sub query to return a user ID 
$insert="INSERT INTO roles (userID , isAdmin , isMod , isFormerStaff , isUser , isBanned) VALUES ((SELECT userID FROM users WHERE Username = $uName;) , 0 , 0 , 0 , 1 , 0);"; //insert query to add user to roles table 
//I tested this code in mysql phpmyAdmin and it worked with out error... 
if (!mysqli_query($db,$insert)){ 
    echo "User role not created - please add user manually."; 
} 

在第二个查询是有在userID字段中选择语句,这是因为我需要它来获取最后一个注册用户的用户ID,请记住,这是在用户生成后立即运行,并假定桌子很干净。

任何帮助,你们可以显示或问题,将不胜感激源....我知道它的大概的东西,我错过了...但我不能看到它..

杰西·芬德

+2

在多个地方, '用户名= $ uName;'< - 删除分号并在'$ uName'周围加引号,除非这是一个数字。除此之外,你很容易受到SQL注入的影响。请参阅http://stackoverflow.com/q/60174/2191572并祝你好运 – MonkeyZeus

+0

你已经开放SQL注入。由于您使用的是mysqli,请利用[prepared statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)和[bind_param](http://php.net/手动/ EN/mysqli的-stmt.bind-param.php)。 – aynber

+0

而不是做select-inside-the-insert语句,你可以[得到插入id](http://php.net/manual/en/mysqli.insert-id.php)你的第一个插入查询。 – aynber

回答

0

杰西挡泥板,

我已经看到了你写的选择ID声明,但它只是一个简单的字符串格式查询,你是不是通过添加MYSQL_QUERY使其成为一个查询格式($选择)

代码将在MySQL中正常工作,因为有没有必要使用的mysql_query,因为它就像它的查询,但是从PHP,您需要将字符串转换为查询,以便它就像一个查询..

试试这个:

$select="(SELECT userID FROM users WHERE Username = $uName)"; 
$lasid = mysqli_query($db,$select); 

//sub query to return a user ID 
$insert="INSERT INTO roles (userID , isAdmin , isMod , isFormerStaff , isUser , isBanned) VALUES ($lasid , 0 , 0 , 0 , 1 , 0);"; 
mysqli_query($db,$insert); 
if (!mysqli_query($db,$insert)){ 
    echo "User role not created - please add user manually."; 
} 
+1

'WHERE用户名= $ uName' - 如果(很有可能)是一个字符串;它会失败。 –

相关问题