poxin poxin - 5 months ago 12
PHP Question

PHP query single line from database

I'm having a problem echoing a single line from a sql query. I'm still pretty new at this but I can't figure it out at all.

I have a page titled "listing.php?id=7"

Inside the page is this script:

<?php
mysql_connect("localhost", "user", "pass");
mysql_select_db("table");

$query = "SELECT * FROM vehicles WHERE id='$id'";
$result = mysql_query($query);

while($r = mysql_fetch_array($result))
{
$year = $r["year"];
$make = $r["make"];
$model = $r["model"];
$miles = $r["miles"];
$pricepay = $r["pricepay"];
$pricecash = $r["pricecash"];
$transmission = $r["transmission"];
$color = $r["color"];
$vin = $r["vin"];

echo "$year $make $model $miles $pricepay $pricecash $transmission $color $vin<br />";
}
?>


The problem lies within "WHERE id='$id'". When I use a var, it displays nothing, but if I manually make it my ID number, example 7, it works fine. What's am I doing wrong?

Answer

Take your original code and add this line before the query:

$id = (int)$_GET['id']; // Sanitize Integer Input

And change your query as others suggested to remove the quotes:

$query = "SELECT * FROM vehicles WHERE id=$id";

I am assuming your id is a normal mysql auto_increment which starts at 1. That means if `$_GET['id'] is anything but a number, it will come back as 0 and thus not match anything in the database.

Comments