2014-01-15 25 views
0

我在「SELECT * FROM table LIMIT'中插入$ q時出現問題」$ q。「'」;在ajax和mysql中的限制

HTML代碼: 保存在「ajax.php」文件中的html代碼。

<html> 
<head> 
<script> 
function showUser(str) 
{ 
if (str=="") 
    { 
    document.getElementById("txtHint").innerHTML=""; 
    return; 
    } 
if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText; 
    } 
    } 
xmlhttp.open("GET","getuser.php?q="+str,true); 
xmlhttp.send(); 
} 
</script> 
<meta charset="utf-8"> 
</head> 
<body> 

<form> 
<select name="users" onchange="showUser(this.value)"> 
<option value="">Select a person:</option> 
<option value="1">Peter Griffin</option> 
<option value="2">Lois Griffin</option> 
<option value="3">Glenn Quagmire</option> 
<option value="4">Joseph Swanson</option> 
</select> 
</form> 
<br> 
<div id="txtHint"><b>Person info will be listed here.</b></div> 

</body> 
</html> 

和PHP代碼: 與HTML代碼相同的目錄保存在 「getuser.php」 這個PHP代碼。

<?php 
$q = intval($_GET['q']); 
$m = 2; 

$con = mysqli_connect('localhost','root','','net'); 

mysqli_select_db($con,"members"); 
$sql="SELECT * FROM members LIMIT '".$q."'"; 

$result = mysqli_query($con,$sql); 

echo "<table border='1'> 
<tr> 
<th>Firstname</th> 
<th>Lastname</th> 
<th>Age</th> 
<th>Hometown</th> 
<th>Job</th> 
</tr>"; 


while($row = mysqli_fetch_array($result)) 
    { 
    echo "<tr>"; 
    echo "<td>" . $row['username'] . "</td>"; 
    echo "<td>" . $row['password'] . "</td>"; 
    echo "<td>" . $row['name'] . "</td>"; 
    echo "<td>" . $row['family'] . "</td>"; 
    echo "<td>" . $row['email'] . "</td>"; 
    echo "</tr>"; 
    } 
echo "</table>"; 

mysqli_close($con); 
?> 
輸出顯示

這messege:

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\php2\admin\test\getuser.php on line 30 

,但是當我插入 「SELECT * FROM成員限制2」 這工作順利

+0

讓我們擺脫明顯的第一個。試試這一行,而不是你所擁有的:'$ sql =「SELECT * FROM members LIMIT」。$ q;'。 – Sebas

回答

1

在SQL查詢你不能逃脫整數值。 我會寫:

$sql = "SELECT * FROM members LIMIT " . (int)$q . ";"; 
+0

你應該考慮註冊用戶。而代碼甚至沒有轉義:它將字符串參數傳遞給LIMIT而不是整數。 – NobleUplift

+0

(int)$ q將字符串轉換爲整數,不需要轉義整數。 – andreaslangsays

+0

我的意思是OP的代碼並不是逃避輸入,OP首先應該被教導。你的解決方案很好。曾經有一個PHP中的錯誤,其中cast(int)1a2b3c4d將導致1234 IIRC,但現在它僅佔用整數的前部分,導致1或0(如果它不是數字)。 – NobleUplift

1

這個代碼是危險的極端你允許任何人以注入到你的數據庫。您需要首先清理變量,如果您只使用雙引號,則不需要對語句進行連接。 $ x woudl會被正確解釋。

function clean_data($string) { 
     $string = trim($string); 
     if (get_magic_quotes_gpc()) { 
      $string = stripslashes($string); 
     } 
     $string = strip_tags($string); 
     return html_entity_decode($string, ENT_QUOTES); 
} 

$x = clean_data($_GET['q'); 
$q = "SELECT * FROM members LIMIT $x"; 
+0

謝謝。問題解決了 –