I have created a form with submit button. If "price" for a particular product is already filled then the Submit button must be disabled:
Code Php
<?php
$host="localhost";
$username="root";
$password="";
$db_name="ge";
$con=mysqli_connect("$host", "$username", "$password","$db_name")or die("Your Connection is in error");
$sql="SELECT pname,catogery,email FROM quetation WHERE catogery = '$catogery'";
$results=mysqli_query($con,$sql);
$count=mysqli_num_rows($results);
if($count == 0) {
echo "<font color=\"#0000\"><h1 align=\"center\">No details found</h1></font>";
} else {
$resource=mysqli_query($con,$sql);
echo "<font color=\"#000000\">
<h2 align=\"center\"></h2>
<table align=\"center\" border=\"1\" width=\"50%\">
<tr>
<td><b>ProdName</b></td>
<td><b>Catogery</b></td>
<td><b>Price</b></td>
</tr> ";
while($result=mysqli_fetch_array($resource)) {
echo "
<div class=\"row\">
<div class=\"input-field col s12\">
<tr>
<td>".$result[0]."</td>
<td>".$result[1]."</td>
<td>
<form name=\"abc\" methos=\"post\" action=\"postprice.php\">
<input type=\"submit\" value=\"send\">
</form>
</td>
</div>
</div>
</tr>";
} echo "</table></font>";
}
?>
Only once price should be entered if already entered then send button should be disabled
Whenever I load this page it should check the database and if price value is filled then it should disable the send button.
Use the below code in the submit button:
<input type="submit" onClick="this.disabled=true;">
This will disable the button after clicking the submit button. Hope it helps you.
PLz try this code, hope it will work.
<?php
$host="localhost";
$username="root";
$password="";
$db_name="ge";
$con=mysqli_connect("$host", "$username", "$password","$db_name")or die("Your Connection is in error");
$sql="SELECT pname,catogery,email,price FROM quetation WHERE catogery = '$catogery'";
$results=mysqli_query($con,$sql);
$count=mysqli_num_rows($results);
if($count == 0)
{
echo "<font color=\"#0000\"><h1 align=\"center\">No details found</h1></font>";
}
else
{
$resource=mysqli_query($con,$sql);
echo "<font color=\"#000000\">
<h2 align=\"center\"></h2>
<table align=\"center\" border=\"1\" width=\"50%\">
<tr>
<td><b>ProdName</b></td>
<td><b>Catogery</b></td>
<td><b>Price</b></td>
</tr> ";
while($result=mysqli_fetch_array($resource))
{
echo "
<div class=\"row\">
<div class=\"input-field col s12\">
<tr>
<td>".$result[0]."</td>
<td>".$result[1]."</td>
<td><form name=\"abc\" methos=\"post\" action=\"postprice.php\">";
if($result[3]==''){
echo "<input type=\"submit\" value=\"send\" onClick='this.disabled=true;'>";
} else {
echo "<input type=\"submit\" value=\"send\" disabled>";
}
echo "</td>
</form>
</div>
</div>
</tr>";
}echo "</table></font>";
}
?>
first you will check in database product price is available or not if price is available then set the variable 0 for not available or 1 for available;
Related
I want to create a column that has a text box inside each table row. The user can write any text inside the text box and click the 'Save' button to save it in the database. Additionally, the text box can be edited unlimited times. My code is the following:
index.php
<?php
...
while($row = $result->fetch_assoc()){
echo "<form action= 'search.php' method='post'>";
echo "<form action='' method='get'>";
echo "<tr>
<td><input type='checkbox' name='checkbox_id[]' value='" . $row['test_id'] . "'></td>
<td> ".$row['test_id']." </td>
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
<td> ".$row['path']." </td>
<td> ".$row['video1_path']." </td>
<td> ".$row['video2_path']." </td>
<td> ".$row['video3_path']." </td>
<td> ".$row['video4_path']." </td>";
if(empty($row["directory"])){
echo "<td></td>";
}else {
echo "<td><div><button class='href' id='" . $row['test_id'] . "' >View Report</button><div></td>";
}
echo " <td style='display: none;'> ".$row['directory']." </td>
</tr>";
}
?>
</table> <br>
<input id= 'select_btn' type='submit' name='submit' value='Submit' class='w3-button w3-blue'/>
</form>
</form>
</div>
<!-- Opens the pdf file from the pdf_report column that is hidden -->
<script type="text/javascript">
$(document).on('click', '.href', function(){
var result = $(this).attr('id');
if(result) {
var dir = $(this).closest('tr').find("td:nth-child(9)").text();
window.open(dir);
return false;
}
});
</script>
<!-- Updates text input to database -->
<script type="text/javascript">
$(document).on('click', '.name', function(){
var fcookie1= 'mycookie1';
var fcookie2= 'mycookie2';
var name = $(this).attr('id');
if(name) {
var text1 = $(this).closest('tr').find("td:nth-child(2)").text();
var text2 = $(this).closest('tr').find("td:nth-child(3)").text();
document.cookie='fcookie1='+text1;
document.cookie='fcookie='+text2;
$.ajax({
url: "name_edit.php",
type:"GET",
success: function() {
// alert("Edited Database");
}
});
}
});
</script>
name_edit.php
<?php include 'dbh.php' ?>
<?php include 'search.php' ?>
<?php
if (isset($_COOKIE["fcookie1"]))
echo $_COOKIE["fcookie1"];
else
echo "Cookie Not Set";
if (isset($_COOKIE["fcookie2"]))
echo $_COOKIE["fcookie2"];
else
echo "Cookie Not Set";
$var1 = $_COOKIE["fcookie1"];
$var2 = $_COOKIE["fcookie2"];
$conn = mysqli_connect($servername, $username, $password, $database);
$sql = "UPDATE test_data SET name='$var2' WHERE id='$var1'";
$query_run= mysqli_query($conn,$sql);
if($query_run){
echo '<script type="text/javascript"> alert(Data Updated)</script>';
} else {
echo '<script type="text/javascript"> alert(Data Not Updated)</script>';
}
?>
My idea was for the user to write any text. Then i will 'grab' the text and its expected id and save it to a cookie, when the save button is clicked. The cookie will then be echoed in name_edit.php and insert it in the sql code which will then update my database.
Im not sure what to include in 'value' inside the form tag. If there is data inside the database then display it inside the text box which can also be edited, else display blank for a text to be inserted.
I am new to coding and I'm a bit confused if my idea is correct or should i approach it another way.
I did some research and found out i did not have to use form but instead use 'contenteditable'. To edit the specific column i changed
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
to this:
<td class='name' data-id1='" . $row['test_id'] . "' contenteditable='true'>".$row['name']."</td>
and for my jquery i added the following:
<style>
.editMode{
border: 1px solid black;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
// Add Class
$('.name').click(function(){
$(this).addClass('editMode');
});
// Save data
$(".name").focusout(function(){
$(this).removeClass("editMode");
var id = $(this).closest('tr').find("td:nth-child(2)").text();;
var value = $(this).text();
$.ajax({
url: 'name_edit.php',
type: 'post',
data: { value:value, id:id },
success:function(response){
alert('Edits Saved');
return false;
}
});
});
});
</script>
and in the php side, i simply did the following:
<?php include 'dbh.php' ?>
<?php
$conn = mysqli_connect($servername, $username, $password, $database);
$field = $_POST['field'];
$value = $_POST['value'];
$id= $_POST['id'];
$sql = "UPDATE test_data SET name='".$value."' WHERE test_id='".$id."'";
mysqli_query($conn,$sql);
echo 1;
?>
I am currently calling tables using php in order to show pending purchase requests. An admin will either approve or deny these requests based on the contents of each table. Each table will have a unique identifier and this is how they are divided. I am trying to determine how I can approve/deny each table individually, but I'm new to jQuery. I've used it before in a similar manner but can't seem to find a solution for what I am trying to do.
Right now, I'm just trying to set up an alert to make sure that the function is working properly.
PHP code showing table format (code is in a while loop):
echo "<form method='POST' onsubmit='moveTable(this)'>
<table id='pendingTable'>
<tbody>
<tr style='background-color:$bgcolor'>
<input type='hidden' value='".$RNrow['request_number']."'>
<td id='name'>".$PRrow['ItemName']."</td>
<td>".$PRrow['ItemDesc']."</td>
<td>".$PRrow['BrandName']."</td>
<td>".$PRrow['ManNum']."</td>
<td>".$PRrow['NSN']."</td>
<td>".$PRrow['ItemCost']."</td>
<td>".$PRrow['Qty']."</td>
</tr>
</tbody>";
<input type='submit' value='Approve' onclick=\"return confirm ('Are you sure you want to approve this request?')\">
<input style='margin-left:5px' type='submit' value='Deny' onclick=\"return confirm ('Are you sure you want to deny this request?')\">
<script type="text/javascript">
function moveTable(){
$('#pendingTable tr').each(function(){
alert('hello');
});
}
</script>
The information from these tables would then be moved to an 'approved/denied' mysql table. I figure it may have to do with the uniqueness of the table id but haven't found a way around that. Any help would be appreciated.
You cannot use id as it is supposed to be unique within the DOM, you can use classes instead like this:
echo "<form method='POST' onsubmit='moveTable(this)'>
<table class='pendingTable'>
<tbody>
<tr style='background-color:$bgcolor'>
<input type='hidden' value='".$RNrow['request_number']."'>
<td id='name'>".$PRrow['ItemName']."</td>
<td>".$PRrow['ItemDesc']."</td>
<td>".$PRrow['BrandName']."</td>
<td>".$PRrow['ManNum']."</td>
<td>".$PRrow['NSN']."</td>
<td>".$PRrow['ItemCost']."</td>
<td>".$PRrow['Qty']."</td>
</tr>
</tbody>";
<input type='submit' value='Approve' onclick=\"return confirm ('Are you sure you want to approve this request?')\">
<input style='margin-left:5px' type='submit' value='Deny' onclick=\"return confirm ('Are you sure you want to deny this request?')\">
<script type="text/javascript">
function moveTable(form){
$(form).find('.pendingTable tr').each(function(){
alert('hello');
});
}
</script>
You can paste this entire script into one PHP script and you should be able to see how it passes the table id via ajax to the script at the bottom of the page. Give it a try!
<?php if (!isset($_POST['doAjaxAction'])) { ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dev Doc</title>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<style>
form {
margin-bottom: 50px;
}
</style>
</head>
<body>
<?php
$RNrow['request_number'] = '123';
$RNrow['ItemName'] = 'ItemName';
$RNrow['ItemDesc'] = 'ItemDesc';
$RNrow['BrandName'] = 'BrandName';
$RNrow['ManNum'] = 'ManNum';
$RNrow['NSN'] = 'NSN';
$RNrow['ItemCost'] = 'ItemCost';
$RNrow['Qty'] = 'Qty';
$bgcolor = 'grey'
?>
<form method='POST'>
<table id='<?php echo $RNrow['request_number'] ?>' class="pendingTable">
<tbody>
<tr style='background-color:<?php echo $bgcolor; ?>'>
<input type='hidden' value='<?php echo $RNrow['request_number'] ?>'>
<td id = 'name'>"<?php echo $RNrow['ItemName'] ?>"</td>
<td>"<?php echo $RNrow['ItemDesc'] ?>"</td>
<td>"<?php echo $RNrow['BrandName'] ?>"</td>
<td>"<?php echo $RNrow['ManNum'] ?>"</td>
<td>"<?php echo $RNrow['NSN'] ?>"</td>
<td>"<?php echo $RNrow['ItemCost'] ?>"</td>
<td>"<?php echo $RNrow['Qty'] ?>"</td>
</tr>
</tbody>
<input type='submit' value='Approve' onclick="moveTable(<?php echo $RNrow['request_number'] ?>, 'Approve')">
<input style='margin-left:5px' type='submit' value='Deny' onclick="moveTable(<?php echo $RNrow['request_number'] ?>, 'Deny')">
</table>
</form>
<?php
$RNrow['request_number'] = '456';
$RNrow['ItemName'] = 'ItemName2';
$RNrow['ItemDesc'] = 'ItemDesc2';
$RNrow['BrandName'] = 'BrandName2';
$RNrow['ManNum'] = 'ManNum2';
$RNrow['NSN'] = 'NSN2';
$RNrow['ItemCost'] = 'ItemCost2';
$RNrow['Qty'] = 'Qty2';
$bgcolor = 'lightblue'
?>
<form method='POST'>
<table id='<?php echo $RNrow['request_number'] ?>' class="pendingTable">
<tbody>
<tr style='background-color:<?php echo $bgcolor; ?>'>
<input type='hidden' value='<?php echo $RNrow['request_number'] ?>'>
<td id = 'name'>"<?php echo $RNrow['ItemName'] ?>"</td>
<td>"<?php echo $RNrow['ItemDesc'] ?>"</td>
<td>"<?php echo $RNrow['BrandName'] ?>"</td>
<td>"<?php echo $RNrow['ManNum'] ?>"</td>
<td>"<?php echo $RNrow['NSN'] ?>"</td>
<td>"<?php echo $RNrow['ItemCost'] ?>"</td>
<td>"<?php echo $RNrow['Qty'] ?>"</td>
</tr>
</tbody>
<input type='submit' value='Approve' onclick="moveTable(<?php echo $RNrow['request_number'] ?>, 'Approve')">
<input style='margin-left:5px' type='submit' value='Deny' onclick="moveTable(<?php echo $RNrow['request_number'] ?>, 'Deny')">
</table>
</form>
<script>
function moveTable(id, action) {
//Opens OK or Cancel Dialog
if (confirm('Are you sure you want to approve this request?')) {
//Hit F12 in your browser to the console. This shows what passed in
alert('ID Sent: ' + id, ' -- Action: ' + action);
//Posts ID and Action to self, with 'doAjaxAction' set to 1, so only the php script at bottom executes during AJAX call
$.post('<?php echo basename($_SERVER['PHP_SELF']); ?>',
{
//seen as $_POST['id'] and $_POST['action'] to script at the bottom
doAjaxAction: '1',
id: id,
action: action
},
//This function gives us the data returned from approve_deny.php
function (data, status) {
// 'data' returns 'DID SOMETHING'
// 'status' returns status of ajax call
alert("Data Sent: " + data + "\nStatus: " + status);
if (status === 'success') {
//Removes the order from the page. Can change this to grey it out, shrink it, etc
alert('AJAX call was a.. ' + status);
// $("#" + id + "\"").empty();
}
});
}
//If user changes mind, and clicks cancel on confirm
else {
alert('Action Cancelled.')
}
}
</script>
</body>
</html>
<?php } ?>
<?php
if (isset($_POST['doAjaxAction']) && $_POST['doAjaxAction'] == '1') {
$id = $_POST['id'];
$action = $_POST['action'];
if ($action == 'Approve') {
echo "APPROVED ID # " . $_POST['id'] . " do something with passed ID " . PHP_EOL;
}
if ($action == 'Deny') {
echo "DENIED ID # " . $_POST['id'] . " do something with passed ID " . PHP_EOL;
}
echo "DID SOMETHING AT END" . PHP_EOL;
}
?>
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.
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>';
I have three files, index.html, database.php, and function.js. In my database.php, I have created a form with a delete button to execute the delete sql query on click. My main purpose is to display a table with records displayed and a delete button on each so that whenever I click the delete button, it executes the SQL query and removes that particular row from the database.
It works fine before I added in ajax into the javascript. Now when delete button is clicked, the whole page just refreshes.
How do I execute the delete query on the delete button click using a javascript function that I want to call in my php file without creating/using new files?
I am using vi editor to code so I do not have any means of debugging except IE's developer tools. My javascript file doesn't seem to be working because in the HTML file the form returns a null at
onsubmit="return checkFields()";
as stated from the error I received, but it's probably just because there are errors in my javascript file.
P.S. I am new to PHP, javascript, and ajax so do pardon me if I make any careless or obvious mistakes. I also do not know any jQuery or JSON. Any form of help in the simplest explanation would be greatly appreciated.
Here is the index.html file:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="function.js" type="text/javascript"></script>
</head>
<body>
<form name="infoForm" method="post" onsubmit="return checkFields()" action="">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" maxlength="40"></td>
</tr>
<tr>
<td>Address:</td>
<td><textarea maxlength="45" name="address"id="address" ></textarea></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone" id="phone" maxlength="20"><br></td>
</tr>
<tr>
<td>Gender:</td>
<td><input checked type="radio" name="gender" id="male" value="Male">Male
<input type="radio" name="gender" id="female" value="Female">Female</td>
</tr>
<tr>
<td>
Nationality:
</td>
<td>
<select name="nation">
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Thailand">Thailand</option>
<option value="Indoensia">Indonesia</option>
<option value="Philippines">Philippines</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<br><input type="reset" value="Cancel">
<input type="submit" name="result" value="Submit"/>
</td>
</tr>
</table>
</form>
<div id="divTable"></div>
</body>
</html>
Here is the database.php file:
<?php
// Define database parameters //
DEFINE ('DB_USER' ,'iqwe');
DEFINE ('DB_PASSWORD', 'inqwe123');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'hqwdqq');
$table_info = "info";
// Connect to database
$conn = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to Database:'. mysql_error());
#mysql_select_db (DB_NAME) OR die ('Could not select the Database: '.mysql_error());
// Delete Row
if(isset($_POST['delete'])){//java script function somewhere
echo "<script>";
echo "deleteRow()";
echo "</script>";
}
//Check if phone no. is duplicate and if not, insert data
if(isset($_POST['result'])){
$phone = $_POST['phone'];
$query_string = "select phone from $table_info where phone='$phone'";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "A same phone number has been found. Please enter a different phone number.";
}else{
$query_string = "insert into $table_info(name, address, phone, gender, nation) values('".$_POST['name']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['gender']."','".$_POST['nation']."')";
$result = #mysql_query($query_string);
}
}
// Display table
$query_string = "select * from $table_info";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "<table border=1>";
echo "<tr><th>Name</th><th>Address</th><th>Phone no.</th><th>Gender</th><th>Nationality</th><th>Created</th><th>Modified</th><th>Action</th></tr>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>", $row['name'], "</td>";
echo "<td>", $row['address'], "</td>";
echo "<td>", $row['phone'], "</td>";
echo "<td>", $row['gender'], "</td>";
echo "<td>", $row['nation'], "</td>";
echo "<td>", $row['createdTime'], "</td>";
echo "<td>", $row['modifiedTime'], "</td>";
?>
<!--Delete button-->
<td><form id="delete" method="post" action="">
<input type="hidden" name="deleteRow" value="<?php echo $row['user_id']; ?>"/>
<input type="button" name="delete" value="Delete" onclick="return deleteRow(<?php echo $row['user_id']; ?>);"/></td></form></tr>
<?php
}
echo "</table>";
}
else{
echo "0 results";
}
?>
<form method="post" action="index.html">
<input type="submit" name="goBack" value="Back"/>
</form>
And here is the function.js file:
function checkFields(){
var name = document.getElementById("name");
var address = document.getElementById("address");
var phone = document.getElementById("Phone");
if(confirm('Do you want to submit')){
if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
alert("Please fill in all your details.");
return false;
}
else{
var page = "database.php";
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", page, true);
xmlhttp.send(null);
return false;
}
}
else{
return false;
}
}
function deleteRow(id){
if(confirm("Are you sure you want to delete this contact?")){
//$id = $_POST['user_id'];
$query_string = "delete from $table_info where user_id='id';
$result = mysql_query($result) or die ('Could not execute.'. mysql_error());
return false;
}
}
It looks like you're missing a closing double-quote at the end of this line:
$query_string = "delete from $table_info where user_id='id';
It should read:
$query_string = "delete from $table_info where user_id='id'";
There may be other errors as well. You should learn to use your browser's built-in script debugging features (and/or download one if your browser doesn't have one). For example, try Firebug and the Web Developer Toolbar for Firefox.