2012-12-06 70 views
-1

如果任何人都可以爲我提供合適的代碼,那就太棒了。我試圖做的是在正在回顯的信息之後添加一個<hr />,如果從我的數據庫中拉出多個結果。如果有人能幫助我,這裏是代碼。謝謝。if function placement

<html> 
<script> 
function goBack() 
    { 
    window.history.back() 
    } 
</script> 
<body> 
<div style="width: 875px; margin-left: 30px; margin-right: auto;"><img   src="searchresults.png" alt="" title="Search Results" alt="" /></p> 
<?php 


$term = $_POST['term']; 

$sql = mysql_query("SELECT * FROM store_location where store_name like '%$term%' or  address like '%$term%' or city like '%$term%' or state like '%$term%' or zip like  '%$term%' or phone like '%$term%' or fax like '%$term%' or email like '%$term%' or url  like '%$term%' "); 

    if(mysql_num_rows($sql) == 0) echo "<p>No TeachPro Store(s) in your area.</p>"; 

    while ($row = mysql_fetch_array($sql)){ 

echo 'Store Name: '.$row['store_name']; 
echo '<br/> Address: '.$row['address']; 
echo '<br/> City: '.$row['city']; 
echo '<br/> State: '.$row['state']; 
echo '<br/> Zip: '.$row['zip']; 
echo '<br/> Phone: '.$row['phone']; 
echo '<br/> Fax: '.$row['fax']; 
echo '<br/> Email: <a href="mailto:'.$row['email'].'">'.$row['email'].'</a>'; 
echo '<br/> URL: <a href="'.$row['url'].'">'.$row['url'].'</a>'; 
echo '<br/><br/>'; 
} 
?> 
</div> 
<input type="button" value="Back" onclick="goBack()"> 
</body> 
</html> 
+0

因此,您真的應該在擔心hr標籤之前清理您的用戶輸入。看看這個:http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php – span

+0

另一個腳本可以攻擊 – 2012-12-06 21:41:31

+0

@Dagon一位同事不相信上週我發現我每天看到的大多數PHP腳本都很脆弱。 –

回答

1

只是包裝你while循環在else情況下,輸出的<hr>在那裏。如果沒有找到行,您已經有適當的邏輯來輸出<p>,並且可以擴展它。

if(mysql_num_rows($sql) == 0) { 
    echo "<p>No TeachPro Store(s) in your area.</p>"; 
} 
// Instead of relying on an empty fetch to output nothing, put it in an else {} 
else { 
    while ($row = mysql_fetch_array($sql)){ 
    echo 'Store Name: '.$row['store_name']; 
    echo '<br/> Address: '.$row['address']; 
    echo '<br/> City: '.$row['city']; 
    echo '<br/> State: '.$row['state']; 
    echo '<br/> Zip: '.$row['zip']; 
    echo '<br/> Phone: '.$row['phone']; 
    echo '<br/> Fax: '.$row['fax']; 
    echo '<br/> Email: <a href="mailto:'.$row['email'].'">'.$row['email'].'</a>'; 
    echo '<br/> URL: <a href="'.$row['url'].'">'.$row['url'].'</a>'; 
    echo '<br/><br/>'; 
    } 
    // And your <hr /> and whatever else you need... 
    echo "<hr />"; 
} 

剛想HTML輸出一個側面說明 - 一定要在htmlspecialchars()包裹這些數值進行適當的轉義爲HTML,爲了避免出現問題,如果它們包含HTML特殊字符,如< > &(也可能是防止XSS,如果這是用戶輸入!)

// Ex: 
echo 'Store Name: '.htmlspecialchars($row['store_name']); 

而更爲嚴峻的是mysql_real_escape_string()消毒針對SQL注入您的查詢輸入。

// At a minimum: 
$term = mysql_real_escape_string($_POST['term']); 

從長遠來看,考慮切換到支持預備語句的API,如MySQLi或PDO。