davids_media Posted April 5, 2012 Share Posted April 5, 2012 Below is my code to retrieve data and display it; [code]<?php error_reporting(E_ALL ^ E_NOTICE); ini_set("display_errors", 1); require ('includes/config.inc.php'); include ('./includes/header.html'); require (MYSQL); include ('./includes/main.html'); $q = "SELECT catID, cat FROM category"; $r = mysqli_query($dbc, $q); if (!$r) die ("No Access" . mysqli_error($dbc)); $rows = mysqli_num_rows($r); for ($j = 0 ; $j < $rows ; ++$j) { $row = mysqli_fetch_row($r); echo '<div id="right">'; echo '<h1>'. $row[1] . '</h1>' . '<br />'; echo '<br />'; echo '</div>'; } include ('./includes/footer.html'); ?> [/code] Now, what I want to do is create an SQL injection attack free querystring, so when the user types in this; cat.php?id=1 they get this data displayed; catID: 1 cat: Flowers could anyone please help me on this, as I am really struggling to come up with a solution Quote Link to comment Share on other sites More sharing options...
The Little Guy Posted April 5, 2012 Share Posted April 5, 2012 // Your code above $id = (int)$_GET['id']; $q = "SELECT catID, cat FROM category where catID = $id"; // Your code below Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 5, 2012 Share Posted April 5, 2012 I agree with The Little Guy's solution, but I wanted to comment on part of your current code above: $rows = mysqli_num_rows($r); for ($j = 0 ; $j < $rows ; ++$j) { $row = mysqli_fetch_row($r); echo '<div id="right">'; echo '<h1>'. $row[1] . '</h1>' . '<br />'; echo '<br />'; echo '</div>'; } That is an inefficient solution. No need to calculate the number of rows and then create a for loop. Instead, just use a while loop. That is the standard for extracting the records from a query result. Also, I would highly advise using mysqli_fetch_assoc() to get the fields by name instead of the numeric index. If you make changes to the DB structure or queries later you will have a lot of code that needs to be "fixed" if you use the numeric index rather than the name. I also changed the output to use double quotes for the string delimiter so you can add linebreaks to the HTML output. Makes a world of difference when debugging the HTML output. while($row = mysqli_fetch_assoc($r)) { echo "<div id='right'>\n"; echo "<h1>{$row['cat']}</h1><br /><br />\n"; echo "</div>\n"; } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.