I have been messing about creating stuff in PHP so decided to create a site... However, when I am pulling things from my DB it is resizing the text and pushing things off of the page :/
I have tested with plain text and my site is displaying correctly:
http://gentetcreations.co.uk/blog-2.php
However, with HTML text it displays in a weird way and I can't seem to get it fixed:
http://gentetcreations.co.uk/blog-1.php
JSFidle here!
<!DOCTYPE HTML>
<html>
<head>
<title>GentetCreations</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div id="main">
<?php
include("inc/pageHead.php");
?>
<div id="site_content">
<?php
include("inc/side.php");
?>
<div id="content">
<?php
include("inc/dbconnection.php");
$id = $_GET['id'];
$id = trim($id);
$result = mysqli_query($conn, "SELECT * FROM blog WHERE authorised = 1 AND blog_id = '" . $id . "'");
if(!$result) {
die("Database query failed: " . mysqli_error($conn));
} else {
$rows = mysqli_num_rows($result);
if ($rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tags = "";
$result2 = mysqli_query($conn, "SELECT * FROM tags WHERE blog_id = '" . $row['blog_id'] . "'");
if(!$result2) {
die("A Database query failed: " . mysqli_error($conn));
} else {
while ($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
$rawTag = $row2['tag'];
$tag = str_replace(" ", "", $rawTag);
$tags .= "<a href='tag-" . $tag . ".php'>" . $tag . "</a> ";
}
}
echo "
<span class='mainContentWidth'>
<table>
<tr>
<th>
<a href='blog-" . $row['blog_id'] . ".php'>
<h2>" . $row['title'] . "</h2>
</a>
</th>
</tr>
<tr>
<td>
<p>" . date("d/m/Y", strtotime($row['createdDate'])) . "</p><br />
<span>" . $row['content'] . "</span>
<br />
<br />
<span><small>Tags: " . $tags . "</small></span>
</td>
</tr>
</table>
</span>";
} //$row = mysqli_fetch_array($result, MYSQLi_ASSOC)
} else { //$rows > 0
echo "<br /><h1>An error occurred.</h1><br /><h2>The blog you were looking for could not be found.</h2>";
}
}
?>
</div>
</div>
<?php
include("inc/footer.php");
?>
</div>
</body>
</html>
I am new to doing web based coding so I am really confused here and not too sure what is going on.
If anyone could help me here or push me in the right direction to display everything correctly, I would be very happy!
You have block level elements inside a span tag. You should avoid doing that.
For current issue you can add this CSS
table tr td > span {
width: 615px;
}
Related
I am trying to dynamically create a script but it is not working.
I tried:
echo '<script type="text/javascript">alert("hello!");</script>';
echo '<script>alert("hello!");</script>';
echo '<script type="text/javascript">$( document ).ready(function() {alert("hello!");});</script>';
please help
Upon request here is the full code where the script is dynamically created at:
In fact , there is a php page that has a javascript file that calls an ajax function on press of a button that sends the type and calls this php page , this one will dynamically create the bootstrap carousel with the right pictures (give the right category)
<?php
//the login database info goes here too
$_type= $_POST['Type'];
$_category= $_POST['Category'];
if($_type == "adult")
{
$title = "FOR THE ADULTS";
}
else
$title = "FOR THE KIDS";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT image,imagealt FROM gallery where type='".$_type."' AND category='".$_category."' ";
$result = $conn->query($sql);
$result1 = $conn->query($sql);
?>
<tr>
<td class="GalleryImageInfo">
<div id="parent_back" >
<h1>GALLERY</h1>
<p class="ForAdults"> <?php echo $title ?> </p>
<p class="ButtonGalleryPreview" style="text-align:center"> <?php echo $_category ?> </p>
<?php
$countit = 0;
if ($result->num_rows > 0) {
// output data of each row
?>
<div id="slider_caption" > <div>
<?php
while($row = $result->fetch_assoc()) {
$image_description = $row["imgdesc"];
echo "
<div class=\"carousel-caption caption-".$countit."\">
<h3>Description</h3>
<p>".$image_description."</p></div>";
$countit++;
}
echo "</div></div>";
echo "<p class=\"GalleryImageBack\" style=\"font-family:BandaBold; color:#6c555e; font-size:15px;\"><i class=\"fa fa-arrow-circle-left\" style=\"margin-right:10px; font-size:15px;\" ></i>BACK</p>
</div>
</td>
<td style=\"width:100%\">
<div class=\"container\" style=\"width:100% ; padding:0px !important;\">
<div id=\"myCarousel2\" class=\"carousel slide\" data-ride=\"carousel\">
<!-- Wrapper for slides -->
<div class=\"carousel-inner\">";
$firstitem = true;
while($row = $result1->fetch_assoc()) {
//echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
$image_url = $row["image"];
$image_alt = $row["imagealt"];
if($firstitem)
{ echo"<div class=\"item active\">
<img src=\" $image_url \"
alt=\".$image_alt.\" style=\"width:100%;\">
</div>";
$firstitem= false;
}
else
echo"<div class=\"item\">
<img src=\" $image_url \"
alt=\".$image_alt.\" style=\"width:100%;\">
</div>";
}
echo " </div>
<!-- Left and right controls -->
<a class=\"left carousel-control\" href=\"#myCarousel2\" data-slide=\"prev\">
<span class=\"glyphicon glyphicon-chevron-left\"></span>
<span class=\"sr-only\">Previous</span>
</a>
<a class=\"right carousel-control\" href=\"#myCarousel2\" data-slide=\"next\">
<span class=\"glyphicon glyphicon-chevron-right\"></span>
<span class=\"sr-only\">Next</span>
</a>
</div>
</div>
</td>
</tr>";
echo "<script type=\"text/javascript\">$(document).ready(function() {
alert(\"hello!\");
});</script>";
}
else {
echo "0 results";
}
$conn->close();
?>
check if you added the jquery script in this page or not.
I have an SQL-database with many tables. Now I would like to create an input-form to be able to get data into the db without writing the entire sql-code every time. And this should work as follows:
All table names are listed in a drop-down menu. After having selected a table name, a new table with 4 columns is created automatically:
The first column of this table simply contains an increasing number.
The second column contains the field-names of the selected table.
In the third column there are empty input fields to enter the values for the database. Only in the third line (=product name) there is a drop-down menu with all product names from the main-table of the db.
The fourth column contains the data type (e.g. int or varchar)
All tables in the database have the same structure in the first 3 columns: the first column contains the table-id, the second column the foreign-key (=master_id) and the third column the product_name.
Up to this point, the script works well with the following 2 php-files (javasql.php and getuser.php):
javasql.php:
enter code here
<!DOCTYPE html>
<html>
<head>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="" class="optdrugs">please select</option>
<?php
include("files/zugriff.inc.php"); // database Access
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'product'";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<option class="optdrugs" value="'. $row['TABLE_NAME'] . '">' .
$row['TABLE_NAME']. '</option>';
echo '<br>';
}
?>
</select>
</form>
<br>
<div id="txtHint"><b>Bitte Tabelle auswählen:</b>
<br>
<?php
if (isset($_POST["submit"])) {
$sent = $_POST['sent'];
$q = $_POST['tablename'];
$column_passed = unserialize($_POST['column']); // content of array
$column is passed from getuser.php
foreach ($_POST["insertvalue"] as $key => $value) {
echo $value . "<br>";
$werte[] = "'$value'";
}
$sql="INSERT INTO $q ($column_passed) VALUES (" .
implode(", ", $werte) . ")"; // data entry
mysqli_query($db, $sql);
if (mysqli_affected_rows($db) > 0) {
echo "<h3 style='color:blue'>successful</h3>";
} else {
echo "<h3 style='color:red'>not
successful</h3>";
}
}
?>
</div>
</body>
</html>
enter code here
getuser.php:
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<form id="formdatabase" name="formdatabase" action="javasql.php"
method="post">
<input type="hidden" name="sent" value="yes">
<?php
$q = strval($_GET['q']);
$con = mysqli_connect('localhost','root','','product');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM $q";
$result = mysqli_query($con,$sql);
$numcols = mysqli_num_fields($result); // gets number of columns in result table
$field = mysqli_fetch_fields($result); // gets the column names from the result table
$data_type_array = array(
1=>'tinyint',
2=>'smallint',
3=>'int',
4=>'float',
5=>'double',
7=>'timestamp',
8=>'bigint',
9=>'mediumint',
10=>'date',
11=>'time',
12=>'datetime',
13=>'year',
16=>'bit',
252=>'text',
253=>'varchar',
254=>'char',
246=>'decimal'
);
$data_type_array = array_flip($data_type_array);
echo "<table>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th><th>" . 'Column names' . "</th>
<th>" . 'Values for db-entry' . "</th><th>" . 'Type' . "</th>";
echo "</tr>";
echo "<tr>";
$nr = 1;
for($x=0;$x<$numcols;$x++):?>
<td><?= $nr; ?></td>
<td><?= $field[$x]->name; ?></td>
<?= $column[] = $field[$x]->name; ?>
<td>
<?php
if ($field[$x]->name == 'Name') { // if-Beginn
?>
<select name="insertvalue[<?= $x; ?>]" id="insertvalue<?=
$x; ?>" size="1" onchange = "javascript:getSelectedRow()">
<?php
include("files/zugriff.inc.php");
$sql = "SELECT * FROM product_main ORDER BY Name";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<option class="optdrugs" value='. $row['Name'] . '>' .
$row['Name'] . '</option>';
echo '<br>';
}
?>
</select>
<?php
$name_option = "";
} else {
$name_option = "<input type='text' id='insertvalue" . $x . "'
name='insertvalue[" . $x . "]' size='50'>";
echo $name_option;
}
?>
</td>
<?php
$key = array_search($field[$x]->type, $data_type_array);
if($key !== false){
echo "<td>" . $key . "</td>";
}else{
echo "<td>" . $field[$x]->type . "</td>";
}
?>
<td><?= $field[$x]->type; ?></td>
<?= $nr = $nr + 1; ?>
</tr>
<?php endfor;
echo "</table>";
mysqli_close($con);
?>
<input type="hidden" name="tablename" value="<?= $q; ?>">
<input type="hidden" name="column" value="<?php echo htmlentities
(serialize($column)); ?>">
<input type="submit" value="Enter values" name="submit">
</form>
</body>
</html>
Since I need the master_id (= foreign key) in addition to the product-name for database entry, I would like to extend my script, so that the respective master_id is automatically sent to the input field in line 2, when a product-name is selected in line 3 ... without clicking a button. I tried to do this with javascript but it didn´t work. As far as I know, the solution would be to use AJAX but unfortunately, I am not very used to AJAX.
I would be more than happy, if someone could help me to solve this problem!
I am trying to display MySQL results (with and without a search) using three divisions. Div 1 has radio buttons for selecting the viewing the results. Div 2 has a text that states all members are displayed, a text search box for Name, and a drop-down menu for Type. The results of the search are displayed in Div 3.
When All Members is selected the text "Display All Members" shows in Div 2 and the correct data is displayed in Div 3 (works correctly). When the Name radio button is selected the correct text search box displays in Div 2 but I receive the following errors in Div 3:
Warning: mysqli_query(): Couldn't fetch mysqli in /home/desgar20/elrenochamber.com/member_dir_test2.php on line 171
Warning: mysqli_error() expects exactly 1 parameter, 0 given in /home/desgar20/elrenochamber.com/member_dir_test2.php on line 173
Could not access database:
If I enter text into the search box and submit, Div 2 and Div 3 go blank
I am using javascript to show/hide the divisions and php for the search.
I have searched for answers but have not found anything to resolve this issue. I don't know what I am missing. Help- -need advice.
<style type="text/css">
.box {
display: none;
}
</style>
<script type="text/javascript">
//Show or application part based on selection
$(document).ready(function(){
$('input[type="radio"]').click(function(){
if($(this).attr("value")=="all"){
$(".box").not(".all").hide();
$(".all").show();
$(".all_listing").show();
}
if($(this).attr("value")=="name"){
$(".box").not(".name").hide();
$(".name").show();
$(".all_name").show();
}
if($(this).attr("value")=="type"){
$(".box").not(".type").hide();
$(".type").show();
$(".all_type").show();
}
});
});
</script>
</head>
<body>
<?php
require_once 'php/dbconnect.php'; // Connect to database
$connection = db_connect();
?>
<div id="container">
<div id="service">
<div id="web">
<img width="150px" src="images/search1.png" />
<h3>Member <strong><span class="green">Directory</span></strong></h3>
<strong>View Members By:</strong><br /><br />
<div id="sortOptions">
<label><input type="radio" name="sortRadio" value="all"> All Members</label><br />
<label><input type="radio" name="sortRadio" value="name"> Name</label><br />
<label><input type="radio" name="sortRadio" value="type"> Type</label>
</div><!-- sortOptions -->
</div><!-- end web -->
<div id="vector">
<div class="all box">
<h3>Display <strong><span class="green">All Members</span></strong></h3>
<p>All Members Displayed</p>
</div><!-- all box -->
<div class="name box">
<h3>Display by <strong><span class="green">Member Name</span></strong></h3>
<p><form name="namesearch" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>">
Name: <input type="text" name="find">
<input type="submit" name="search" value="Search Names">
</form></p>
</div><!-- name box -->
<div class="type box">
<h3>Display by <strong><span class="green">Member Type</span></strong></h3>
<p><form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="post">
Type: <select name="type" id="type">
<option value="">-- Select A Type --</option>
<?php
$query = "SELECT * FROM select_type"; //create type drop-down menu
$result = mysqli_query($connection, $query);
while ($line = mysqli_fetch_array($result)) {
echo "<option value='". $line['type'] ."'>". $line['type']."</option>";
}
?>
</select>
<input type="submit" name="searchType" value="Search Types">
</form>
</div><!-- type box -->
</div><!-- end vector -->
</div><!-- end service-->
<div id="media" class="group">
<div class="all_listing box">
<p>Directory Listing</p>
<!-- Start Directory Listing -->
<?php
$sql = "SELECT * FROM members ORDER BY name"; // Database query and results
$result = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($result)) {
// Check record for website
if ($row['web']!== "") {
echo "<a target=blank href=". $row['web'] . ">" .$row["name"] . "</a><br> " .
"". $row["type"] . "<br>" .
"Address: " . $row["physicaladdress"] . "<br>" .
"Phone: " . $row["phone"] . "<br>" . "<hr>";
}
else {
echo $row["name"]. "<br> " .
"". $row["type"] . "<br>" .
"Address: " . $row["physicaladdress"] . "<br>" .
"Phone: " . $row["phone"] . "<br>" . "<hr>";
}
}
$connection->close();
?>
</div><!-- all_listing box -->
<div class="all_name box">
<p>Results based on Name Search</p>
<?php
if (isset($_POST['search'])) { // Has "Select Names button ben pushed
$find = $_POST['find'];
$sql = "SELECT * FROM members WHERE name LIKE '%" . $find . "%' ";
$result = mysqli_query($connection, $sql);
if(! $result) {
die ('Could not access database: ' . mysqli_error());
}
while($row = mysqli_fetch_array($result)) {
// Check record for website
if ($row['web']!== "") {
echo "<a target=blank href=". $row['web'] . ">" .$row["name"] . "</a><br> " .
"". $row["type"] . "<br>" .
"Address: " . $row["physicaladdress"] . "<br>" .
"Phone: " . $row["phone"] . "<br>" . "<hr>";
}
else {
echo $row["name"]. "<br> " .
"". $row["type"] . "<br>" .
"Address: " . $row["physicaladdress"] . "<br>" .
"Phone: " . $row["phone"] . "<br>" . "<hr>";
}
}
}
?>
</div><!-- all_name box -->
</body>
</html>
I modified the code as recommendation but still receive the same errors as mention above. Here is the area that I am having difficulty with:
This is the division (div 1) that will display the search option in div 2:
<div id="web">
<div id="sort_options">
<label><input type="radio" name="sortRadio" value="name"> Name</label><br />
</div><!-- sort_options -->
</div><!-- end web -->
This is the search feature for div 2:
<div class="name box">
<form name="namesearch" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>">
Name: <input type="text" name="find">
<input type="submit" name="search" value="Search Names">
</form></p>
</div>
This is the php code in div 3 to run the query with input from div 2:
<div class="all_name box">
<?php
if (isset($_POST['search']))
{
$find = $_POST['find'];
$sql = "SELECT * FROM members WHERE name LIKE '%" . $find . "%' ";
$result = mysqli_query($connection, $sql);
if ( $result == false )
{
echo ("Error description: " . mysqli_error($connection));
}
else
{
while($row = mysqli_fetch_array($result))
{
// Check record for website
if ($row['web']!== "")
{
echo "<a target=blank href=". $row['web'] .">" .$row["name"] . "</a><br> " .
"". $row["type"] . "<br>" .
"Address: " . $row["physicaladdress"] . "<br>" .
"Phone: " . $row["phone"] . "<br>" . "<hr>";
}
else
{
echo $row["name"]. "<br> " .
"". $row["type"] . "<br>" .
"Address: " . $row["physicaladdress"] . "<br>" .
"Phone: " . $row["phone"] . "<br>" . "<hr>";
}
}
}
}
?>
</div>
What am I doing wrong here?
Change this snippet:
$sql = "SELECT * FROM members ORDER BY name"; // Database query and results
$result = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($result)) {
to at least
$sql = "SELECT * FROM members ORDER BY name"; // Database query and results
$result = mysqli_query($connection, $sql);
while($result !== false && $row = mysqli_fetch_array($result)) {
Reason: If your query is faulty, $result will have the value false which will cause the given error.
Better code would be like this:
$sql = "SELECT * FROM members ORDER BY name"; // Database query and results
$result = mysqli_query($connection, $sql);
if ( $result == false )
{
// handle error with mysqli_... functions
}
else
{
while($row = mysqli_fetch_array($result)) {
...
As always: take the error as standard, success is the exception!
i'm new to Html , php , javascript. I'm using a table generated from mysql query:
<?php
session_start ();
require_once ('auth.php');
require_once ('connection.php');
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="example">
<?php
$result = $mysqli->query ( "Select name ,date from table" );
while ( $row = $result->fetch_assoc () ) {
echo "<tr>".
"<td>" . $row ['name'] . "</td>
<td>" . $row ['date'] . "</td>
</tr>";
}
$result->free ();
?>
</table>
</body>
</html>
Now i want to select a row , redirect to another page transferring data from the selected row to the new page. Thanks for your help
Try this:
<?php
session_start ();
require_once ('auth.php');
require_once ('connection.php');
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="example">
<?php
$result = $mysqli->query ( "Select name ,date from table" );
while ( $row = $result->fetch_assoc () ) {
$url = "second.php?name={$row ['name']}&date={$row ['date']}";
echo "<tr>".
"<td>" . $row ['name'] . "</td>
<td>" . $row ['date'] . "</td>
</tr>";
}
$result->free ();
?>
</table>
</body>
</html>
Where second.php is the action page where you can get the passed parameters name and date using $_GET['name'], $_GET['date'] respectively.
I would additionally select the id (if the table has any) or any other unique key. Then in the output you can add a link to something like display.php?id=X with X being the unique key from this row.
Then, in the display.php you can just use the query "SELECT name, date FROM table WHERE id = " . intval($_GET['id']) . " to select the single row and display it just like you did on the other page.
Can someone help me with some javascript that will allow me to call a function when I click on a button?
I know this has been posted before, but every answer I have seen is too vague and I have been at this for 8 hours now :(
Please bear in mind I am a javascript beginner.
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php include 'connect.php'; ?>
<table border cellpadding=5>
<div>
<tr>
<th>Report</th>
<th></th>
</tr>
<tr>
<td>Students with highest scores</td>
<td>
<button type= button>Generate report</button>
</td>
</div>
</table>
<?php
function highestScore()
{
$data = mysql_query("SELECT t.Test_name, s.Student_firstname, s.Student_surname, sc.Result
FROM Tests t
JOIN Scores sc ON t.id_Tests = sc.Tests_id_Tests
JOIN Students s ON sc.Students_id_Students = s.id_Students
WHERE t.id_Tests = 1
ORDER BY sc.Result DESC");
if(!$data)
{
die("Invalid Query: " . mysql_error());
}
Print"<table border cellpadding=5>";
while($info = mysql_fetch_array($data))
{
Print"<tr>";
Print "<th>Test:</th> <td>" . $info['Test_name'] . "</td> ";
Print "<th>First Name:</th> <td>" . $info['Student_firstname'] . "</td> ";
Print "<th>Surname:</th> <td>" . $info['Student_surname'] . "</td> ";
Print "<th>Result:</th> <td>" . $info['Result'] . "</td> ";
}
Print "</table>";
}
?>
</body>
I want to use the "Generate report" button I have made, to execute the "highestScore" function.
The function creates a table of values from a mySQL database.
There will eventually be more buttons which bring up different tables.
Any help is appreciated.
HTML and Javascript run on the browser while PHP runs on the server. You will have to make another server call either by using AJAX or refreshing the page. Here's how to do it with AJAX without refreshing the page. ($.ajax docs)
Create a new PHP page: query.php with the following code:
<?php
$data = mysql_query("SELECT t.Test_name, s.Student_firstname, s.Student_surname, sc.Result
FROM Tests t
JOIN Scores sc ON t.id_Tests = sc.Tests_id_Tests
JOIN Students s ON sc.Students_id_Students = s.id_Students
WHERE t.id_Tests = 1
ORDER BY sc.Result DESC");
if(!$data)
{
die("Invalid Query: " . mysql_error());
}
Print"<table border cellpadding=5>";
while($info = mysql_fetch_array($data))
{
Print"<tr>";
Print "<th>Test:</th> <td>" . $info['Test_name'] . "</td> ";
Print "<th>First Name:</th> <td>" . $info['Student_firstname'] . "</td> ";
Print "<th>Surname:</th> <td>" . $info['Student_surname'] . "</td> ";
Print "<th>Result:</th> <td>" . $info['Result'] . "</td> ";
}
Print "</table>";
?>
Use the button's click event to run an ajax request: (Add the following script to your HTML page)
$(function(){
$('button').click(function(){
$.ajax({
url:'query.php',
success:function(response){ alert(response); }
}); // this will alert the code generated in example.php
});
});
Instead of using button, use a form with a submit button. Send a request by POST, and detect that in PHP using isset($_POST['report']) and then display your report.
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php include 'connect.php'; ?>
<table border cellpadding=5>
<div>
<tr>
<th>Report</th>
<th></th>
</tr>
<tr>
<td>Students with highest scores</td>
<td>
<form method="POST">
<input type="submit" name="report">Generate report</button>
</form>
</td>
</div>
</table>
<?php
function highestScore()
{
$data = mysql_query("SELECT t.Test_name, s.Student_firstname, s.Student_surname, sc.Result
FROM Tests t
JOIN Scores sc ON t.id_Tests = sc.Tests_id_Tests
JOIN Students s ON sc.Students_id_Students = s.id_Students
WHERE t.id_Tests = 1
ORDER BY sc.Result DESC");
if(!$data)
{
die("Invalid Query: " . mysql_error());
}
Print"<table border cellpadding=5>";
while($info = mysql_fetch_array($data))
{
Print"<tr>";
Print "<th>Test:</th> <td>" . $info['Test_name'] . "</td> ";
Print "<th>First Name:</th> <td>" . $info['Student_firstname'] . "</td> ";
Print "<th>Surname:</th> <td>" . $info['Student_surname'] . "</td> ";
Print "<th>Result:</th> <td>" . $info['Result'] . "</td> ";
}
Print "</table>";
}
if (isset($_POST['report'])) {
highestScore();
}
?>
</body>
A raw button doesn't make sense in pure HTML. It does just nothing - except looking like a button.
You may use it in conjunction with JavaScript:
<form action="input_button.htm">
<textarea cols="20" rows="4" name="field1"></textarea>
<input type="button" name="Text 1" value="Add some new Text"
onclick="this.form. field1.value='Some new Text'">
</form>
This button executes a JavaScript through a click on it - and replaces the textarea named field1.
So you want this all on one page so the first thing you need is form html tag wrapped around the button, I have named mine 'submit' and set the action to the page itself <?php echo $_SERVER['PHP_SELF']; ?>. When the button is clicked it will preform your php code
Script
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php include 'connect.php'; ?>
<table border cellpadding=5>
<div>
<tr>
<th>Report</th>
<th></th>
</tr>
<tr>
<td>Students with highest scores</td>
<td>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- Calls for the PHP script on the page-->
<button type= button>Generate report</button>
</form>
</td>
</div>
</table>
<?php
//Script that is called
if(isset($_POST['submit'])){ //The ID of the form we used is 'submit' so when that is clicked it will execute this
function highestScore()
{
$data = mysql_query("SELECT t.Test_name, s.Student_firstname, s.Student_surname, sc.Result
FROM Tests t
JOIN Scores sc ON t.id_Tests = sc.Tests_id_Tests
JOIN Students s ON sc.Students_id_Students = s.id_Students
WHERE t.id_Tests = 1
ORDER BY sc.Result DESC");
if(!$data)
{
die("Invalid Query: " . mysql_error());
}
Print"<table border cellpadding=5>";
while($info = mysql_fetch_array($data))
{
Print"<tr>";
Print "<th>Test:</th> <td>" . $info['Test_name'] . "</td> ";
Print "<th>First Name:</th> <td>" . $info['Student_firstname'] . "</td> ";
Print "<th>Surname:</th> <td>" . $info['Student_surname'] . "</td> ";
Print "<th>Result:</th> <td>" . $info['Result'] . "</td> ";
}
Print "</table>";
}
highestScore(); //executes your function you created
}
?>
</body>
HTML and JavaScript run on the browser while PHP runs on the server. You have to write Ajax or java-script.In java-script you can call the php page and do your stuff in that page.And it would be the better approach.You can pass the variable also.I post a example here.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function removeItem(oButton)
{
var hello = "hello";
var world = "world";
window.location.href = "trytest.php?w1=" + hello + "&w2=" + world;//Your page location
}
</script>
</head>
<body>
<form>
<h2>This is the test </h2>
<button type="show" onclick="removeItem(this); return false;">Test</button>
</body>
</html>