Clickable data displayed from mysql using PHP - javascript

I'm not very good at JavaScript but here is my problem.
I have three pages: page1.php, page2.php, page3.php
On page1.php, I have a form for users to select grade level they want to view, then the action is performed on page2.php -- displaying the list of all students in that grade.
This is the code for page2.php
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$level = $_POST['level_group'];
$room = $_POST['room_group'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT std_id, std_name FROM students WHERE std_level LIKE '$level%' AND std_room LIKE '$room';");
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Action</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo"<form action='view_one_student.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td>" . '<input type="submit" value="view"> <input type="submit" value="sdq">' . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>
The question...now is How can I write the code on page3.php so that when users clicks on view or sdq button next to each column, the student ID should be captured, send a request to the database, and query other data related to this particular student such as age, address, phone..etc. and display them on that page3.php

page2.php
You have to add a hidden input with the id of the student in page2.
<input type="hidden" value="'.$row["std_id"].'" name="std_id">
Change your action page to page3 (if that's where you want to display the student info: name, age...)
<form action='page3.php' method='post'>page2.php
The code for page2:
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$level = $_POST['level_group'];
$room = $_POST['room_group'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT std_id, std_name FROM students WHERE std_level LIKE '$level%' AND std_room LIKE '$room';");
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Action</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo"<form action='page3.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td> <input type='hidden' value='" . $row["std_id"] . "' name='std_id'>";
echo "<input type='submit' value='view'>";
echo "<input type='submit' value='sdq'></td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>
page3.php
A posible solution for page3 can be: (add your columns you need: age, address, phone..)
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$id = $_POST['std_id'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM students WHERE std_id ='$id';");
echo '<h3>Student detail</h3>';
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Age</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td>" . $row['std_age'] . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>

You can modify your code like this. A hidden field will send the student id to the page of view_one_student.php.
while($row = mysqli_fetch_array($result))
{
echo"<form action='view_one_student.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo '<input type="hidden" value="'.$row["std_id"].'" name="std_id">';
echo "<td>" . '<input type="submit" value="view"> <input type="submit" value="sdq">' . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
On view_one_student.php you have to catch that with:
$_POST["std_id"]
And eventually input that into a sql sentense in view_one_student.php:
$sql = "SELECT * FROM <table> WHERE id=".$_POST["std_id"];
Thats the general idea.

Related

Updating mySQL table with user interface - PHP

[Sample Look]
I'm trying to make an interface where you can edit/add/remove fields of a mySQL database. This is how it looks visually, and I have all the functionality on the client side working.
My question is: How can I pass any edits/adds/removals to the server side? I'll include a link for my JSFiddle.
And the code below will show how I currently great the table.
<?php
$servername = "localhost";
$username = "lalalal";
$password = "lalalal";
$link = mysqli_connect("localhost", "lalala", "lalala", "lalala");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlStart = "SELECT `Name`, `EXT`, `Returning Time`, `Returning Date`, `Out`, `Reset`, `Booked` FROM `lalala`";
if($result = mysqli_query($link, $sqlStart)){
if(mysqli_num_rows($result) > 0){
echo "<table id = contactTable>";
echo "<tr id = row1>";
echo "<th id = sortTable onclick=sortTable(0)>Name ↕</th>";
echo "<th style = width:100px;>EXT</th>";
echo "<th style = width:300px;>Returning Time</th>";
echo "<th style = width:300px;>Returning Date</th>";
echo "<th style = width:70px;>Out</th>";
echo "<th style = width:100px;>Reset</th>";
echo "<th style = width:600px;>Booked</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
$currentCheck = $row['Out'];
if ($currentCheck == 0) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
if ($currentTime == 0) {
echo "<td> <form> <input type = 'time', id = 'timePickChange'> </form> </td>";
} else {
echo "<td> <form> <input type = 'time', id = 'timePickChange' value =" . $currentTime . "> </form> </td>";
}
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = 'datePickChange' value =" . $currentDate . "> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)'> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
} else if ($currentCheck == 1) {
echo "<tr style = 'background-color: #E2E9FD'>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
echo "<td> <form> <input type = 'time', id = timePickChange disabled> </form> </td>";
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = datePickChange disabled> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)' checked> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
}
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sqlStart. " . mysqli_error($link);
}
?>
Depending on your data validation model, you might want to control the inputs value client side before posting them to your back-end.
AFAIK, you're already adding/editing/removing your contacts on the client side, so If I understand correctly, when your user should click on Edit/Remove & confirm , it would be a confirmation of what the user has done in the browser, this doesn't really change much apart from the fact that otherwise you might need dedicated buttons/row (or any other bindable events).
For these operations what you could do is proceed to bulk delete / edit, and this could be easily done by filtering out in your JS all the modified/deleted data and sending it to your back end PHP with Ajax/jQuery in the form of a stringified array.
As for insertion operation you'd submit them at the same time you add them to your table, by executing a POST operation.
And it could be done with something like this :
$.ajax({
method: "PUT",
url: "some.php",
data: JSON.stringify(myUpdatedDataInAnArray)
// you might need to stringify your array to ensure format ?
})
.done(function( msg ) {
alert( "Data Updated: " + msg );
});
In your back end php, you'd listen for POST/PUT/DELETE methods with something like that :
if (isset($_POST['add'])){
do your thing
}
if (isset($_PUT['updated'])){
//Since you're sending a stringified array, you must parse it with
$myArray = json_decode($_PUT['updated']);
do your thing
}
if (isset($_DELETE['deleted'])){
do your thing
}
I say Ajax because using a traditional POST/PUT/DELETE form would result in refreshing the page.
Here are some useful refs :
JS JSON Stringify and JSON Parse
PHP : JSON DECODE and JSON Encode
Ajax docs
Ajax Examples

How to send data and run a link with that data with one click

I want to send latitude and longitude data so I can search it up on Google Map. Those data has to be selected from a database but I can't figure how to do it in one click.
Here is my code.
<?php
$con = mysqli_connect("localhost","root","","project");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM table1");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Latitude</th>
<th>Longitude</th>
<th>Date</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['latitude'] . "</td>";
echo "<td>" . $row['longitude'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td><a href='./clicktest.php?id=".$row['id']."'>View Location</a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
And as you can see, it sends the id value of a row that I want to another page which is
<?php
$con=mysqli_connect("localhost","root","","project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_GET['id'])) {
$result = "SELECT * FROM table1 WHERE id='".$_GET['id']."'" ;
$show = mysqli_query($con, $result);
while($row = mysqli_fetch_array($show))
{
$latitude = $row['latitude'];
$longitude = $row['longitude'];
echo "<a href='http://www.google.com/maps/place/".$latitude.",".$longitude."'>click here</a>";
}
mysqli_close($con);
}
?>
And finally can run a link to Google Map on this page. But what I want is to click on the 'view location' on the first page and jump to the google map page with data on that row without having to go through another page and another click.
I did some research and maybe this is about AJAX? And are there any ways to do it without using AJAX?(since I never use it before)
Thanks
I think you need to directly link to google maps page and use "target=_blank" attribute on it. for example:
echo 'View Location';
You can add as many parameter to the anchor tag as you like, so add the lat and long like this for example
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['latitude'] . "</td>";
echo "<td>" . $row['longitude'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td><a href='./clicktest.php?id=".$row['id']
.'&lat=' . $row['latitude']
. '&long' . $row['longitude']"'>View Location</a></td>";
echo "</tr>";
}

How can create a separate click event for each input button displayed using a while loop

I am listing users from the database in a table. for each user; there is an 'Approve' and 'Reject' button.
I want to put my code in such way that when i click each button for each user,only the approval or the reject event should affect that specific user? My table looks like this:
right now when i click 'approve' on one user, the other user's approval event also gets triggered. here is my approval code:
$sql = "select * from user_table ORDER BY date_registered DESC LIMIT 10";
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result)){
$emailadr = $row["email"];
$adresses [] = $emailadr;
echo "<tr>";
echo "<td>";
echo $row["firstname"];
echo "</td>";
echo "<td>";
echo $row["lastname"];
echo "</td>";
echo "<td>";
echo $row["idnumber"];
echo "</td>";
echo "<td>";
echo $row["qualification"];
echo "</td>";
echo "<td>";
echo $row["dofa"];
echo "</td>";
echo "<td>";
echo $row["date_registered"];
echo "</td>";
echo "<td>";
echo '<button name="approve" value='. $row["user_id"].'>Approve</button> <button name="reject" value='. $row["user_id"].'>Reject</button>';
echo "</td>";
echo '</tr>';
}
if(isset($_POST['approve'])){
// Approved user ID is now in $_POST['approve']
mail($adresses[$row["user_id"]],'subect
1','approved','From:email#example.com');
}elseif(isset($_POST['reject'])){
//
}
}
print_r($adresses);
When inserting new users, you normally have a auto increment column that relates to each row or user (generally called ID) you can do it a few ways first thing you need to do is include that ID or value so you know which user to change:
Create your Buttons:
<button name="approve" value="5"> Approve</button>
<button name="reject" value="5"> Reject</button>
You would update the value to your user ID
You can then simply check whether you have Approved or Rejected the user:
if(isset($_POST['approve'])){
// Approved user ID is now in $_POST['approve']
}elseif(isset($_POST['reject'])){
// Rejected user ID is now in $_POST['reject']
}
To get $adresses you need to assign it outside the loop. Also updated $adresses [] to array_push($adresses, $row["email"]); just because of preference but can be changed back if you prefer.
<?php
$adresses = array();
$sql = "select * from user_table ORDER BY date_registered DESC LIMIT 10";
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)){
array_push($adresses, $row["email"]);
echo "<tr>";
echo "<td>";
echo $row["firstname"];
echo "</td>";
echo "<td>";
echo $row["lastname"];
echo "</td>";
echo "<td>";
echo $row["idnumber"];
echo "</td>";
echo "<td>";
echo $row["qualification"];
echo "</td>";
echo "<td>";
echo $row["dofa"];
echo "</td>";
echo "<td>";
echo $row["date_registered"];
echo "</td>";
echo "<td>";
echo '<button name="approve" value='. $row["user_id"].'>Approve</button> <button name="reject" value='. $row["user_id"].'>Reject</button>';
echo "</td>";
echo '</tr>';
}
if(isset($_POST['approve'])){
mail($adresses[$_POST["approve"]],'subect 1','approved','From:email#example.com');
//update DB to approved
}elseif(isset($_POST['reject'])){
//update DB to rejected
}
}
print_r($adresses);
?>
Yes.. Passing the contentid or some unique identifier will solve this.

value of $_POST is always the last value of my <tr>

I have a problem in which I cannot solve. I have a simple page where I query all Users and list them in a table. When a user clicks on one of the table rows, it should be taken to another page where the user can edit information of the that they picked. The problem is that in my script, the $_POST value is always the value of the last
CODE
<?php
include "conn.php";
$pquery = "SELECT * FROM Patient NATURAL JOIN User ORDER BY LastName;";
$patientQuery = $conn->query($pquery);
if (mysqli_num_rows($patientQuery) == 0)
echo "<p>No patients found.</p>";
else{
while($assoc = $patientQuery->fetch_assoc()){
echo "<tr onclick = 'sub();'>";
echo "<td>";
echo $assoc['UserID'];
echo "<input type = 'hidden' name = 'UserID' value = '". $assoc['UserID'] ."' />";
echo "</td>";
echo "<td>";
echo $assoc['FirstName'];
echo "</td>";
echo "<td>";
echo $assoc['LastName'];
echo "</td>";
echo "</tr>";
}
}
?>
<script>
function sub(){
document.getElementById("edit").submit();
return false;
}
</script>
I've slightly modified your code - this should work:
<?php
include "conn.php";
$pquery = "SELECT * FROM Patient NATURAL JOIN User ORDER BY LastName;";
$patientQuery = $conn->query($pquery);
if (mysqli_num_rows($patientQuery) == 0)
echo "<p>No patients found.</p>";
else{
while($assoc = $patientQuery->fetch_assoc()){
echo "<tr onclick = 'sub(". $assoc['UserID'] .");'>";
echo "<td>";
echo $assoc['UserID'];
echo "</td>";
echo "<td>";
echo $assoc['FirstName'];
echo "</td>";
echo "<td>";
echo $assoc['LastName'];
echo "</td>";
echo "</tr>";
}
}
?>
<script>
function sub(UserID){
document.location.href = 'http://www.yourdomain.com/something.php?UserID='+UserID;
return false;
}
</script>

Javascript not working in AJAX response

Below code is the AJAX response to another page. I have added onclick event to table row and written javascript code to handle it. But javascript code doesn't work.Is this wrong way of coding or there is any problem in code. Suggest me a simple solution
<?php
echo '<script type=\"text/javascript\">
function clicked(){
alert("I am an alert box!");
}
</script>';
$q = $_GET['q'];
include 'db_connect.php';
$sql="SELECT name,address,mobile,email,pan,tan FROM client WHERE name = '$q'";
$sql_bill="SELECT clientname,financialyear,receiptno,amount,ddate,type,chequeno,category FROM billing WHERE clientname = '$q'";
$sql_total="SELECT SUM(amount) AS TotalAmount FROM billing";
$result = mysql_query($sql);
$result_bill = mysql_query($sql_bill);
$result_total = mysql_query($sql_total);
$total= mysql_fetch_array($result_total);
echo "<h4><b>Client details</b></h4><table align='center' border='2'>
<tr>
<th>Name</th>
<th>Address</th>
<th>Mobile</th>
<th>Email</th>
<th>PAN</th>
<th>VAT TIN</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['mobile'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['pan'] . "</td>";
echo "<td>" . $row['tan'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<h4><b>Payment received details</b></h4><table align='center' border='2'>
<tr>
<th>Client Name</th>
<th>Financial Year</th>
<th>Receipt No</th>
<th>Date</th>
<th>Type</th>
<th>Chequeno</th>
<th>Category</th>
<th>Amount</th>
</tr>";
while($row = mysql_fetch_array($result_bill))
{
echo "<tr onclick=\"clicked()\">";
echo "<td>" . $row['clientname'] . "</td>";
echo "<td>" . $row['financialyear'] . "</td>";
echo "<td>" . $row['receiptno'] . "</td>";
echo "<td>" . $row['ddate'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row['chequeno'] . "</td>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['amount'] . "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<td colspan=7>Total</td>";
echo "<td>".$total['TotalAmount']. "</td>";
echo "</tr>";
echo "</table>";
?>
Try this instead of your script code:
echo <<<EOD
<script type="text/javascript">
function clicked(){
alert("I am an alert box!");
}
</script>
EOD;
Edit 1:
Look in the console (F12), What happens when you click on a tr?
The following fiddle replicates your code and works:
http://jsfiddle.net/Yaj44/
Edit 2:
I think it has something to do with the way you call the data.
Put the function in your main page,
then call the AJAX.
Set innerHTML of specific div with responseData.
If you do it in that order, it might work.
Your way to adding this functionality is very dirty..
If you use JQuery, you can add on the end:
$('tr').click(function() {
alert('Do something on click!');
});
mysql_fetch_array is outdated, use mysqli (or PDO) instead.
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();

Categories

Resources