The Problem
Hello, I am creating a search function that will allow users to search for a specific E-Number and see whether it is derived from animals or not, basically seeing if it's vegan. I have successflly connected to the database using PHP on my website.
The Code
At the top of the page:
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=***** port=*****
dbname=**** user=**** password=*****")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// Performing SQL query
$query = 'SELECT vegan FROM enumbers WHERE code = searchq';
}
?>
The search bar:
<div id="tablebox">
<!-- Search bar -->
<p>Is It Vegan?</p>
<form name="form1" method="post" action="searchEnumbers.php">
<input name="search" type="text" size="30" maxlength="5" />
<input name="submit" type="submit" value="Search" />
</form>
</div>
How will I now display the 'vegan' result that has been searched? I am unsure how to print the results.
Update
The column names in the enumbers table are: 'code', 'name', 'type', and 'vegan'.
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=db.dcs.aber.ac.uk port=5432
dbname=cs399030_16_17 user=sec17 password=Liverpool2112")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// Performing SQL query
$pg_query = 'SELECT vegan FROM enumbers WHERE code = '.$searchq;
$result = pg_query($query);
foreach($result as $r){ //If you have multiple records or $result
echo "<p> Your ".$r->params." or ".$r['params']." here </p>"; //for instance
}
}
?>
You should have something like:
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=**** port=****
dbname=**** user=**** password=****")
or die('Could not connect: ' . pg_last_error());
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
// Performing SQL query
$query = 'SELECT vegan FROM enumbers WHERE code = '.$searchq;
// make the query with: pg_query
// $result = pg_query($query);
foreach($result as $r){ //If you have multiple records or $result
echo "<p> Your ".$r->params." or ".$r['params']." here </p>"; //for instance
}
//you could use: var_dump(pg_fetch_all($result));
}
?>
<!-- If you want to show always the form. If not, put inside the else -->
<div id="tablebox">
<!-- Search bar -->
<p>Is It Vegan?</p>
<form name="form1" method="post" action="searchEnumbers.php">
<input name="search" type="text" size="30" maxlength="5" />
<input name="submit" type="submit" value="Search" />
</form>
</div>
Note this is not the best way to do it (you could use AJAX, and differents pages in order to now refresh the page), or others ways. But this could work as the way you want.
Check official documentation from PHP: http://php.net/manual/kr/function.pg-connect.php
Hope it helps!