Forum Moderators: coopster

Message Too Old, No Replies

capturing url id in mysql query

passing url id

         

otter

6:42 am on Feb 19, 2009 (gmt 0)

10+ Year Member


All,

Here is the relevent part of the code. I can not figure out why the ID from the URL is not passing into the sql query.

<?php
$ID=intval($_get['id']);
?>

<?php
$link = mysql_connect('db', 'name', 'pswd');
if (!$link) {
die('Could not connect: ' . mysql_error());
}

$result = mysql_query('SELECT class_name, ID FROM table where id=$id');
if (!$result) {
die('Invalid query: ' . mysql_error());

rest of code......

I am very new to PHP but I am good at SQL. I have tried
snipets of code like

<?php
$id = $_GET['id'];
echo "the id is: $id";
?>

and am able to get the variable to pass through.
I have tried variations of 's and "s and either get a SQL syntax error or a blank page. I tried adding the intval() funtion thinking that the id was being passed as text instead of a number, but that didn't seem to work either.

Any thoughts?
Thank you in advance.

phranque

7:27 am on Feb 19, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



welcome to WebmasterWorld [webmasterworld.com], otter!

it's probably a variable interpolation problem.
try this:
$result = mysql_query('SELECT class_name, ID FROM table where id=' . $id);

a good practice (especially for debugging) is to assign the sql string to a variable so you can print out the resulting statement:
$sql = 'SELECT class_name, ID FROM table where id=' . $id;
$result = mysql_query($sql);

also, i just noticed your variable assignment for $ID is upper case and your usage in the string is lower case.
(i'm not a PHP programmer so this may not be an issue.)

otter

3:14 pm on Feb 19, 2009 (gmt 0)

10+ Year Member


Thank you for the reply. I finally got it to work.
Here is what I ended up with:

<?php

$id = $_GET['id'];

$link = mysql_connect('localhost', 'user', 'pswd');
if (!$link) {die('Could not connect: ' . mysql_error());}

$sql = 'SELECT class_name, ID FROM test.test_ems_ce where id=' . $id;
$result = mysql_query($sql);
if (!$result) {die('Invalid query: ' . mysql_error());}

echo "the id is: $id";

$row = mysql_fetch_array($result);
echo $row['class_name'];
echo "<br />";

mysql_close($link);
?>

I really don't know for sure what the error was other than possibly I was missing a ; when I was doing

$row = mysql_fetch_array($result)

and that is what caused the blank page to be returned.

Anyway thanks for the help.

tbarbedo

3:33 pm on Feb 19, 2009 (gmt 0)

10+ Year Member



You can always look at the Apache error log to give you some clues as to why something is not processing right in your PHP..

ApacheFolder\logs\error.txt

otter

3:38 pm on Feb 19, 2009 (gmt 0)

10+ Year Member



I didn't know that. Thank you! I'll start giving that a try.