How to create a new page from a clickable row table - javascript

I have a problem and i can't find any solution on the internet.
So i have a db with about 20 columns. I print from this db only 5 columns for a preview like this:
<?php
$host = "localhost";
$user = "user";
$pass = "";
$db_name = "db_test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT id,first,sec,school,data FROM test");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border ="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
After the table is print, I want when click is press to create a new page with all the records from the db for that specific id. I have search over the internet but i can't find any solution. Can anyone help me ?:) Thanks in advice.

I’ve take the liberty of making a few changes to the structure of the code to make it simpler.
The solution is to embed something in an anchor (a) which has a query string linking to the next page. Something of this nature:
details.php?id=…
Anyway, here is a solution:
$thead=array();
$tbody=array();
// Set Properties
$all_property = array('id','first','sec','school','data'); // ***
// Note: corrected an error which incorrectly imploded thead:
$thead=sprintf('<tr>%s</tr>',implode('',$all_property)); // implode & put into a proper row
// Get Data
while ($row = mysqli_fetch_array($result)) {
$tr=array();
foreach ($all_property as $item) {
// Here is a solution: Make id clickable
if($item=='id')
$tr[]=sprintf('<th>%s</th>',$item,$item);
else $tr[]=sprintf('<td>%s</td>');
}
$tbody[]=sprintf('<tr>%s</tr>',implode('',$tr));
}
And in the HTML after the PHP block:
<table class="">
<thead>
<?php print $thead; ?>
</thead>
<tbody>
<?php print $tbody; ?>
<tbody>
</table>
Note the following points:
You shouldn’t put the logic into the HTML part of the document. Here I have just put the data into some variables to be output when the time comes. It’s cleaner and easier to maintain.
The recommend way to push onto an array is to use the $array[]=… notation.
I’m not sure why you are reading the column names if you already know that for your SQL query. However, I’ve left it that way.
I’ve also include suitable th elements and table sections.
That might work …

Basically you can play with hide() and show() using Jquery to achieve this. Initially you load all columns from the db and next you hide using some jquery functions. So on click the table again call jquery show method to display remaining columns

For that, use jQuery or other javascript supports. Basically redirect user to another page with "page?id=1". then extract id from url then use jQuery or js to load the corresponding values.
create a new page with empty form fields. then on load, get url parameter and use javascript to fill the fields.

<?php
$host = "localhost";
$user = "user";
$pass = "";
$db_name = "db";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
echo '<table class="data-table" border ="1">
<tr class="data-heading">'; //initialize table tag
$result = mysqli_query($connection,"SELECT id,firstname,lastname,email FROM test");
// Set Properties
$all_property = array('id','first','sec','school','data'); // ***
$thead=sprintf('<tr>%s</tr>',implode('',$thead)); // implode & put into a proper row
// Get Data
while ($row = mysql_fetch_array($result)) {
$tr=array();
foreach ($all_property as $item) {
// Here is a solution: Make id clickable
if($item=='id')
$tr[]=sprintf('<th>%s</th>',$item,$item);
else $tr[]=sprintf('<td>%s</td>');
}
$tbody[]=sprintf('<tr>%s</tr>',implode('',$tr));
}
?>
<table class="data-heading">
<thead>
<?php print $thead; ?>
</thead>
<tbody>
<?php print $tbody; ?>
<tbody>

Related

How to make buttons on client side that redirect to a php page with database information

I am brand new to programming and I had a unique (I think) question.
I made a MySql database for storing employee records. I am able to submit new employee data to the db and am able to retrieve employee data from the db and display it in an HTML table.
I want to create buttons on the table for each ID#. Each button would redirect you to a different php page and display the employee information associated with the ID# whose button was clicked.
Does anyone know how would I go about doing this?
echo '<table border="0" cellspacing="25" cellpadding="2">
<tr>
<td>ID</td>
<td>First</td>
<td>Last</td>
<td>SIN</td>
<td>Password</td>
</tr>';
function loadList() {
include_once 'includes/dbh.inc.php';
try {
$sqlarray = "SELECT * FROM employee;";
$result = mysqli_query($conn, $sqlarray);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$employeeID = $row['id'] . "<br>";
$employeeFN = $row['firstname'] . "<br>";
$employeeLN = $row['lastname'] . "<br>";
$employeeSIN = $row['sin_'] . "<br>";
$employeePASS = $row['pass_'] . "<br>";
echo '<tr>
<td>'.$employeeID.'</td>
<td>'.$employeeFN.'</td>
<td>'.$employeeLN.'</td>
<td>'.$employeeSIN.'</td>
<td>'.$employeePASS.'</td>
</tr>';
}
}
else {
echo "error no data";
}
} catch (\Exception $e) {
echo ("error");
}
}
Mate, welcome in the programming world. You can create a anchor tag which will redirect user to a new php page with employee id in URL. check below code:
echo '<tr>
<td>'.$employeeID.'</td>
<td>'.$employeeFN.'</td>
<td>'.$employeeLN.'</td>
<td>'.$employeeSIN.'</td>
<td>'.$employeePASS.'</td>
<td><a href="details.php?id='$employeeID.'>View Details</a></td>
</tr>'
Here you need to create a new php page with details.php name. There you need to get employee id by GET global variable and need to fetch details from database to show. Check below code:
<?php
include_once 'includes/dbh.inc.php';
$employeeId = $_GET['id'];
$sqlarray = "SELECT * FROM employee where id = '".$employeeId."';";
$result = mysqli_query($conn, $sqlarray);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$employeeDetails = mysql_fetch_row($result);
Here $employeeDetails has all data which you can use to render in HTML. But please read little bit about SQL injection before using the same code to avoid crashes. Hope it helps you.
You could do like this by adding <a></a> tag
echo '<tr>
<td><a href="show.php?id='$employeeID.'>Show</a></td>
<td>'.$employeeID.'</td>
<td>'.$employeeFN.'</td>
<td>'.$employeeLN.'</td>
<td>'.$employeeSIN.'</td>
<td>'.$employeePASS.'</td>
</tr>';
And in show.php page get this id by $_GET['id']

Calling a PHP function in a dynamically created HTML table

I have a HTML Table that is populated from a mySQL table as seen below:
$sql = "SELECT `ID`,`SaveName`, `CourseNumber`, `FormType`, `POSTString`, `DateModified` FROM `SavedFormsTable` WHERE 1";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Save File Name</th>
<th>Course Number</th>
<th>Date Modified</th>
<th>Load Old Form</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['SaveName'] . "</td>";
echo "<td>" . $row['CourseNumber'] . "</td>";
echo "<td>" . $row['DateModified'] . "</td>";
echo '<td><button type="button" onclick="LoadFormJS('.$row['ID'].');">Load Form!</button>';
echo "</tr>";
}
echo "</table>";
My problem is on the 4th line from the bottom. in the HTML <button>
I am trying to create a button IN THE HTML TABLE that when clicked will call a PHP function. But i have to echo the HTML in order to create the table from the mySQL database.
Is there a clever way of to do this???
The PHP function I need to call:
function LoadFormPHP($ID){
$con=mysqli_connect("","User636626","EasyPassword","pansyc5_SavedForms");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = sprintf("SELECT `POSTString` FROM `SavedFormsTable` WHERE `ID`=%d",$ID);
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
//mysql_close($con);
$_POST = unserialize(base64_decode($row["POSTString"]));
}
The JS function i tried (and failed) to call the PHP function from:
<script>
function LoadFormJS(ID){
alert(ID);
<?php LoadFormPHP(ID) ?>
}
</script>
You cannot mix html (client side) and php (server side) together. For this kind of cases AJAX is a good tool. The onclick can contain a request to a javascript function that fires the request back to your server, and returns the desired HTML.
You just have some syntax issues -
echo '<td><button type="button" onclick="LoadForm(' .$row['ID'] .')">Load Form!</button>';
What you could do to call the PHP function is to surround your button with a form using a hidden input to hold the value of $row['ID']. Clicking on the button would load the proper form at that point and you could ditch the inline JS in favor of a form action.

Elements not included in div when added using Javascript

I have a list of products on my website a Catalogue. The following PHP Code uses javascript to create a div and insert all the product description links inside it.
$sql = "SELECT * from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo "<script>document.getElementById('products').innerHTML = '<div class=ks>';</script>";
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
echo "<script>document.getElementById('products').innerHTML += '$xx';</script>";
}
echo "<script>document.getElementById('products').innerHTML += '</div>';</script>";
Ignore all the ks style sheet class and all the mysql stuff for now.
The problem is it displays the grey backgrounded div (grey from style sheet)
and THEN the links. I need the links to be inside the div.
For a little explanation for those of you who are confused by the pieces of code unrelated to the primary purpose of this question,
The Products table in MySQL is a table that hold all my product info including price, name, id, e.t.c.
the "Getdesc.php?hid=..." link is a link to a php web page that will display all the information about the product from it's Id.
"Products" is an Id of a different div that contains this internal div (With the products I mean) PLUS some other stuff ( I don't feel like telling you all about it).
Sorry for the messy code, thanks in advance.
Javascript:
//from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener () {
document.getElementById('products').innerHTML = this.responseText;
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.php", true);
oReq.send();
PHP
$sql = "SELECT <columns> from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo '<div class="ks">';
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
echo '' . htmlspecialchars($row['Name']) . '<br>';
}
echo '</div>'
why not put everything in a variable :
$html = '<div class="ks">'; // btw you forgot those double-quotes. you html won't evaluate the class if not surrounded by double-quotes
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
$html.= $xx;
}
$html.= '</div>';
then echo it? if you're using php, then there's no need to change the page with javascript after it's been loaded, you just sent all the remainder of the page to the client, why not directly put this code at the right place?
echo $html;

Two questions about possible mysql and php functionalities (maybe javascript?), and where I should look to learn more

First, is it possible for when I insert a record onto my mysql table, a page is automatically generated using the new record in some way. EXAMPLE: My column "image" is on autoincrement, so my image names are always numbers. Furthermore, is it possible for when I insert a record, I automatically generate a page with my image name. So basically, I submit record 367, the image name is 367, and my site will automatically generate mysite.com/367? I want to go in more details but you get the point. Is it possible? If not, what's the closest thing possible?
Also, is there someway to automatically update my page periodically. Such as I set it so at 5pm, it'll automatically insert a code. 5:30pm, it'll insert a different code, which I preprogrammed to do. This is useful, for say I'm on vacation but I still want to update my site regularly.
Can you guys point me to any specific tutorial/terminology/methods/programs/codes/anything? All help would be appreciated!
EDIT: Code I have so far (just want to show to Nick)
<html>
<head>
<title>tgh</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("thegoodhumor");
$strSQL = "SELECT * FROM gallery";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by GalleryID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '<td><img src="https://s3.amazonaws.com/imagetitle/' . $objResult["Picture"] . '" />' .
$objResult["GalleryName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br>
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
It sounds like you want a dynamic web page. To make a dymaic webpage I'd suggest using PHP which would interact with the mysql server.
For example, a user would visit 'mysite.com/info.php?image=367' and the php script would get the information 'image=367'. Your PHP script could do a select query against the mysql database 'SELECT paragraph FROM table WHERE image_id = 367' and then write that data out to the user's web browser.
As far as the user is concerned they just visited 'mysite.com/info.php?image=367', but in the background, PHP dynamically created the webpage content after it got that request.
More basic info about dynamic webpages: http://way.clicktracks.com/help/en/pr650/index.html?dynamicwebsiteshowtheywork.htm
Simple Intro to PHP:
http://www.tizag.com/phpT/
http://www.w3schools.com/php/php_intro.asp
Here is a head start I wrote for you, feel free to use it.
<?php
if (!isset($_GET['imageNumber']))
die("You must specify an image number");
$image_requested = mysql_real_escape_string($_GET['imageNumber']); //sanitizes input
$dbhost = 'localhost'; //TODO: Set this to the ip address of your mysql server if it is not on the same machine
$dbuser = 'root'; //TODO: Set the username you use to access your mysql db here
$dbpass = 'password'; //TODO: Set the password you use to access your mysql db here
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'database_name_here'; //TODO: Set the database name here
mysql_select_db($dbname);
$query = "SELECT paragraph FROM table_name WHERE image_id = " . $image_requested; //TODO: Set table_name, column to get, and image_id to the correct column name
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die(mysql_error());
echo "Here is the paragraph of text" . $row['paragraph']; //TODO: Set paragraph to the same column you retrieved 3 lines above.
mysql_close($conn);
?>
As for the second part of your question, it can also be done with PHP
<?php
$specifictime = strtotime("tuesday 3pm");
if (time("now") > $specifictime)
{
echo " its after 3pm on tuesday";
}
else {
echo " not 3pm on tuesday yet";
}
?>

How do I create links in the cells of a PHP generated table?

I have a table generated from some PHP code that lists a SMALL amount of important information for employees. I want to make it so each row, or at least one element in each row can be clicked on so the user will be redirected to ALL of the information (pulled from MySQL database) related to the employee who was clicked on. I am not sure how would be the best way to go about this, but I am open to suggestions. I would like to stick to PHP and/or JavaScript. Below is the code for my table:
<table>
<tr>
<td id="content_heading" width="25px">ID</td>
<td id="content_heading" width="150px">Last Name</td>
<td id="content_heading" width="150px">First Name</td>
<td id="content_heading" width="75px">SSN</td>
</tr>
<?php
$user = 'user';
$pass = 'pass';
$server = 'localhost';
$link = mysql_connect($server, $user, $pass);
if (!$link){
die('Could not connect to database!' . mysql_error());
}
mysql_select_db('mydb', $link);
$query = "SELECT * FROM employees";
$result = mysql_query($query);
mysql_close($link);
$num = mysql_num_rows($result);
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
$class = (($i % 2) == 0) ? "table_odd_row" : "table_even_row";
echo "<tr class=".$class.">";
echo "<td>".$row[id]."</td>";
echo "<td>".$row[l_name]."</td>";
echo "<td>".$row[f_name]."</td>";
echo "<td>".$row[ssn]."</td>";
echo "</tr>";
}
?>
</table>
EDIT
Ok, after modifying what #DrColossos posted I have been able to get my links to work correctly, but now I'm having trouble with the uniqueness part. Below is the code I am now using to create my table:
echo "<td>".$row[id]."</td>";
echo "<td>".$row[l_name]."</td>";
echo "<td>".$row[f_name]."</td>";
echo "<td>".$row[ssn]."</td>";
This makes all of the elements of a row hyperlink to Edit_Employee.php?**id**. For instance if the id was one the hyperlink would be Edit_Employees.php?1. Now what do I need to do in my Edit_Employee.php page to get or recognize the id in the link, because it is that id that is unique and that is what I need to base my MySQL search on.
EDIT
Figured it out. This did the trick:
$id = $_GET['id'];
I found that creating my links as I did makes the id a global variable which PHP can pull from the hyperlink. I used the code above in the page that the hyperlink points to and I was able to get what I wanted. Not too hard, but frustrating if you don't know how it is done!
You can already create an unique link with the "ID" of each employee.
You could do the following:
echo "<td><a href="employee.php?id=\"" . $row['id'] . "\">" . $row['id'] . "</td>";
or more readable
echo "<td><a href="employee.php?id=\"{$row['id']}\">{$row['id']}</td>";
Then you can use the employee.php to display it's detail (the id will be in $_GET['id'], see here). Don't forget to check the value of $_GET['id'] before you process it, since it can contain harmfull data (e.g. SQL-Injection).
BTW, the HTML attribute 'id' that you use in the table id="content_heading" is supposed to be unique on the site, just as a site note.

Categories