2017-06-06 112 views
-2

我有一個註冊頁面,它與下面的這個process.php代碼綁定在一起。當我運行這個代碼時,它返回「Error」。我在某個地方犯了錯嗎?PHP&MySQL註冊頁面

<?php 
require_once ('newmeowconnection.php'); 
if (isset($_POST['form_input']) && $_POST['form_input'] == 'registration') { 
    registerUser(); 
} 
function registerUser() { 
    $query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) 
    VALUES('{$_POST['first_name']}','{$_POST['last_name']}','{$_POST['email']}', '{$_POST['password']}', NOW(), NOW())"; 
    $run = mysqli_query($query); 
    if ($run) { 
     $_SESSION['loggedin'] = TRUE; 
     $_SESSION['user'] = $_POST['email']; 
     header('Location: http://localhost/homepage.php'); 
    } else { 
     echo 'Error'; 
    } 
} 
?> 
+1

您的代碼很容易受到[** SQL注入**](https://en.wikipedia.org/wiki/SQL_injection)攻擊。你應該使用[** mysqli **](https://secure.php.net/manual/en/mysqli.prepare.php)或[** PDO **](https://secure.php.net/ manual/en/pdo.prepared-statements.php)準備帶有綁定參數的語句,如[**這篇文章**]所述(https://stackoverflow.com/questions/60174/how-can-i-prevent-sql步噴射功能於PHP)。 –

+1

**從不**存儲純文本密碼。你應該使用['password_hash()'](http://us3.php.net/manual/en/function.password-hash.php)和['password_verify()'](http://us3.php。 net/manual/en/function.password-verify.php)。如果您使用的是5.5之前的PHP版本,請不要**使用MD5或SHA1來散列密碼。相反,您可以使用[此兼容包](https://github.com/ircmaxell/password_compat)。 –

+0

也許不只是echo'ing'錯誤'你應該讓它回聲一些有用的東西像'mysqli_error'。 –

回答

1

mysqli_query需要連接對象上運行,或通過連接到它:

$run = mysqli->query($connection, $query); 

$run = $connection->query($query); 
+0

原始代碼似乎比OO風格更多的是程序風格,我建議您編寫符合作者風格的答案,因爲答案更有意義。 – GrumpyCrouton

+0

當我使用它時,頁面是空白的,甚至沒有出現「錯誤」。當然,我的數據庫也沒有更新。 :/ – Mia

+0

請在你的問題中添加包含mysqli連接的** newmeowconnection.php **文件的內容。我的代碼只顯示如何使用mysqli查詢! –

0

問題是你是使用單引號,裏面的單引號。例如'{$ _POST ['first_name']}'被讀爲{$ _POST [first_name作爲一個SQL變量,並且]另一個字符串。

請嘗試以下

... 

$first_name = $_POST['first_name']; 
$last_name = $_POST['last_name']; 
$email = $_POST['email']; 
$password = $_POST['password']; 

$query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES('{$first_name}','{$last_name}','{$email}', '{$password}', NOW(), NOW())"; 

...

+0

我嘗試過,但它仍然導致「錯誤」。 :/ – Mia