2011-06-06 113 views
0

任何人都可以告訴我如何將PHP值$ value_aid和$ value_tradeid傳遞給我的sql查詢res3嗎?將變量從php傳遞到mysql查詢和顯示

<?php 
//error_reporting(E_ALL); 

///////////////////////Connect to the database and close the connection when finished/////////////////////////////// 

include ("dbconnect.php"); 

///////////////////////////////// Gather and Display area_id ////////////////////////////// 

$res=mysql_query("SELECT area_id FROM pc_test WHERE postcodes = '".$_POST['postcode']."'"); 
while ($row = mysql_fetch_array($res)) 
{ 
// This works !! 
//echo("$row[area_id]"); 
$value_aid="$row[area_id]"; 
echo("$value_aid"); 
} 

////////////////// Gather and Display postcodes relating to area_id //////////////////////// 

$res3=mysql_query("SELECT trade_id FROM trade WHERE trade_type = '".$_POST['trade_type']."'"); 
while ($row3 = mysql_fetch_array($res3)) 
{ 
// And this works !! 
echo("\n$row3[trade_id]"); 
$value_tradeid="$row3[trade_id]"; 
} 

/**************************************** Gather the query information ********************************************/ 

//************!!!!!!!!!!!!!!!! This part does not work as the variable values are not being passed !!!!!!!!!!!**********// 

$res2=mysql_query("SELECT first_name, last_name, phone_mobile, postcode, trade_type FROM customer WHERE area_id = '$value_aid' && trade_id = '$value_tradeid'"); 

/**************************************** DISPLAY QUERY RESULTS HERE *********************************************/ 
while ($row2 = mysql_fetch_array($res2)) 

{ 

echo("<TABLE align='center' border = '1' bgcolor = 'A7E3F6'><TH><strong>SEARCH RESULTS<strong></TH>"); 
echo("<TR><TD><strong>Name :<strong>\n$row2[first_name]\n$row2[last_name]</TD></TR>"); 
echo("<TR><TD><strong>Phone :<strong>\n$row2[phone_mobile]</TD></TR>"); 
echo("<TR><TD><strong>Postcode :<strong>\n$row2[postcode]</TD></TR>"); 
echo("<TR><TD><strong>Trade Type :<strong>\n$row2[trade_type]</TD></TR></TABLE>"); 
} 

/*********************** If no matching records in my table...DISPLAY MESSAGE HERE ******************************/ 

if (mysql_num_rows($res2) == 0) { 

echo ("<strong><br><br>No one is advertising for this area just yet, sorry.<br>We will have tradesmen advertising here very soon.</strong>"); 
} 

//include ("db_close.php"); 

?> 
+1

請考慮使用[PDO](http://php.net/manual/en/book.pdo.php)或事先轉義您的值。你有一個SQL注入漏洞 – JohnP 2011-06-06 10:34:42

+0

你的問題是$ res3和$ res是表。考慮在循環中運行或準備sql查詢。 – 2011-06-06 10:37:49

回答

0

首先,不要傳給你從用戶那裏得到的變量(彥博,_GET,...)直接進入數據庫查詢沒有逃脫他們(比如mysql_escape_string($ _ POST [「名」])這將導致大量的安全問題(SQL注入)

的變量分配與您只需使用一個諾特爾變量的值:

$value_tradeid = $row['trade_id']; 

變量犯規需要被膠囊包裹的字符串,但數組的鍵都應該

在不工作的查詢中,爲什麼不逃避字符串,就像你在其他人做過的事情一樣。

$res2=mysql_query("SELECT first_name, last_name, phone_mobile, postcode, trade_type FROM customer WHERE area_id = '".$value_aid."' && trade_id = '".$value_tradeid."'"); 

您還應該閱讀關於PDO和準備好的陳述。