Jump to content

Getting data from mysql database for a specific ID number


Guest

Recommended Posts

Hi Guys

 

I have been going through threads on this forum and it looks excellent. I am pretty new to PHP and have some experience with SQL.

 

I have currently created a table with items in it on a mysql database.

 

I have generated a HTML web page that has one input box where I want to enter the ID manually and once submitted that ID will bring up the result for what is on my table that links to that ID field?

 

I have all connections in place and it works fine. I have a index page and one page to get the results.

 

On the index page I have used: <form action="history_results.php" method="REQUEST"> for the input box and on the history_results.php page I am stuck to what code to use to get this information? I just need the php or sql query to use..?

 

Hope this makes sense and thanks in advance.

 

 

 

 

For your form method, use POST or GET ( I prefer POST, as it's less intrusive to the end user )

 

On your history_results.php page... you want something like this ( assuming the name of the input box is 'id' )

 

<?php

# Has the form been submitted?
if ( empty($_POST) )
exit( 'This page is to process form results, and should not be accessed directly' );

# Verify the data coming in is good - make sure its a number
if ( !isset( $_POST['id'] || !is_numeric($_POST['id']) )
exit( 'Invalid data! ID must be a number.' );

# Script hasn't exited, stuff must check out...
# Build the query - (int) forces the variable to be an integer - just in case 
$q = 'SELECT `row1`, `row2` FROM `table` WHERE `id` = '. (int) $id;

# Execute the query, checking for errors
if ( ($r = mysql_query($q)) === FALSE )
# You can add debugging here, using functions like mysql_error(), but I
# like to avoid using them ouside of internal testing, and only when the
# query becomes complex due to it possibly revealing information about your
# database that you don't want others to know
exit( 'Could not execute query!' );

# Check to see if any rows were found
if ( mysql_num_rows($r) < 1 )
exit( 'No results found for ID '. (int) $id );

# Nothing went wrong, we must have some data! Lets grab it!
# This is assuming only 1 row is selected at a time
$data = mysql_fetch_assoc( $r );

# Loop through data and display!
foreach( $data as $col => $val )
echo $col .' = '. $val .'<br />';

?>

It's an array assigner. It's saying that for each item in $data (which is an sql result), split the result as columnvalue belongs to (=>) columname.  This way, you can directly access $data like this:

 

echo $data['usrname'] and it will return the user's name, etc.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.