PHP Search results error - php

I have written the below code as a test , but results are not comng in under the table I have created , the table appear along the top and all the results appear down the left hand side and even if I dont add anythig in the search all teh results show.?, cant see where I am going wrong. I am not worried about the actual HTML Look as it just a test. Appreciate the help. Error is
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel= "stylesheet" href="style5.css"/>
</head>
<boby>
<div class="third_bar">
<div class="second_image">
</div>
<div class="form"><form action= "search1.php" method="post">
<input type="text" name="search" id="search_bar" placeholder="" value="Search for your whisky here" max length="30" autocomplete="off" onMouseDown="active();" onBlur="inactive();"/><input type="submit" id="search_button" value="Go!"/>
</form>
</div>
</body>
</div>
</html>
search1.php
<?php
if (isset($_POST['search'])){
include ('connect.php');
$search = $_POST['search'];
$query = "SELECT * FROM whisky_results";
$result = mysqli_query($conn, $query) or die ('error getting data');
echo "<table>";
echo "<tr> <th>Whisky Name</th> <th>Whisky Desription</th> <th>Highest Price Recorded</th> <th>Lowest Price Recorded</th> </tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo "<tr><td>";
echo $row['description'];
echo "</td><td>";
echo "<tr><td>";
echo $row['highest_price'];
echo "</td><td>";
echo "<tr><td>";
echo $row['lowest_price'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
?>

Related

php: Unable to take value from the user by using submit button

This is my db : link link
<?php
$con=mysqli_connect("localhost","root","","organisation");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM org_insert");
echo "<!doctype html>
<html lang=\"en\">
<head>
<!-- Bootstrap CSS -->
<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">
<title>Hello, world!</title>
</head>
<body>
<table border='1'>
<tr>
<th>below_whom</th>
<th>name</th>
</tr>";
$row = mysqli_fetch_array($result);
#echo '<pre>'; print_r($row); echo '</pre>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['below_whom'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<div class="form-group">
<label for="usr">below_whom:</label>
<input type="text" name ="below_whom" id="below_whom" class="form-control">
</div>
<div class="form-group">
<label for="usr">name:</label>
<input type="text" name ="name" id="name" class="form-control">
</div>
<form method="post">
<input type="button" name="submit" id="submit" class="btn btn-primary" value="submit"/>
</form>
<?php
$con=mysqli_connect("localhost","root","","organisation");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit']))
{
if($below_whom !=''||$name !=''){
$below_whom=$_POST['below_whom'];
$name=$_POST['name'];
$query=mysqli_query("INSERT INTO org_insert VALUES ('$below_whom','$name');");
$query_run = mysqli_query($con,$query);
echo "<p>query inserted.</p>";
}else{
echo "<p>Insertion Failed.</p>";
}
}
mysqli_close($con);
echo"</body>
</html>";
?>
The text under p tag isn't getting executed, ie, the program is not going inside the if statement itself. I have rechecked the syntax, what is the problem? Is the syntax incorrect? I am pretty sure the connection with sql is correct. I have also refereed to some articles, still I am stuck here.
use post variables before if loop as shown below
if(isset($_POST['submit']))
{
$below_whom=$_POST['below_whom'];
$name=$_POST['name'];
if($below_whom !=''||$name !=''){
$query=mysqli_query("INSERT INTO org_insert VALUES ('$below_whom','$name');");
$query_run = mysqli_query($con,$query);
echo "<p>query inserted.</p>";
}else{
echo "<p>Insertion Failed.</p>";
}
}
and in HTML Code add type as submit and start form tag before div as
<form method="post" action=""> and closes after input tag
<input type="submit" name="submit" id="submit" class="btn btn-primary" value="submit"/>
One of the issues that I am able to see is that Your query should be:
$query=mysqli_query("INSERT INTO `org_insert`(`below_whom`,`name`) VALUES ('$below_whom','$name')");
Hope this helps.
Change the mysqli_fetch_array to mysqli_fetch_assoc or add a parameter too
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);

How to make my PHP code more efficient for a search database?

Main objective for this post is to open up a can of worms. I would like to get some advise on what is the best way/ most efficient way to search a phpmyadmin database.
I am just starting to learn PHP. Main goal is to be able to write my own search databases as that has always interested me. I played around with some code to build a basic search database and have it working now.
Below is the code I used. I would guess as it is my first attempt at this I am going about it the wrong way. Assuming this was a large database, how could I make this more efficient? Am I going about it the wrong way using PHP? Is there a better way to do this?
The goal is to have searchable database where the user has multiple options to query to help refine the results.
<html>
<head>
<title> test Search </title>
<style type="text/css">
table {
background-color: #ffffff;
}
th {
width: 200px;
text-align: left;
}
</style>
</head>
<body>
<h1> test Search</h1>
<form method="post" action="index.php">
<input type="hidden" name="submitted" value="true"/>
<label>Colour 1: <input type="text" name="criteria" /></label>
<label>Colour 2: <input type="text" name="criteria2" /></label>
<label>PostCode: <input type="text" name="criteria3" /></label>
<label>Suburb: <input type="text" name="criteria4" /></label>
<label>State: <input type="text" name="criteria5" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$criteria2 = $_POST['criteria2'];
$criteria3 = $_POST['criteria3'];
$criteria4 = $_POST['criteria4'];
$criteria5 = $_POST['criteria5'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%') and (`Colour2`like '%$criteria2%')
and (`PostCode`like '%$criteria3%') and (`Suburb`like '%$criteria4%') and (`State`like '%$criteria5%')
LIMIT 0,10";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');
echo "<table>";
echo "<tr> <th>School</th> <th>State</th> <th>Suburb</th> <th>PostCode</th> <th>Logo</th> <th>Uniform</th></tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['School'];
echo "</td><td>";
echo $row['State'];
echo "</td><td>";
echo $row['Suburb'];
echo "</td><td>";
echo $row['PostCode'];
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Logo']);
echo "\" /></td></td>";
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Uniform']);
echo "\" /></td></td>";
}
echo "</table>";
}// end of main if statment
?>
</body>
</html>

Comment system reposting comment on page reload

I've been doing a very simple php comment system, where the user simply types a comment and it appears on the site.However, I realised that the most recent comment would keep being posted if the user refreshed the page.
I figured it had something to do with the while loop in the getComments function, but I've tried header("Location: index.php") and it had another error, so I'm really out of ideas.
index.php:
<?php
date_default_timezone_set('Europe/Bucharest');
include 'dbh.inc.php';
include 'comments.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<?php
echo "<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='date' value='".date('d-m-Y H:i:s')."'>
<textarea name='message'></textarea><br/>
<button type='submit' name='commentSubmit'>Comment</button>
</form>";
getComments($conn);
?>
</body>
</html>
Comments.inc.php:
<?php
function setComments($conn)
{
if (isset($_POST['commentSubmit']))
{
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid','$date','$message')";
$result = mysqli_query($conn,$sql);
}
}
function getComments($conn)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while($row =$result->fetch_assoc())
{
echo "<div class='comment-box'><p>";
echo $row['uid']." ";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "</p></div>";
}
}
dbh.inc.php
<?php
$conn = mysqli_connect('localhost', 'root', '' , 'commentsection');
Any feedback is greatly appreciated.
So I do not know if this is a good thing, but it seems very practical.What I've finally done is:
I set up a session variable.Then instead of
function getComments($conn)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while($row =$result->fetch_assoc())
{
echo "<div class='comment-box'><p>";
echo $row['uid']." ";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "</p></div>";
}
}
I did
function getComments($conn)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while($row =$result->fetch_assoc())
{
if($_SESSION["repeated"]!=$row['message'])
{
echo "<div class='comment-box'><p>";
echo $row['uid']." ";
echo $row['date']."<br>";
echo nl2br($row['message']);
}
$_SESSION["repeated"]=$row['message'];
echo "</p></div>";
}
}
And it seems to be absolutely working!It has a minor glitch though :
If I delete all the variables in the database after I already posted a comment in this session, at some point it will post it again.(Not a big deal).
But that's all.
I was going for the post/redirect/get, but I was a bit confused and tried this out of curiosity and it worked.(To me)It seems a simpler approach, or is it something I'm not seeing?
easy fix!!!
add recuired to the forms
<input type='text' name='emne' placeholder='Subject' required
<input type='text' name='emne' placeholder='Subject' required>

Having a hard time with displaying information from my database

I'm just learning PHP and I followed the book to the last detail and when I go to the localhost web page that I created to pull information from the database nothing shows on the webpage. I've troubleshooted all night I've Google and read the book over and over to see what I missed. I'm posting the code that I wrote to see if someone can lead me in the right area to fix my problem.
<html>
<head>
<title>Pay Scale</title>
<style type="text/css">
table {
background-color: #FCF;
}
th {
width:150px;
text-align: left;
}
</style>
</head>
<body>
<h1>Pay Scale</h1>
<form method= "post" action= "Payscale.php"
<input type="hidden" name="submitted" value="true" />
<label> Search Category:
<select name="category">
<option value="Id">ID</option>
<option value="First Name">First Name</option>
<option value="Last_Name">Last_Name</option>
</select>
</label> <label>Search Criteria:
<input type="text" name="criteria" />
</label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])){
include('payconnect.php');
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM employee pay range WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('error getting data');
echo "<table>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last_Name</th> <th>Pay_Range</th> </tr>";
While($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['ID'];
echo "</td><td>";
echo $row['First Name'];
echo "</td><td>";
echo $row['Last_Name'];
echo "</td><td>";
echo $row['Pay_Range'];
echo "</td><tr>";
}
echo "<table>";
}
?>
</body>
</html>
There are a couple of problems with the html code for the page. The most obvious is that there is no closing > on your form tag, so the browser slurps up the next line, thinking that it is part of the form tag. Since that line sets the $_POST['submitted'] variable that your PHP script is looking for, the value doesn't get set and the script never runs.
To correct the problem, just add a > to your form declaration:
<form method="post" action="Payscale.php">
There are also a few other problems in the HTML that could be fixed at the same time:
At the top of the page:
<html>
<head>
A document should start with a DOCTYPE declaration so that the browser knows how to interpret the page. For HTML5, this is as simple as adding a line to the start of your file:
<!DOCTYPE html>
<html>
<head>
There is also an error in the table creation code:
echo $row['Last_Name'];
echo "</td><td>";
echo $row['Pay_Range'];
echo "</td><tr>"; # A
}
echo "<table>"; # B
The lines marked A, and B create new elements--a table row, and a new table respectively. You should be closing the elements--i.e. using </tr> and </table>.
It appears that your opening tag is not closed (a minor syntactical error).
Try changing it from this:
<form method= "post" action= "Payscale.php"
to this:
<form method="post" action="Payscale.php">
and see if that solves the problem.
Try this it's working :
<html>
<head>
<title>Pay Scale</title>
<style type="text/css">
table {
background-color: #FCF;
}
th {
width:150px;
text-align: left;
}
</style>
</head>
<body>
<h1>Pay Scale</h1>
<form method= "post" action="Payscale.php">
<input type="hidden" name="submit" value="true"/>
<label> Search Category:
<select name="category">
<option value="Id">ID</option>
<option value="First Name">First Name</option>
<option value="Last_Name">Last_Name</option>
</select>
</label> <label>Search Criteria:
<input type="text" name="criteria" />
</label>
<input type="submit" value="submit" name="submitted"/>
</form>
</body>
</html>
Payscale.php
<?php
if (isset($_POST['submitted'])){
include('payconnect.php');
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM employee pay range WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('error getting data');
echo "<table>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last_Name</th> <th>Pay_Range</th> </tr>";
While($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['ID'];
echo "</td><td>";
echo $row['First Name'];
echo "</td><td>";
echo $row['Last_Name'];
echo "</td><td>";
echo $row['Pay_Range'];
echo "</td><tr>";
}
echo "<table>";
}
?>

Creating a table on HTML with information from various MySQL tables

i have a website i am constructing for a school project, in which i already have various webpages where i get tabular data from my database through the use of While and Foreach.
But on this page in question, i am attempting to retrieve data from various tables, in order for a user to choose a category, and a text and submit.
But for some reason it isn't outputting any data. If i attempt with only one table and without using the table.field method, and only typing the fields, it works.
But from what i know, to retrieve from various tables i have to do so.
Can annione help me out on this?
<html>
<head>
<script type="text/javascript" >
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$query = "SELECT texto.titulo,texto.ID,categoria.categoria,categoria.id FROM categoria,texto";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo "<form id='formulario' name='post' method='post' onsubmit='return validar(this) action='../inserir/inseretexto.php>'";
echo "<button type='submit'>Submeter</button>";
echo "<tr><td colspan ='2'>Historico de Newsletters</td><td colspan='2'>Enviar Newsletter</td></tr>";
echo "<tr><td colspan='2'>Texto </td><td colspan='2'>Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if ($campo == "texto.titulo") {
echo "<tr><td>'".$valor."'</td>";
}
if ($campo == "texto.ID") {
echo "<td><input type='radio' name='nome' value='".$valor."'></td></tr>";
}
if ($campo == "categoria.categoria") {
echo "<td>'".$valor."'</td>";
}
if ($campo=="categoria.id") {
echo "<td><input type='radio' name='nome' value='".$valor."'></td></tr>";
}
}
}
echo "</form>";
echo "</table>";
echo "</center>";
?>
</body>
</html>
Added: Since both tables have a field called id, it won't let me simply put the field names, i have to also put the table name like i did. And yes, i have verified and both tables are populated with data, they work fine on other pages.
This is what I suggest (I didn't consider much code optimization).
<?php
$data = array();
mysql_connect('localhost', 'root', '') or die('problema na conexao');
mysql_select_db('trabalho1');
// Use the same field-names/aliases: id, info
$query = 'SELECT ID AS id, titulo AS info FROM texto';
$results = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
// Use the same field-names/aliases: id, info
$query = 'SELECT id, categoria AS info FROM categoria';
$results = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
?>
<html>
<head>
<script type="text/javascript">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<center>
<table border='2'>
<form id='formulario' name='post' method='post' onsubmit='return validar(this) action='../inserir/inseretexto.php>
<tr><td colspan ='2'><button type='submit'>Submeter</button></td></tr>
<tr><td colspan ='2'>Historico de Newsletters</td><td colspan='2'>Enviar Newsletter</td></tr>
<tr><td colspan='2'>Texto </td><td colspan='2'>Categoria</td></tr>
<?php
foreach ($data as $row) {
echo '<td><input type="radio" name="nome" value="' . $row['id'] . '></td></tr>' .
'<tr><td>' . $row['id'] . '</td>';
}
?>
</form>
</table>
</center>
</body>
</html>
PS: Read about my response about double quotations. Should I use curly brackets or concatenate variables within strings?

Categories