I'm tryig to create a text input on my page to be able to receive a username which is on my database and return another information of himself, how can i do it? For example entering a name and returning his telephone number. i have just no idea how to start. Thanks
Here's the working code. But learn the basics first.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Index page</title>
</head>
<body>
<form method="POST" action="retrieve.php">
Enter your name : <input type="text" name='username'><br><br>
<input type="submit" name="submit">
</form>
</body>
</html>
retrieve.php
<?php
//Database connection
$connection = mysqli_connect("localhost","username","password","database_name");
if (isset($_POST['submit'])) {
$uname = $_POST['username'];
// sql query and user is the table name
$query = "SELECT * FROM `user` WHERE user_name='$uname'";
// query to execute
$result = mysqli_query($connection,$query);
if (!$result) {
echo "fails";
}
while($row = mysqli_fetch_array($result)) {
$telephone_no = $row['phoneno'];
$country_name = $row['country'];
echo "Your results for name - " . $uname;
echo "<br><br>";
echo "Telelephone is : " . $telephone_no;
echo "<br>";
echo "Country name is : " . $country_name;
}
}
?>
Database structure : (User table)
To test the code, insert a person details in PHPMyadmin
insert tab.(Leave id alone as it was set to an auto-increment).
<?php
if(isset($_POST['username']){
try{
$dbh = new PDO("mysql:dbname=Amor;host=127.0.0.1",
"Javier", "your_password");
$sql = "SELECT name, phone, address FROM people_table
WHERE username=:username";
$res = $dbh->prepare($sql);
$res->bindParam('username', $_POST['username'], PDO::PARAM_STRING);
$res->exec();
$row = $res->fetchAll(PDO::FETCH_ASSOC);
print_r($row);
//Sorry mate I'm feeling lazy. You can take over from here
}
?>
**//html code here**
<form action="" method="GET>
<input type="text" name="username">
<input type="submit" value="Search">
</form>