So I got these issues when I tried to extract data from the database. My DB connection is working fine. It is showing "Database connection established" and inside my index.php I wrote a for each loop to get the data and inside my HTML code, I display it inside the table. I got these errors:
Notice: Undefined variable: jokes in C:\xampp\htdocs\comp1321_database\jokes\jokes.html.php on line 16
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\comp1321_database\jokes\jokes.html.php on line 16
Here is the HTML and php code to display the data:
<?php include_once 'admin/includes/helpers.inc.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>List of Jokes</title>
</head>
<body>
<p>Add your own joke</p>
<p>Here are all the jokes in the database</p>
<!-- into a table -->
<table border="1">
<?php foreach ($jokes as $joke): ?>
<!-- <form action="?deletejoke" method="post"> -->
<tr>
<td><?php html($joke['joketext']);?></td>
<td><?php $display_date = date("D d M Y", strtotime($joke['jokedate']));
html($display_date); ?>
</td>
<td><img height="100px" src="images/<?php html($joke['image']);?>"
/></td>
<td><input type="hidden" name="id" value="<?php echo $joke['id'];
?>">
<input type="submit" value="Delete"></td>
</tr>
<!-- </form> -->
<?php endforeach; ?>
</table>
<?php include 'admin/includes/footer.inc.html.php';?>
</body>
</html>
and here is the index.php:
<?php
// selection block
include 'admin/includes/db.inc.php';
//
try
{
$sql = 'SELECT * FROM joke';
$result = $pdo->query($sql);
} catch (PDOException $e) {
$error = 'Error fetching jokes' . $e->getMessage();
include 'error.html.php';
exit();
}
foreach ($result as $row) {
$jokes[] = array(
'joketext'=> $row ['joketext'],
'jokedate'=> $row['joketext'],
'image'=> $row['image']
);
}
include 'jokes.html.php';
?>
Many thanks.
Initialize your jokes variable before you try to use it, ie:
$jokes = [];
try
{
$sql = 'SELECT * FROM joke';
$result = $pdo->query($sql);
} catch (PDOException $e) {
$error = 'Error fetching jokes' . $e->getMessage();
include 'error.html.php';
exit();
}
foreach ($result as $row) {
$jokes[] = array(
'joketext'=> $row ['joketext'],
'jokedate'=> $row['joketext'],
'image'=> $row['image']
);
}
You need define $jokes on your php file, you can do it on header of file.
<?php include_once 'admin/includes/helpers.inc.php';?>
<?php
$jokes = someGetJokesFunction(); // write function to get data from database
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>List of Jokes</title>
</head>
<body>
<p>Add your own joke</p>
<p>Here are all the jokes in the database</p>
<!-- into a table -->
<table border="1">
<?php foreach ($jokes as $joke): ?>
<!-- <form action="?deletejoke" method="post"> -->
<tr>
<td><?php html($joke['joketext']);?></td>
<td><?php $display_date = date("D d M Y", strtotime($joke['jokedate']));
html($display_date); ?>
</td>
<td><img height="100px" src="images/<?php html($joke['image']);?>"
/></td>
<td><input type="hidden" name="id" value="<?php echo $joke['id'];
?>">
<input type="submit" value="Delete"></td>
</tr>
<!-- </form> -->
<?php endforeach; ?>
</table>
<?php include 'admin/includes/footer.inc.html.php';?>
</body>
</html>
Related
i am completely new to this world and i am trying to get more confident with PHP and MYSQL, so i am playing with a small web application just to fetch and retrieve data with MYSql and PHP.
I created a table in HTML and my goal is to retrieve this data from a mysql table with PHP
The problem is that the data are displayed twice... Can you help me understand where is error ?
Below the code :
<?php
session_start();
include_once("database.php");
$db = $conn;
$query = " SELECT categoria FROM categoria_prodotto";
$result = $db->query($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>test</title>
</head>
<body>
<section id="main-page">
<div class="link">
<span> Create a new purchase table </span>
</div>
<table>
<tr>
<td> category </td>
<td> product </td>
</tr>
<?php while ($row = mysqli_fetch_array($result)) :
foreach ($row as $temp) {
$query1 = "SELECT `nome` FROM `supermarket`.`lista_prodotto` WHERE `categoria_prodotto` = '$temp' ORDER BY `categoria_prodotto` DESC";
$result1 = $db->query($query1);
?>
<tr>
<td><?php echo $row[0]; ?> </td>
<td>
<?php while ($row1 = mysqli_fetch_array($result1)) :
echo $row1[0]; ?>
<?php endwhile;
}
endwhile; ?>
</td>
</tr>
</table>
<div class="link">
<span> Store a new product </span>
</div>
</section>
</body>
</html>
////
And here the result in browser with two row with same data duplicated each time
[here][1]
Thank you in advance for helping me to troubleshoot my problem :)
[1]: https://i.stack.imgur.com/XEBsi.jpg
You have some unnecessary loops, also if you use the object oriented version of the MySQLI API its a lot easier to read. I also change the query to use a Prepared parameterised query that you bind data to before the executing the query, much safer and protects you against SQL Injection
<?php
session_start();
include_once("database.php");
$db= $conn;
$query = "SELECT categoria FROM categoria_prodotto";
$result = $db->query($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>test</title>
</head>
<body>
<section id="main-page">
<div class="link">
<span> Create a new purchase table </span>
</div>
<table>
<tr>
<td> category </td>
<td> product </td>
</tr>
<?php
while($categoria_prodotto = $result->fetch_assoc()):
$query1 = "SELECT `nome`
FROM `supermarket`.`lista_prodotto`
WHERE `categoria_prodotto` = ?
ORDER BY `categoria_prodotto` DESC";
$stmt1 = $db->prepare($query1);
$stmt1->bind_param('s', $categoria_prodotto['categoria']);
$stmt->execute();
$result1= $stmt->get_result();
$supermarket = $result1->fetch_assoc();
?>
<tr>
<td><?php echo $categoria_prodotto['categoria']; ?></td>
<td><?php echo $supermarket['nome']; ?></td>
?>
<?php
endwhile;
?>
</td>
</tr>
</table>
</section>
</body>
</html>
Been working on a product page for my wife's jewelry site. I added php from a tutorial and tried to run the page. None of the images including the header showed up along with the footer. They show up on every other page. None of the information product showed up either. the page says connection opened and i receive no errors. The navigation shows up along with some of the css but that is all.
Here is my code I am using.
<?php
error_reporting(E_ALL);
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
?>
<?php
if (isset($_GET['id'])) {
// Connect to the MySQL database
include_once("storescripts/connect_to_mysql.php");
$con =
mysqli_connect("$db_host","$db_username","$db_pass","$db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
} $id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$sql = "SELECT * FROM products WHERE category='Bracelets';";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
// get all the product details
while($row = mysqli_fetch_assoc($result)); {
$item_number = $row["item_number"];
$price = $row["price"];
$desc = $row["description"];
$category = $row["category"];
}
} else {
echo "Data to render this page is missing.";
exit();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Bracelets</title>
<meta charset="utf-8">
<meta http-equiv="x=UA-comparable" content="IE-edge">
<meta name="description" content="Pinky's Pearls is a website where
one
of a kind jewelry designed by Nichole <q>Nicki</q> can be seen and
purchased">
<meta name="keywords" content="jewelry, beads, bracelets, rings,
pendants, necklaces, pearls, crystal">
<meta name="viewpoint" content="width=device-width, initial-scale=1">
<meta name="author" content="samuel jaycox">
<link href="style.css" rel="stylesheet">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/4.7.0/css/font-awesome.min.css">
<link rel="shortcut icon" type="image/png" href="pictures/pinky.png">
<script src="https://use.fontawesome.com/0c9491c5b9.js"></script>
</head>
<body>
<div align="center" id="wrapper">
<div id="banner-wrapper">
<?php
include_once("c:/xampp/htdocs/pinkys_pearls/templates/template_bracelets.php");
?>
<br>
<?php include_once("templates/template_navigation.php"); ?>
<br>
<br>
<br>
<!--Start Comment page Body Content-->
<div id="body-content">
<div class="bracelet_body">
<table width="100%" border="2" cellspacing="0" cellpadding="15">
<tr>
<td width="19%" valign="top"><img src="pictures/inventory/<?php echo
$pid; ?>.png" width="142" height="188" alt="<?php echo $item_number; ?>"
/>
<br />
<a href="pictures/inventory/<?php echo $pid; ?>.png">View Full Size
Image</a></td>
<td width="81%" valign="top"><h3><?php echo $item_number; ?></h3>
<p><?php echo "$".$price; ?><br />
<br />
<?php echo $desc; ?>
<br />
</p>
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="pid" id="pid" value="<?php echo $id; ?
>"
/>
<input class="button" type="submit" name="button" id="button"
value="Add to Shopping Cart" />
</form>
</td>
</tr>
</table>
</div>
</div>
<!--end of Comment body-->
<?php include_once('templates/template_footer.php'); ?>">
</body>
</html>
Please make sure your paths are right!
Try to change your links
<?php include_once("c:/xampp/htdocs/pinkys_pearls/templates/template_bracelets.php"); ?>
<?php include_once("c:/xampp/htdocs/pinkys_pearls/templates/template_navigation.php"); ?>
as
<?php include_once("localhost/pinkys_pearls/templates/template_bracelets.php"); ?>
<?php include_once("localhost/pinkys_pearls/templates/template_navigation.php"); ?>
and make sure with your image paths, if folder varies you cannot get load the images.
On the list.php page, I am passing a variable using hidden input method in form.
This form redirects to listd.php where the variable is used to run an SQL query to delete a particular row from the database where the variable==name.
If I print the variable on listd.php before processing SQL query then it is visible but during when query is processed it gives unidentified index error.
The code in listd.php works if I take input from the user on the same page.
list.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Sports </title>
<link rel="stylesheet" href="main.css" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Tangerine">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Great+Vibes|Roboto|Barrio" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<?php
require ("config.php");
?>
<div class="row">
<div class="container-fluid">
<div class="jumbotron text-center">
<h3> List Events</h3>
<?php
session_start();
if($_SESSION['username'])
echo "<h2>Welcome ".$_SESSION['username']."!</h2>";
else
header('location:index.php');
//session_start();
if(isset($_SESSION['username']))
echo "<h3><a href='logout.php'>Logout</a></h3>";
?>
</div>
</div>
</div>
<div class="container">
<h2>Hover Rows</h2>
<p>The .table-hover class enables a hover state on table rows:</p>
<table class="table table-hover">
<thead>
<tr>
<th>Event </th>
<th>Add</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<!--
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
-->
<?php
{$result="SELECT name FROM events";
$q = mysqli_query($conn,$result) or die(mysql_error());
while ($row=mysqli_fetch_array($q))
{
echo "<tr> <td>";
echo $row['name'];
echo "</td>";
echo "<td>";
echo '<button> Add </button> <br><br>';
echo "</td>";
echo "<td>";
echo '<form action="liste.php" method="post" >';
echo '<input type="hidden" name="edit" value="';?>
<?php echo $row['name'];
echo'"> <input type="submit" value="Edit">';
echo "</form>";
echo "</td>";
echo "<td>";
echo '<form action="listd.php" method="post" >';
echo '<input type="hidden" name="del2" value="';?>
<?php echo $row['name'];
echo'"> <input type="submit" value="Delete">';
echo "</td>";
echo "</form>";
}
}
?>
<!--
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
-->
</tbody>
</table>
</div>
</body>
</html>
listd.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Sports </title>
<link rel="stylesheet" href="main.css" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Tangerine">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Great+Vibes|Roboto|Barrio" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<?php
require ("config.php");
?>
<div class="row">
<div class="container-fluid">
<div class="jumbotron text-center">
<h3> Events </h3>
<div class="row">
<div class="container-fluid text-primary text-center">
<br>
<button class="btn"> Add </button> <br><br>
<button class="btn"> Edit </button> <br><br>
<button class="btn"> Delete </button> <br><br>
<button class="btn"> View </button> <br><br>
</div>
</div>
<?php
session_start();
?>
<form action="listd.php" method="post" class="a">
<table>
<tr>
<td> Category Name </td>
<td>
<strong>
<?php echo $_POST["del2"];
$k=$_POST['del2'];
?>
</strong>
</td>
</tr>
<tr>
<td></td>
<td> <input type="submit" value="Delete" name="delete"> </td>
</tr>
</table>
</form>
<?php
$event=$k;
if(isset($_REQUEST['delete'] )&& $event )
{
$sql="DELETE FROM events WHERE name='$event'";
if(mysqli_query($conn,$sql))
{
echo "deleted Succesfully";
//header('location:listd.php');
}
else
echo "error";
}
?>
</div>
</div>
</div>
</body>
</html>
It's really not necessary to use two forms to do this, unless this is a very dangerous action. this is also the source of your problem. $k is not preserved on the second postback. Requests are stateless. When you submit the second form, the listd.php script runs again from the start, and the values assigned to variables the last time it ran. This is the normal behaviour of HTTP requests in general.
A single-form version might look like this:
list.php
<?php
//this needs to be before anything else otherwise the redirect might fail due to headers already sent.
session_start();
if(isset($_SESSION['username'])) //corrected to use isset(). Only one test for this is needed.
{
echo "<h2>Welcome ".$_SESSION['username']."!</h2>";
echo "<h3><a href='logout.php'>Logout</a></h3>";
}
else
{
header('location:index.php');
die(); //script needs to die because webcrawlers/bots will ignore the redirect header, and view the rest of the page anyway, without permission. Using die() means the rest of the page never gets output.
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Sports </title>
<link rel="stylesheet" href="main.css" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Tangerine">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Great+Vibes|Roboto|Barrio" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<?php
require ("config.php");
?>
<div class="row">
<div class="container-fluid">
<div class="jumbotron text-center">
<h3> List Events</h3>
</div>
</div>
</div>
<?php
$message = null; //will hold any extra message to the user resulting from data processing actions (such as delete)
//only run the next section if del2 has been submitted from a postback.
if(isset($_POST['del2']))
{
$event = $_POST['del2'];
$sql= "DELETE FROM events WHERE name='$event'"; //here you should use parameterised queries, I will leave it to you to look this up online, using the link I gave in the comments.
if(mysqli_query($conn,$sql))
{
$message = "Deleted succesfully";
}
else
{
$message = "error";
//here you should check mysqli_error() and log the output somewhere (not visible to the user)
}
}
?>
<div class="container">
<h2>Hover Rows</h2>
<!-- here is an example of how you can inject the confirmation message into somewhere suitable in the page. You can modify this to suit your needs. -->
<?php if ($message != null) { echo "<p><b>".$message."</b></p>"; } ?>
<p>The .table-hover class enables a hover state on table rows:</p>
<table class="table table-hover">
<thead>
<tr>
<th>Event </th>
<th>Add</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
$result="SELECT name FROM events";
$q = mysqli_query($conn,$result) or die(mysqli_error()); //corrected to use mysqli_error not mysql_error
while ($row=mysqli_fetch_array($q))
{
echo "<tr> <td>";
echo $row['name'];
echo "</td>";
echo "<td>";
echo '<button> Add </button> <br><br>';
echo "</td>";
echo "<td>";
echo '<form action="liste.php" method="post" >';
echo '<input type="hidden" name="edit" value="';
echo $row['name'];
echo'"> <input type="submit" value="Edit">';
echo "</form>";
echo "</td>";
echo "<td>";
echo '<form action="list.php" method="post" >';
echo '<input type="hidden" name="del2" value="';
echo $row['name'];
echo'"> <input type="submit" value="Delete" onclick="return confirm("Are you sure?");>'; //adds a confirmation dialog box to the delete button
echo "</td>";
echo "</form>";
}
?>
</tbody>
</table>
</div>
</body>
</html>
You do not need listd.php at all.
P.S. A separate hint: I see you are copying the same HTML <head> etc material into every page script. This is not necessary. You can create two files e.g. header.php and footer.php. In header.php you can put the opening <html> and <head> tags right down to <body> and any other enclosing tags necessary for the consistent layout of all your pages. Then in footer.php you can put the equivalent closing tags. And then in all the other pages of your site you can simply write <?php require_once("header.php"); ?> as the first line and <?php require_once("footer.php"); ?> as the last line. Then any changes you need to make to the headers (e.g. new CSS files or something) are automatically applied to all the pages without tedious copy/paste actions. Although I suggested that you remove your second script here, you can do this for any other pages in your site. It's also a good general principle of code re-use which you can apply to all kinds of situations in your future code.
P.P.S. I'd also consider using an up-to-date doctype. The HTML5 doctype declaration is simply <!DOCTYPE html>. This will likely result in more consistent behaviour of the HTML and CSS in your page, and future-proofs your application against deprecation of older doctypes which are no longer in current use.
Ok so basically I am having problems with outputting results from a search facility.
So let's say for example I search and I select a hotel with 'hotel_id' = 4 instead it always outputs results with 'hotel_id' = 1 no matter what I select. The search facility searches through name of hotel and guest's surname's and which ever is selected it should output anything that matches it, and that should be guests details, bookings that they made and hotels they have chosen.
My search facility looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="navigation">
<form action = "index.php" method="get">
<input type = "submit" name = "mainpage" value = "Main Page" class = "submitbut" id = "but1" />
</form>
</div>
<form action="index.php" method="post">
<input type = "text" name = "search" id = "searching" />
<input type = "submit" name = "data_submit" value = "Search" id = "scan" />
</form>
<?php
if(isset($_GET['mainpage'])){
header("Location:mainpage.php");
exit;
}
if (isset($_POST["data_submit"])){
$search_term = $_POST['search'];
$conn = new PDO(
'mysql:host=localhost;dbname=u1358595',
'root'
);
$stmt = $conn->prepare("SELECT * FROM hotel
INNER JOIN booking
ON hotel.hotel_id=booking.hotel_id
INNER JOIN guest
ON guest.guest_id=booking.guest_id
WHERE name LIKE :search_term");
$stmt->bindValue(':search_term','%'.$search_term. '%');
$stmt->execute();
echo
"<table><tr>
<th>Hotels Matched</th>
</tr>";
while($hotel = $stmt->fetch())
{
echo
"<tr>"."<td>"."<a href='details.php?name=".$hotel['name']."'>".$hotel['name']."</a>"."</td>"."</tr>";
}
echo "</table>";
$stmt = $conn->prepare("SELECT * FROM guest
INNER JOIN booking
ON guest.guest_id=booking.guest_id
INNER JOIN hotel
On booking.hotel_id=hotel.hotel_id
WHERE guest.last_name LIKE :search_term");
$stmt->bindValue(':search_term','%'.$search_term. '%');
$stmt->execute();
echo
"<table><tr>
<th>Guests Matched</th>
</tr>";
while($hotel = $stmt->fetch())
{
echo
"<tr>"."<td>"."<a href='details.php?name=".$hotel['first_name']."'>".$hotel['last_name']."</a>"."</td>"."</tr>";
}
echo "</table>";
$conn = NULL;
}
?>
</body>
</html>
And my results are printed on another page, and it's code is:
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<div class="navigation">
<form action = "index.php" method="get">
<input type = "submit" name = "mainpage" value = "Main Page" class = "submitbut" id = "but1" />
</form>
</div>
<?php
$conn = new PDO(
'mysql:host=localhost;dbname=u1358595',
'root'
);
if(!isset($_GET['name']))
{
echo "You shouldn't have got to this page";
exit;
}
$name = $_GET['name'];
$query = "SELECT * FROM hotel WHERE name=$name";
$stmt = $conn->prepare($query);
$stmt->bindValue(':name',$name);
$stmt->execute();
echo
"<table><tr>
<th>hotel_id</th>
<th>name</th>
<th>address</th>
<th>postcode</th>
<th>town</th>
<th>description</th>
<th>rating</th>
<th>image</th></tr>";
while($hotel=$stmt->fetch());
{
echo
"<td>". $hotel['hotel_id']."</td>".
"<td>". $hotel['name']."</td>".
"<td>". $hotel['address']."</td>".
"<td>". $hotel['postcode']."</td>".
"<td>". $hotel['town']."</td>".
"<td>". $hotel['description']."</td>".
"<td>". $hotel['rating']."</td>".
"<td>"."<img src='". $hotel['image']. "'>"."</td>"."</tr>";
//$variable = $hotel['hotel_id'];
}
echo "</table>";
/*
$query2 = "SELECT * FROM booking WHERE hotel_id=$variable";
echo
"<table><tr>
<th>hotel_id</th>
<th>guest_id</th>
<th>payment-type</th>
<th>amount</th>
<th>nights</th></tr>";
$results2 = $conn->query($query2);
if($variable = $results2->fetch()) { echo
"<tr>"."<td>".$variable['hotel_id']."</td>".
"<td>". $variable['guest_id']."</td>".
"<td>". $variable['payment-type']."</td>".
"<td>". "£".$variable['amount']."</td>".
"<td>". $variable['nights']."</td>"."</tr>";
$guest_id = $variable['guest_id'];
}
echo "</table>";
$query3 = "SELECT * FROM guest WHERE guest_id=$guest_id";
echo
"<table><tr>
<th>guest_id</th>
<th>first_name</th>
<th>last_name</th>
<th>address</th>
<th>postcode</th>
<th>town</th></tr>";
$results3 =$conn->query($query3);
while($guest = $results3->fetch()) { echo
"<tr>"."<td>".$guest['guest_id']."</td>".
"<td>". $guest['first_name']."</td>".
"<td>". $guest['last_name']."</td>".
"<td>". $guest['address']."</td>".
"<td>". $guest['postcode']."</td>".
"<td>". $guest['town']."</td>"."</tr>";
}
echo "</table>";
*/
$conn=NULL;
?>
</body>
</html>
I am stuck on this for days now so please help me to make this work and also if there are any ways to reduce and not duplicating same code all over again.
Thanks for any efforts ;)
Please note I am not allowed to use javascript
I changed the pieces identified as probably incorrect and did some tidying up - looks like it should work, certainly there should be nothing wrong with the selection of records based upon the search
<!--
Search ( assumed to be index.php )
----------------------------------
As this page displays results from the search I assume that this
is "index.php" and that the form `POST`s back to this page.
-->
<?php
error_reporting( E_ALL );
?>
<!DOCTYPE html>
<html>
<head>
<title>Hotel Database Search</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="navigation">
<form action="index.php" method="get">
<input type="submit" name="mainpage" value="Main Page" class="submitbut" id="but1" />
</form>
</div>
<form action="index.php" method="post">
<input type="text" name="search" id="searching" />
<input type="submit" name="data_submit" value="Search" id="scan" />
</form>
<?php
/* This is liable to cause an error: headers should not be sent after any output */
if( isset( $_GET['mainpage'] ) ) exit( header( "Location: mainpage.php" ) );
if ( isset( $_POST["data_submit"] ) ){
$search_term = strip_tags( trim( $_POST['search'] ) );
$conn = new PDO( 'mysql:host=localhost;dbname=u1358595', 'root' );
$stmt = $conn->prepare("SELECT * FROM `hotel` h
INNER JOIN `booking` b ON h.`hotel_id`=b.`hotel_id`
INNER JOIN `guest` g ON g.`guest_id`=b.`guest_id`
WHERE `name` LIKE :search_term;");
$stmt->bindValue(':search_term','%' . $search_term . '%');
$stmt->execute();
echo "<table><tr><th>Hotels Matched</th></tr>";
while( $rs= $stmt->fetch(PDO::FETCH_OBJ) ) {
echo "<tr><td><a href='details.php?name=".$rs->name."'>".$rs->name."</a></td></tr>";
}
echo "</table>";
$stmt = $conn->prepare("SELECT * FROM `guest` g
INNER JOIN `booking` b ON g.`guest_id`=b.`guest_id`
INNER JOIN `hotel` On b.`hotel_id`=h.`hotel_id`
WHERE g.`last_name` LIKE :search_term;");
$stmt->bindValue( ':search_term', '%'.$search_term.'%' );
$stmt->execute();
echo "<table><tr><th>Guests Matched</th></tr>";
while( $rs= $stmt->fetch(PDO::FETCH_OBJ) ) {
echo "<tr><td><a href='details.php?name=".$rs->first_name."'>".$rs->last_name."</a></td</tr>";
}
echo "</table>";
$conn = NULL;
}
?>
</body>
</html>
<!--
Results ( assumed to be "details.php" )
---------------------------------------
I again assume that this is the details page and this is linked to
via the results found on "index.php"
-->
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<div class="navigation">
<form action="index.php" method="get">
<input type="submit" name="mainpage" value="Main Page" class="submitbut" id="but1" />
</form>
</div>
<?php
if( !isset( $_GET['name'] ) ) exit("You shouldn't have got to this page");
$conn = new PDO( 'mysql:host=localhost;dbname=u1358595', 'root' );
$name = $_GET['name'];
$query="SELECT * FROM `hotel` WHERE `name`=:name;";
$stmt = $conn->prepare( $query );
$stmt->bindValue( ':name', $name );
$stmt->execute();
echo
"<table>
<tr>
<th>hotel_id</th>
<th>name</th>
<th>address</th>
<th>postcode</th>
<th>town</th>
<th>description</th>
<th>rating</th>
<th>image</th>
</tr>";
while( $rs=$stmt->fetch(PDO::FETCH_OBJ) ){
echo "
<tr>
<td>{$rs->hotel_id}</td>
<td>{$rs->name}</td>
<td>{$rs->address}</td>
<td>{$rs->postcode}</td>
<td>{$rs->town}</td>
<td>{$rs->description}</td>
<td>{$rs->rating}</td>
<td><img src='{$rs->image}'></td>
</tr>";
}
echo "</table>";
$conn=NULL;
?>
</body>
</html>
Hi So this is the code:
Its a page to display my available tables in the database in a drop-down, then display the results in the table. The actual code to do so (in the middle) works perfectly on its own, but when I try to add my template around it I get errors...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="" >
<meta name="description" content="" >
<meta http-equiv="content-type" content="text/html; charset=utf-8" >
<title>SNYSB Archive</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" >
<!-- Location of javascript. -->
<script language="javascript" type="text/javascript" src="swfobject.js" ></script>
</head>
<div id="wrapper">
<div id="header">
<!-- KEEP THIS BIT [ITS FORMATTING] -->
</div>
<!-- end #header -->
<div id="menu">
<ul>
<li>Home</li>
<li>Register</li>
</ul>
</div>
<!-- end #menu -->
<div id="page">
<div id="page-bgtop">
<div id="page-bgbtm">
<div id="content">
<div class="post">
<div class="post-bgtop">
<div class="post-bgbtm">
<h1 class="title">PUT HEADING HERE!</h1>
<div class="entry">
<p class="Body">
<?php
$dbname = 'snysbarchive';
$conn= mysql_connect('localhost', 'root', 'usbw');
if (!$conn) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
if (mysql_select_db($dbname, $conn))
{
?>
<form method="post" action="new 2.php">
<select name="tables">
<?php
while ($row = mysql_fetch_row($result)) {
?>
<?php
echo '<option value="'.$row[0].'">'.$row[0].'</option>';
}
?>
</select>
<input type="submit" value="Show">
</form>
<?php
//mysql_free_result($result);
if (isset($_POST) && isset($_POST['tables']))
{
$tbl=$_POST['tables'];
//echo $_POST['tables']."<br />";
$query="SELECT * from $tbl";
$res=mysql_query($query);
echo $query;
if ($res)
{
?>
<table border="1">
<?php
while ( $row = mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "<td>".$row[3]."</td>";
echo "</tr>";
} ?>
</table>
<?php
}
}
?>
</div>
</div>
</div>
</div>
<div style="clear: both;"> </div>
</div>
<!-- end #content -->
<div id="sidebar">
<ul>
<li>
<h2>Welcome!</h2>
<p>Welcome to SNYSBs archive!
</p>
</li>
<li>
<h2>SNYSB</h2>
<p>
Contact Us!
</p>
</li>
</ul>
</div>
<!-- end #sidebar -->
<div style="clear: both;"> </div>
</div>
</div>
</div>
<!-- end #page -->
<div id="footer">
<p>Copyright (c) 2008 Sitename.com. All rights reserved. Design by Free CSS Templates.</p>
</div>
<!-- end #footer -->
</div>
</body>
</html>
It keeps saying unexpected end but I am not sure how to fix it?
Error Message:Parse error: syntax error, unexpected $end in file on line 128
Thanks
This may also occur when mixing short and normal open tags when the server does not support short-open-tags (<? instead of <?php), even though this wasn't the case in your code.
<?php
$showHeader = true;
if ($showHeader) {
?>
<h1>Hello, World!</h1>
<?
}
?>
Note that the closing bracket will not be registered if the server doesn't support the <? open tag.
Line 50: if (mysql_select_db($dbname, $conn)) has an opening bracket and not a closing one.
You may need to change <? to <?php
you forget to close this block with a } :
if (mysql_select_db($dbname, $conn))
{
?>
Try this code :
<?php
$dbname = 'snysbarchive';
$conn= mysql_connect('localhost', 'root', 'usbw');
if (!$conn) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
if (mysql_select_db($dbname, $conn))
{
?>
<form method="post" action="new 2.php">
<select name="tables">
<?php
while ($row = mysql_fetch_row($result)) {
echo '<option value="'.$row[0].'">'.$row[0].'</option>';
}
?>
</select>
<input type="submit" value="Show">
</form>
<?php
}
//mysql_free_result($result);
if (isset($_POST) && isset($_POST['tables']))
{
$tbl=$_POST['tables'];
//echo $_POST['tables']."<br />";
$query="SELECT * from $tbl";
$res=mysql_query($query);
echo $query;
if ($res)
{
?>
<table border="1">
<?php
while ( $row = mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "<td>".$row[3]."</td>";
echo "</tr>";
}
?>
</table>
<?php
}
}
?>
You have missed a '}' so following if block is not closed.
if (mysql_select_db($dbname, $conn))
{
By adding a } in Line #91 your code will be worked.
But always try to write much cleaner code by following best practices.
You have not selected your database with correct braces around the function.