我想從mysql變量中獲取內容以用於php代碼,實際名稱(遊戲),url(遊戲)和alt(遊戲)。圖片網址和搜索數據庫正在工作。我很感激任何編碼方面的幫助。我不知道如何編寫指向名稱,url和alt的指針。mysql php獲取變量
search_site.php
<link rel="shortcut icon" href="catchamouse3.png">
<link rel="stylesheet" type="text/css" href="homestyles2.css">
<link rel="stylesheet" type="text/css" href="submit.css">
<link rel="stylesheet" type="text/css" href="allflashgames(3).css">
<link rel="stylesheet" type="text/css" href="searchbar.css">
<link rel="stylesheet" type="text/css" href="styles2.css">
<?php
include('func.php');
if(isset($_POST['keywords'])){
$suffix = "";
$keywords = mysql_real_escape_string(htmlentities(trim($_POST['keywords'])));
$errors = array();
if(search_results($keywords) === false){
$errors[] ='<h1>We didn\'t find anything for "'.$keywords.'"</h1>';
}
if(empty($errors)){
$results = search_results($keywords);
$results_num = count($results);
$suffix = ($results_num!=1)?'s':'';
echo '<h1>',$results_num,' item',$suffix,' For "',$keywords,'"</h1>';
foreach($results as $result){
echo '
<span class="overimage">
<a href="$game_url" target="_blank">
<span class="hoverimage">
<span class="hovertext1line-home">',$result['name'],'</span><img class="onlinegameimage-home" src="',
$result['image_url'],'" alt=',$result['alt'],'>
</span>
</a>
</span>
';
}
}
else{
foreach($errors as $error){
echo $error,'<br>';
}
}
}
?>
func.php
<?php
$con = mysql_connect('localhost','root','');
mysql_select_db("my_search_test",$con);
function search_results($keywords){
$returned_results = array();
$where ="";
$keywords = preg_split('/[\s]+/',$keywords);
$total_keywords = count($keywords);
foreach($keywords as $key=>$keyword){
$where .= "`keywords` LIKE '%$keyword%'";
if($key != ($total_keywords -1)){
$where .=" AND ";
}
}
$results = "SELECT name, image_url, game_url, alt FROM search_games WHERE $where";
$results_num = ($results =mysql_query($results))? mysql_num_rows($results):0;
if($results_num === 0){
return false;
}
else{
while($results_row = mysql_fetch_assoc($results)){
$returned_results[] = array(
'image_url' => $results_row['image_url']
);
}
return $returned_results;
}
}
?>
您在此處觸發'search_results($ keywords)'兩次。首先檢查'=== false',然後在if(空($ errors))塊中檢查第二個。這是多餘的。調用'search_results($ keywords)'一次,存儲結果並在需要的地方使用結果。 – Marcus
**警告**:如果您只是學習PHP,請不要學習過時的['mysql_query'](http://php.net/manual/en/function.mysql-query.php)界面。這很糟糕,並且已經在PHP 7中被刪除了。像[PDO不是很難學的東西](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-php-pdo- for-database-access /)以及[PHP The Right Way](http://www.phptherightway.com/)等指南有助於解釋最佳實踐。使用'htmlspecialchars'會損壞用戶數據,並且在插入數據庫時應該使用** not **。每當您在HTML中顯示值時,請使用它。 – tadman