Is there any way to prevent sql injections in our codes?? suppose if any users put ' index.php?id='12 instead of index.php?id=12 how can we give them some sort of error message or redirect to other page? is there any way?
check out http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php There is some built in mysql functions to help you out. Lance
If you'll only be dealing with numbers, you can use the intval() to clean the data, or is_numeric() to determine if it's valid.
i had used "mysql_real_escape_string()" but when users type index.php?id='12 then the page dont show anything... i wanna display message something like : the ID doesnt exists or something else....
As said above, you need to first handle the variables each by type. So, when the input should be integer, you can use the intval() function. When it is text with no html allowed, you can use strip_tags(). And so on. This is step 1.
<? $nid=intval(mysql_real_escape_string($HTTP_GET_VARS['id'])); include 'connect.php'; $news = mysql_query("SELECT * FROM news where id = '$nid'"); $count = mysql_num_rows($news); if(!$count == 0){ while($row = mysql_fetch_array($img)){ $n_id = $row["id"]; $short_news=$row["short_news"]; $full_news = $row["full_news"]; echo $short_news; echo "<br>"; echo $full_news; } <? } else { echo "Sorry the news you are trying to view doesn't exists."; } ?> Code (markup): i used this but it doesnt shows me error message... and YES i am only dealing with the numbers in ID field....... how can this be remove....
Now you should start tracing Replace this: $news = mysql_query("SELECT * FROM news where id = '$nid'"); with: $news = mysql_query("SELECT * FROM news where id = '$nid'") or die(mysql_error()); to see what is wrong.
i did that but ...man, it doesnt show any error messages? i am testing in my personal web server (IIS)... doesnt show the error, m confused... what am i facing??
well if i replaced that then it shows error like: Warning: mysql_connect(): Access denied for user: 'root@localhost' (Using password: YES) in C:\connect.php on line 8 in connect.php: <? $user="root"; $pwd="123"; $db="news"; $host="localhost"; $conn=mysql_connect ($host, "$user", "$pwd") or die ("<font color=\"red\">".'~ Database Connection Error [Plz inform Kanchan] ~'."</font>"); mysql_select_db ($db); ?> Code (markup):
OK I was just checking out if the connection has an issue. Now try this: <? $nid=intval($_GET['id']); include 'connect.php'; $news = mysql_query("SELECT * FROM news where id = $nid"); $count = mysql_num_rows($news); if($count <> 0){ while($row = mysql_fetch_array($news)){ // this was $img I don't know why! $n_id = $row["id"]; $short_news=$row["short_news"]; $full_news = $row["full_news"]; echo $short_news; echo "<br>"; echo $full_news; } <? } else { echo "Sorry the news you are trying to view doesn't exists."; } ?> PHP: