How to call a PHP function from a HTML button click? - javascript

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>

Related

Refresh page if certein php script is executed

I have a somefile.php and someotherfile.js with the code as below
javascript file
function deleteSelectedRow() {
return (confirm('Are you sure you want to delete this record))
};
<!DOCTYPE html>
<html lang=" en">
<head>
<title> Title </title>
</head>
<body>
<h1>Select the user to delete from the list below </h1>
<form action="" method="POST">
<?php
if(require_once('../SQL/mySQL_connect.php'))
{
$query = "SELECT id, FirstName, LastName, PhoneNumber FROM participants ORDER BY id ASC";
$userDetails = #mysqli_query($mysqli, $query);
}
else
{
echo "Couldn't connect to database";
echo mysqli_error($mysqli);
}
// mysqli_close($mysqli);
?>
<br><br><br>
<table name="userDetailsTable" id="userDetailsTable" align="left" cellspacing="7" cellpadding="8">
<tr>
<td align="center"><b>S No</b></td>
<td align="center"><b>Id</b></td>
<td align="center"><b>Rank</b></td>
<td align="center"><b>First Name</b></td>
<td align="center"><b>Last Name</b></td>
</tr>
<?php
for($i = 1; $i <= mysqli_num_rows($userDetails); $i++)
// while($row=mysqli_fetch_array($userDetails))
{
$row=mysqli_fetch_array($userDetails);
echo '<tr>
<td align ="center" >'. $i .'</td>
<td align ="center" >' . $row['id'] . '</td>
<td align ="center">' . $row['Rank'] . '</td>
<td align ="center">' . $row['FirstName'] . '</td>
<td align ="center">' . $row['LastName'] . '</td>
<td align ="center"> <input type = submit name="delete" value="delete" onclick="return deleteSelectedRow();" ></input></td>';
echo '</tr>';
}
?>
</table>
</form>
<?php
if(isset($_POST['delete']))
{
require_once('../SQL/mySQL_connect.php');
$query="DELETE FROM `participants` WHERE `participants`.`id` = ".$_POST['IDNumber']."";
$response = #mysqli_query($mysqli, $query);
if($response)
{
echo "Deleted from Database Successfully";
}
else
{
echo "Couldn't Delete from database";
echo'<br>';
echo mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
?>
</body>
What this code does is as follows
Connects to database and retrieves the user details
Creates a table and prints out the user details in it
user clicks on delete button in front of any record and it gets deleted after confirmation
A success message is displayed that the message is deleted
What I want to do is that after displaying the success message the above printed table should get updated automatically so that user is confirmed that the id no longer exists in the table
I tried the following solutions
reload page just before the success message is displayed so that user sees the success message as well as the updated table as well (since reload will re-connect to database and refetch the table)
I tried to use "location.reload(true)" command but i can't figure out where to place this line so that it gets executed just before the success message is displayed.
Any help is much appreciated
A few things:
you'll want the delete operation to be the first thing you do on the page (if it's a form submit) because otherwise you'll print the "pre-deleted" table.
you need to pass the ID through post in the form. It's easier if you just have a unique for for every row, and have a hidden ID input for each.
The confirm is better attached to the form submit event, because otherwise you'll miss other, non-click, input methods.
Your delete operation, as it was written in the question, is susceptible to an SQL Injection attack. You'll want to escape that POST value.
Something like the below should work
function deleteSelectedRow() {
return (confirm('Are you sure you want to delete this record))
};
<?php
$message = '';
$connected = false;
if(require_once('../SQL/mySQL_connect.php'))
{
$connected = true;
}
if($connected && isset($_POST['delete']))
{
$id_to_delete = mysqli_real_escape_string($mysqli, $_POST['IDNumber']);//escape value to prevent sql injection attack
$query="DELETE FROM `participants` WHERE `participants`.`id` = ".$id_to_delete."";
$response = #mysqli_query($mysqli, $query);
if($response)
{
$message = "Deleted from Database Successfully";
}
else
{
$message = "Couldn't Delete from database";
$message .='<br>';
$message .= mysqli_error($mysqli);
}
//mysqli_close($mysqli);
}else{
$message = "unable to connect to database";
}
?><!DOCTYPE html>
<html lang=" en">
<head>
<title> Title </title>
</head>
<body>
<h1>Select the user to delete from the list below </h1>
<?php
if($connected)
{
$query = "SELECT id, FirstName, LastName, PhoneNumber FROM participants ORDER BY id ASC";
$userDetails = #mysqli_query($mysqli, $query);
}
else
{
echo "Couldn't connect to database";
echo mysqli_error($mysqli);
}
?>
<br><br><br>
<?php if($message){ /* do we have a success/error message from the delete operation? */ ?>
<p><?php echo $message; ?></p>
<?php } ?>
<table name="userDetailsTable" id="userDetailsTable" align="left" cellspacing="7" cellpadding="8">
<tr>
<td align="center"><b>S No</b></td>
<td align="center"><b>Id</b></td>
<td align="center"><b>Rank</b></td>
<td align="center"><b>First Name</b></td>
<td align="center"><b>Last Name</b></td>
</tr>
<?php
for($i = 1; $i <= mysqli_num_rows($userDetails); $i++)
// while($row=mysqli_fetch_array($userDetails))
{
$row=mysqli_fetch_array($userDetails);
echo '<tr>
<td align ="center" >'. $i .'</td>
<td align ="center" >' . $row['id'] . '</td>
<td align ="center">' . $row['Rank'] . '</td>
<td align ="center">' . $row['FirstName'] . '</td>
<td align ="center">' . $row['LastName'] . '</td>
<td align ="center"> <form action="" method="POST" onsubmit="return deleteSelectedRow();"><input type="hidden" name="IDNumber" value="'.$row['id'].'" /><input type = submit name="delete" value="delete"></form></td>';
echo '</tr>';
}
?>
</table>
<?php if($connected){
mysqli_close($mysqli);
} ?>
</body>
You need to store the Success/Error message in a $_SESSION["flash"] instead of show by echo and after delete the user you must redirect to the same page.
On the top of the page, if isset the $_SESSION["flash"] you can show the message and remove it from the session. In code:
if(isset($_POST['delete']))
{
require_once('../SQL/mySQL_connect.php');
$query="DELETE FROM `participants` WHERE `participants`.`id` = ".$_POST['IDNumber']."";
$response = #mysqli_query($mysqli, $query);
if($response)
{
$_SESSION["flash"] = "Deleted from Database Successfully";
}
else
{
$_SESSION["flash"] = "Couldn't Delete from database";
//echo'<br>';
//echo mysqli_error($mysqli);
}
mysqli_close($mysqli);
header('Location: '.$_SERVER['PHP_SELF']);
}
and on the top of the page of before isset($_POST['delete']):
if(isset($_SESSION["flash"])){
echo $_SESSION["flash"];
unset($_SESSION["flash"]);
}
don't forget to start_session() on the top of the page.
I'll notice that your code have a SQL Injection Vulnerability. You shouldn't do MySQL queries without validate GET and POST input data.

How to post the information using javascript for a preview table

Hey I need to know how to post the information to another php page using javascript to provide a preview table.
Here's my HTML that has a onchange tag that sends the productID to the function.
<form action="Home.php" method="Post">
<div>
<p>
<span class="text">Please Select a product:</span>
<select id="Select_Product" name="Select_Product" onchange="productInfo(this.value)" class="select">
<?php
//setting the select statement and running it
$search = "SELECT * FROM Library.Products order by Name";
$return = mysql_query($search);
//echo "<select id=Select_Product name=Select_Product onchange=productInfo(this.value) class=select>";
while ($row = mysql_fetch_array($return)) {
echo "<option value='" . $row['ProductID'] . "' selected='selected'>".$row['Name'] . "</option>";
}
?>
</select>
</p>
<table>
<tr>
<td>
<input name="action" type="submit"class="button" id="button_Add" value="Add"/>
</td>
<td>
<input name="action" type="submit" class="button" id="button_Remove" value="Remove"/>
</td>
<td>
<input name="action" type="submit" class="button" id="button_empty" value="Empty"/>
</td>
</tr>
</table>
</div>
From there I want it to send it to catalogue.php.
<script>
function productInfo(key) {
//Send key to catalogue.php
}
</script>
If I can get the other page to get that variable I can run a MYSQL command to get the information. Here is what catalogue.php looks like at the moment.
<?php
$sql = "SELECT Name, Price FROM Library.Products WHERE ProductID = " . $product_id;
echo "<table border=\"1\" padding=\"3\" width=\"650px\"><tr><th>Name</th><th>Description</th><th>Price</th><th width=\"80px\">Image</th></tr>";
echo "<tr>";
echo "<td>" .$product_id . "</td>";
echo "<td> Hi</td>";
echo "<td></td>";
echo "<td align=\"center\"><img alt=\"\" src=\"productImages/".$product_id.".jpg\ width=\"120\" height=\"120\"/></td>";
echo "</tr>";
echo "</table><br>";
document.
?>
So in a sense I want to turn the key in productInfo(key) to be assigned to the variable $product_id in catalogue.php. Thanks for helping.
You can add an invisible form :
<script>
function productInfo(key) {
//Send key to catalogue.php
document.getElementById( "key" ).value = key;
document.getElementById( "frm" ).submit(); // SUBMIT FORM.
}
</script>
<form action="catalogue.php" method="post" id="frm"
style="display:none" target="_blank">
<input type="text" id="key" name="key"/>
</form>
catalogue.php needs one little change :
<?php
$product_id = $_POST[ "key" ]; //<================== VALUE FROM THE INVISIBLE FORM.
$sql = "SELECT Name, Price FROM Library.Products WHERE ProductID = " . $product_id;
echo "<table border=\"1\" padding=\"3\" width=\"650px\"><tr><th>Name</th><th>Description</th><th>Price</th><th width=\"80px\">Image</th></tr>";
echo "<tr>";
echo "<td>" .$product_id . "</td>";
echo "<td> Hi</td>";
echo "<td></td>";
echo "<td align=\"center\"><img alt=\"\" src=\"productImages/".$product_id.".jpg\ width=\"120\" height=\"120\"/></td>";
echo "</tr>";
echo "</table><br>";
document.
?>
Or you can use Ajax :
html file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax ( key ) {
$.ajax( { type : 'POST',
data : { 'param' : key },
url : 'catalogue.php',
success: function ( data ) {
document.getElementById( "my_div" ).innerHTML = data;
},
error: function ( data ) {
alert( "error" );
}
});
}
function productInfo( key ) {
//Send key to catalogue.php
myAjax( key );
}
</script>
</head>
<body>
<button onclick="productInfo('123')">Click here to get the data</button>
<div id="my_div">
- data will show here -
</div>
</body>
</html>
catalogue.php
<?php
$key = $_POST[ "param" ];
echo "<table border='1'>" .
" <tr>" .
" <td>$key</td>" .
" <td>ABC</td>" .
" </tr>" .
"</table>";
?>

Hyperlink with variables to create a modal box/popup

Like in the title I would like to use a variable inside the hyperlink to use it into the modal window.
I am not using bootstrap, it is a custom code but it works until I try to put some kind of <a href='#openModal?id=".$VARIABLE."'>
Is it possible to do that?
Regards
Update:
<?php
$query = "SELECT * FROM USER";
$result = mysqli_query ($connection,$query)
or die ("You couldn’t execute query");
echo "<div class='admin-table'>
<table cellspacing='15'>
<td><h3>Last Name</h3></td>
<td><h3>Name</h3></td>
<td><h3>Phone</h3></td>
<td><h3>Address</h3></td>
<td><h3>Postcode</h3></td>
<td><h3>Date of Birth</h3></td>
<td><h3>Email</h3></td>
<td><h3>Password</h3></td>
<td><h3>Role</h3></td>
</tr>";
while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC))
{
extract ($row);
echo "<tr>\n
<td>$USER_LASTNAME</td>\n
<td>$USER_FIRTSNAME</td>\n
<td>$USER_PHONE</td>\n
<td>$USER_ADDRESS</td>\n
<td>$USER_POSTCODE</td>\n
<td>$USER_DOB</td>\n
<td>$USER_EMAIL</td>\n
<td>$USER_PASSWORD</td>\n
<td>$USER_ROLE</td>\n
<td><a href='admin_user.php?id=".$USER_ID."'>Delete</a></td>\n
<td><a href='#openModal?id=".$USER_ID."'>Edit</a></td>\n
</tr>\n";
echo "<tr><td colspan ='15'><hr></td></tr>\n";
}
echo "</table></div>\n";
?>
<div id="openModal?id=<?php echo $USER_ID; ?>" class="modalDialog">
<div>X
<h2>$USER_ID</h2>
</div>
</div>
It is working the modal but its just taking the last id, I have to think another solution to pass the variable.
Many thanks for your help
Update 2:
Thank you very much! Now its working,
<?php
$query = "SELECT * FROM USER;";
$result = mysqli_query ($connection,$query) or die ("You couldn’t execute query");
//First echo the table with all your data as you want
echo "
<div class='admin-table'>
<table cellspacing='15'>
<tr>
<td><h3>Last Name</h3></td>
<td><h3>Name</h3></td>
<td><h3>Phone</h3></td>
<td><h3>Address</h3></td>
<td><h3>Postcode</h3></td>
<td><h3>Date of Birth</h3></td>
<td><h3>Email</h3></td>
<td><h3>Password</h3></td>
<td><h3>Role</h3></td>
</tr>";
//Fetch all rows for each user
while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC)) {
extract ($row);
echo "
<tr>
<td>$USER_LASTNAME</td>
<td>$USER_FIRTSNAME</td>
<td>$USER_PHONE</td>
<td>$USER_ADDRESS</td>
<td>$USER_POSTCODE</td>
<td>$USER_DOB</td>
<td>$USER_EMAIL</td>
<td>$USER_PASSWORD</td>
<td>$USER_ROLE</td>
<td><a href='admin_user.php?id=".$USER_ID."'>Delete</a></td>
<td><a href='#openModal?id=".$USER_ID."'>Edit</a></td>
<div id='openModal?id=".$USER_ID."' class='modalDialog'>
<div><a href='#close' title='Close' class='close'>X</a>
<h2>".$USER_ID."</h2>
<p>You can have additional details here.</p>
</div>
</div>
</tr>
<tr>
<td colspan ='15'><hr></td>
</tr>";
}
echo"
</table>
</div>";
?>
Try this:
echo '<a href="#openModal?id='.$VARIABLE.'">';
Update:
echo '<td>Edit</td>\n';
echo '<td>Delete</td>\n';
any reason you can't use onclick ?
<a href="#" onclick="myJsFunc();">
<script>
function myJsFunc() {
//code to open modal
}
</script>
UPDATE
If i have understood you correct you are trying to make a table showing all users and then when the admin clicks at element a modal pop ups providing additional info for the particular user.
<?php
$query = "SELECT * FROM USER;";
$result = mysqli_query ($connection,$query) or die ("You couldn’t execute query");
//First echo the table with all your data as you want
echo "
<div class='admin-table'>
<table cellspacing='15'>
<tr>
<td><h3>Last Name</h3></td>
<td><h3>Name</h3></td>
<td><h3>Phone</h3></td>
<td><h3>Address</h3></td>
<td><h3>Postcode</h3></td>
<td><h3>Date of Birth</h3></td>
<td><h3>Email</h3></td>
<td><h3>Password</h3></td>
<td><h3>Role</h3></td>
</tr>";
//Fetch all rows for each user
while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC)) {
extract ($row);
echo "
<tr>
<td>$USER_LASTNAME</td>
<td>$USER_FIRTSNAME</td>
<td>$USER_PHONE</td>
<td>$USER_ADDRESS</td>
<td>$USER_POSTCODE</td>
<td>$USER_DOB</td>
<td>$USER_EMAIL</td>
<td>$USER_PASSWORD</td>
<td>$USER_ROLE</td>
<td><a href='admin_user.php?id=".$USER_ID."'>Delete</a></td>
<td><a href='#openModal".$USER_ID."'>Edit</a></td>
</tr>
<tr>
<td colspan ='15'><hr></td>
</tr>";
}
echo"
</table>
</div>";
//Fetch again the rows to make the modals with the edit info
while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC)) {
extract ($row);
echo '
<div id="openModal'.$USER_ID.'" class="modalDialog">
<div>X
<h2>'.$USER_ID.'</h2>
<p>You can have additional details here.</p>
</div>
</div>';
}
?>
Old answer before the comments
It seems that single quotes and/or double quotes aren't escaped properly.
Also remember that in PHP string concatenation is made using " . " (dot) and in JavaScript using " + " (plus).
Update 1
I think that if you use the following you will be ok.
echo '<td>Delete</td>';
echo '<td>Edit</td>';
Update 2
Don't forget to add $variable at div too so <a> and div id are the same the same. E.g.
echo '<div id="openModal'.$variable.'" class="modalDialog"></div>';

htmlspecialchars_decode causes width issues

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;
}

get data from HTML table dynamically generated

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.

Categories

Resources