Database Search


#1

I am writing a database search by name. What i am trying to do is select 1 ID from the results to put all of the information from that 1 record in the database on to the next page to print. Heres the code so far
[php]

<? if ($submit) { mysql_connect("*****", "*****", "*****"); $query = "select * from names WHERE name='$submit'"; $result = mysql_db_query("mydb", $query); if ($result) { echo ""; while ($r = mysql_fetch_array($result)) { $ID= $r["0"]; $name = $r["1"]; $last= $r["2"]; $email= $r["3"]; echo ""; } echo "
ID Name Last Email
$ID $name $last $email
"; ?>

[/php]
MOD EDIT: Added php code tags
Any help would be great. Thanks


#2

Change this line :
[php]

$ID

[/php]
to :
[php]

$ID

[/php]

Then on nextpage.php You can use the ID pased (from a $_GET) to query the data and then present it as appropriate.


#3

Couple of other things worth mentioning:

Firstly, if all you want to do is pass the id to the next page, then in effect you only need to fetch the id from the database, not the complete result set. Once you pass the id to the next page, do another query based on that id to fetch the data. To pass all the data to the next page, you need to either store all the info in a query string or use a form with hidden form fields.

Secondly, as you are using mysql_fetch_array, which fetches the results set as an associative array, you should use the table names. mysql_fetch_row uses an enumerated array.

mysql_fetch_array = associative array

while ($r = mysql_fetch_array($result)) {      
            $ID= $r["id"]; 
            $name = $r["name"];  
            $last= $r["last"];  
            $email= $r["email"];
}

mysql_fetch_row - enumerated array

while ($r = mysql_fetch_row($result)) {      
            $ID= $r[0]; 
            $name = $r[1];  
            $last= $r[2];  
            $email= $r[3]; }

you can also use mysql_fetch_object, which fetches the results as an object set

while ($r = mysql_fetch_object($result)) {      
            $ID -> id; 
            $name -> name;  
            $last -> last;  
            $email -> email;
}

Hope that helps.


#4

In response, you can pass the ID by using the above suggested method. The $_GET is a super global http://us3.php.net/variables.predefined and can be used to retrieve information passed in the URL (as opposed to the POST method which doesn’t DISPLAY it in the URL)

e.g
If you had a URL like
http://mydomain.com/nextpage.php?id=120 You could on your code for nextpage.php have something like:
[php]
$id = $_GET[‘id’];
$sql = “SELECT * FROM table WHERE id = ‘$id’”;
$link = mysql_connect(‘localhost’, ‘user’, ‘password’);
$result = mysql_db_query(‘database’, $sql);
$data =mysql_fetch_array($result);

// Then parse the data as you see fit
[/php]

Hope this helps clarify it.


#5

very helpful, thank you