2011-10-29 97 views
0

我有一個包含一些信息的數據庫。 (電子郵件地址和姓名)爲什麼不會這個PHP代碼工作?

我有一個表單可以輸入電子郵件,並且我想打印出屬於此電子郵件的名稱。

$test = $_POST['mail']; //the html code works, $test prints out the email given. 

$question = mysql_query("SELECT name FROM mydb WHERE email = '".$_POST['mail']."'")or die(mysql_error()); 

while($foo = mysql_fetch_assoc($question)) 
{ 
echo $test . " - "; 
echo $foo; 
} 

爲什麼不打印出來的名字?到目前爲止,出於某種原因它打印出Array

感謝

+2

mysql_real_escape_string –

回答

5

讀取的mysql_fetch_assoc

手動返回字符串的關聯數組對應於所提取的行。

得到你需要寫的數據$foo['name'];

+0

的感謝!在我閱讀答覆之前,我設法解決了這個問題。你們快,哈哈 –

1

因爲它是一個數組(如mysql_fetch_assoc()所示)(也許爲了避免另一個應用程序可以被SQL注入)。您必須使用索引來訪問單元格的值:

$foo['name'] 
2

請使用佔位符以避免注入攻擊。 mysql_fetch_assoc()mysqli::fetch_assoc是等同的,因爲它們都返回一個關聯數組;我只是發現面向對象的版本更清潔。

<?php 
$stmt = $dbh->prepare("SELECT name FROM mydb WHERE email = ?"); 
if ($stmt->execute(array($_POST['mail']))) { 
    while ($row = $stmt->fetch_assoc()) { 
     echo $test . " - " . echo $foo['name']; 
    } 
} 
?> 
0
$test = mysql_real_escape_string($_POST['mail']); 

$question = mysql_query("SELECT name, foo FROM mydb WHERE email = '$test'")or die(mysql_error()); 

while($foo = mysql_fetch_assoc($question)) { 
echo $test = $foo['name'] ; 
echo $foo = $foo['foo'] ; 
}