2013-10-01 73 views
0

我有一個註冊頁面,它將註冊數據插入數據庫。 它去沿着這行:插入mysqli

if ($_POST['password'] == $_POST['conf_pass']){ 
     $user = $_POST['username']; 
     $pass = $_POST['password']; 

     $hash = md5(rand(0,1000)); 

     $accres = mysqli_query($connection, "INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)"); 
     $account_id = mysqli_insert_id($accres); 
     $peopleres = mysqli_query($connection, "INSERT INTO people (lastname, firstname, accounts_id, birthdate, phonenumber, username, password, email, hash) VALUES($lastname, $firstname, $account_id, $birthdate, $phonenumber, $username, $password, $email, $hash)"); 

     $peoplerows=mysqli_fetch_assoc($peopleres); 
     $person_id=$peoplerows[0]; 

     mysqli_query("INSERT INTO PeopleToRole (role_id) VALUES(1)"); 
     $email = $_SESSION['email']; 
     $p->addContent("User Registered"); 
} 

我原先編程的所有本使用的是Postgres的(而Apache服務器上本地託管),但不得不改變到mysqli的,因爲主機的網站已經與mysqli的工作。

因此,此代碼返回頁面上註冊的用戶,因此if語句正在工作。但由於某些原因,insert語句不會在數據庫中插入任何內容。

我有某種格式錯誤嗎?或者我錯過了一些小東西? 任何和所有的幫助,將不勝感激。 感謝

+2

使用佔位符。你的數據很容易被sql注入!檢查錯誤!它會告訴你到底發生了什麼錯誤(哪些是你的變量沒有被引用。) – Cfreak

+0

「我有某種格式錯誤嗎?或者我錯過了一些小東西?」這裏是一個不重要的問題,請介意。 –

+0

如果代碼與Postgres而不是mySql一起工作,則可能是某種數據庫設置問題。檢查賬戶,權限,錯誤日誌等。 –

回答

1

一個共同的問題:你不打擾檢查您的查詢的錯誤,所以出問題的時候你不知道發生了什麼事。

檢查返回值mysqli_query()對於FALSE,如果找到它,請檢查mysqli_error($connection)以獲取錯誤消息。

例如:

$accres = mysqli_query($connection, "INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)"); 
if ($accres === false) {die(mysqli_error($connection));} 

做其他查詢類似的東西。當你有錯誤信息時,修復它,或者回來再問一次。

+0

downvoter是否會關注評論? – 2013-10-01 01:43:15

3

你忘了在查詢中的行情,例如,你應該改變:

"INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)" 

到:

"INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES('$address', '$suburb', '$city', '$postcode', '$username')" 

這就是說,這樣使你的代碼容易受到SQL注入的工作(如cfreak在上面的評論中提到)。

下面是the manual一個小例子,顯示瞭如何使用bind_param()使代碼更安全:

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world'); 

/* check connection */ 
if (mysqli_connect_errno()) { 
    printf("Connect failed: %s\n", mysqli_connect_error()); 
    exit(); 
} 

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)"); 
$stmt->bind_param('sssd', $code, $language, $official, $percent); 

$code = 'DEU'; 
$language = 'Bavarian'; 
$official = "F"; 
$percent = 11.2; 

/* execute prepared statement */ 
$stmt->execute(); 

printf("%d Row inserted.\n", $stmt->affected_rows); 

/* close statement and connection */ 
$stmt->close(); 
+0

Downvoter - 關注評論? – alfasin

+1

我不是downvoter,爲什麼甚至提到第一個不正確的查詢方式的修改? mysqli的全部要點是使用預準備語句來避免SQL注入。 – user113215

+0

@ user113215當我提供的答案我喜歡涵蓋一切...;) – alfasin