Jump to content

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


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();

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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