Jump to content

querystrings


davids_media

Recommended Posts

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

Link to comment
Share on other sites

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";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.