Reputation: 61
I am currently working on a website, i am quite new to this. I have established connection to my database with the connection.php file, but it seems quite hard to style a PHP file. So i want to know:
As it is right now all are in one file, so it looks like this
Thank you in advance
Index.php
<?php
ini_set("display_errors", "On");
error_reporting(E_ALL);
$host='database.****.us-east-1.rds.amazonaws.com';
$db = '****';
$port = 5432;
$username = 'postgres';
$password = '****';
try {
$conn = new PDO("pgsql:host=$host;port=$port;dbname=$db;user=$username;password=$password");
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html>
<body>
<h1>Choose Category</h1>
<?php
$sql ="select * from products inner join category on category.category_id = products.category";
//Prepare the select statement.
$stmt = $conn->prepare($sql);
//Execute the statement.
$stmt->execute();
//Retrieve the rows using fetchAll.
$users = $stmt->fetchAll();
// show menu from dropdown
?>
<select>
<?php foreach($users as $user): ?>
<option value="<?= $user['id']; ?>"><?= $user['name']; ?></option>
<?php endforeach; ?>
</select>
</body>
</html>
Upvotes: 0
Views: 336
Reputation: 114
There is a much simpler way but I am going to give an example: Suppose you have a php file:
connection.php:
<?php
function connect(){
$con=mysqli_connect("localhost","root","","dbname");
if(!$con)
die("Could not connect");
}
return $con;
}
?>
Now another file called getAll.php
<?php
require("connection.php");
$con=connect();
$getAll="select * from employees";
$res=mysqli_query($con,$getAll);
while($row=mysqli_fetch_array($res)){
echo "<option value='$row[firstname]'>$row['firstname']</option>"
}
mysqli_close($con);
?>
Now where you want to display the dropdown list:
Suppose a file called display.php
<html>
<body>
<select name="employee">
<?php
require("getAll.php");
?>
</select>
</body>
</html>
This is a simple way to get data from database and display them.
Upvotes: 1