2017-02-07 65 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' - 如果(很有可能)是一個字符串;它會失敗。 –

相關問題