2014-01-05 66 views
0

你好,我是一般的PHP和MySQL新手。但我有一個問題這裏是我的問題:

我想插入數據到數據庫使用窗體。
但是當我這樣做時,它會在用戶名密碼列中返回1。

這裏是我的index.php:

<?php 

$host = 'localhost'; 
$dbname= 'akar'; 
$user = 'akar'; 
$pass = 'raparen'; 

$dsn = "mysql:host=$host;dbname=$dbname"; 
$pdo = new PDO($dsn,$user,$pass); 

$username = isset($_POST['username']); 
$password = isset($_POST['password']); 



    $query = "INSERT INTO users (username,password) VALUES(:username,:password)"; 
    $statement = $pdo->prepare($query); 
    $statement->execute(array(
     ':username'=> $username, 
     ':password'=> $password 
    )); 

?> 

這裏是我的形式:

<form action='index.php' method='post'> 

<input type='text' placeholder='Enter Username here!' name='username' /> 
<input type='password' placeholder='Enter Password here!' name='password' /> 
<input type='submit' value='Submit' /> 

當我這樣做:

$username = $_POST['username']; 

它工作正常,但當我這樣做:

$username = isset($_POST['username']); 

它在數據庫中插入1,而不是輸入中的文本。

對不起,如果我組織任何東西,我是新手。

回答

5

isset()返回一個布爾值,該值是被設置或不被設置的變量的結果。它不用於從變量中獲取值。

$username = isset($_POST['username']); 
$password = isset($_POST['password']); 

應該是:

$username = $_POST['username']; 
$password = $_POST['password']; 

或者,如果你想,如果這些變量沒有被設置爲指定一個默認值,你會做這種方式:

$username = isset($_POST['username']) ? $_POST['username'] : ''; 
$password = isset($_POST['password']) ? $_POST['password'] : ''; 
+0

它索引什麼索引爲undefined? – Zarathuztra

+0

非常感謝,它工作!謝謝你們的幫助! – Akar

4

這是因爲isset返回true如果var存在且其值不爲NULL,否則返回false。文檔中的「返回值」:

如果var存在且值不爲NULL,則返回TRUE,否則返回FALSE 。

這樣做$username = isset($_POST['username']);,你要分配的isset$username返回值是什麼是會得到存儲在數據庫中。

你應該做的是:

if (isset($_POST['username'])) { 
    $username = $_POST['username']; 
} 

所以您分配只有$_POST['username']被設定的$_POST['username']值。

+0

最後一個片段會在查詢中留下未定義的變量錯誤。 –

+0

感謝您的回答! – Akar

0
try { 
    $statement = $pdo->prepare($query); 

    $statement->bindValue(「:username」, $username, PDO::PARAM_STR); 
    $statement->bindValue(「:password」, $password, PDO::PARAM_STR); 

    $statement->execute(); 
} catch (PDOException $e) { 
echo 「Query failed: 「 . $e->getMessage(); 
} 
相關問題