Jump to content

[SOLVED] PHP - using php and mysql to display information from database


dont_be_hasty

Recommended Posts

Hi  :)

 

I'm new to php and have never programmed in it before, so i could do with some help.

I basically have a webpage and when the user inputs a value and submits it, i want to search a database table for this value and display another value in the same row as the inputted value.

 

 

Here's my example:

 

Database is called 'database1'

 

Table - table1(id, name, term)

 

 

The form in the index.html:

 

<form name="term" method="post" action="results.php">

    <input type="text" name="term">

    <input type="submit" value="Submit">

</form>

 

 

The value the user enters - will be a value from the term attribute in table1, there for i would like to display the name and/or id which is in the same row as the term value entered by the user.

 

I have been looking up examples on the internet and have tried writing the following code in results.php to do this.

 

<?php

$username="root";

$password="";

$database="database";

 

mysql_connect(localhost,$username,$password);

@mysql_select_db($database) or die( "Unable to select database");

 

$query="SELECT name FROM table1 WHERE term=$term";

$result=mysql_query($query);

 

mysql_close();

 

$term=mysql_result($result");

?>

 

The parts in red are the parts i think are wrong.

 

 

Also i am using WAMP Server 5, so I'm not sure if i am putting the html and php files in the correct place, so that they can access the database.

 

 

Any help at all will be appreciated.

 

Thanks in advanced.

* not tested; comments in the code *

 

$term = mysql_real_escape_string($_POST['term']);  //get the POST var and clean it with mysq_real_escape_string() to prevent SQL injections
$query="SELECT name FROM table1 WHERE term = '$term'"; //need single quotes around strings ($term)
$result=mysql_query($query) or die(mysql_error()); //added for error checking            
$row = mysql_fetch_assoc($result);  //extract the data from the DB via associative array
echo $row['name'];  //use the array ($row) to display desired results
mysql_close();

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.