In my index.php I am fetching data from the database. I put an edit button on that and I have used a datatable to view data information in this form. I have four field: Name, Age, Email, Update through mysqli_fetch_array I have fetched the data.
This is the index.php file:
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
// using mysqli_query instead
?>
<html>
<head>
<title>Homepage</title>
<link rel="stylesheet" href="DataTables/datatables.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/dataTables.bootstrap.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/jquery.dataTables.css" type="text/css">
<script src="DataTables/datatables.js"></script>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/datatable.js"></script>
<script src="DataTables/DataTables/js/dataTables.bootstrap.js"></script>
<script src="DataTables/DataTables/js/jquery.dataTables.js"></script>
</head>
<body>
Add New Data<br/><br/>
<table id="datatable" class="display" width='100%' border=0>
<thead>
<tr bgcolor='#CCCCCC'>
<td>Name</td>
<td>Age</td>
<td>Email</td>
<td>Update</td>
</tr>
</thead>
<?php
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
//$action=$_POST["action"];
//if($action=='showroom')
{
$result = mysqli_query($mysqli, "SELECT * FROM users ORDER BY id DESC");
while ($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $res['name'] . "</td>";
echo "<td>" . $res['age'] . "</td>";
echo "<td>" . $res['email'] . "</td>";
echo "<td>Edit | Delete</td>";
}
}
?>
</table>
</body>
</html>
This is my edit.php file. First I check empty fields, after that I run updating the table query redirecting to the display page. In our case, it is index.php then getting id from url, selecting data associated with this particular id, fetching data through mysqli_fetch_array .
<?php
// including the database connection file
include_once("config.php");
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if (empty($name) || empty($age) || empty($email)) {
if (empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if (empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if (empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while ($res = mysqli_fetch_array($result)) {
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name; ?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age; ?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email; ?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id']; ?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
Finally, this is my edit.js file. In this file I try to do edit the form through AJAX, but I can't find where I doing mistakes.
<script>
$(document).ready(function (e) {
$('#update').click(function (event)
{
event.preventDefault();
$.ajax({
data: $('form').serialize(),
url: "edit.php", //php page URL where we post this data to save in database
type: 'POST',
success: function (strMessage) {
$('#message').text("strMessage");
}
})
});
});
</script>
You are doing edit and update on same file so you have to add condition on file. change your code as below:
edit.php
<?php
// including the database connection file
include_once("config.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if(empty($name) || empty($age) || empty($email)) {
if(empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if(empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while($res = mysqli_fetch_array($result))
{
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name;?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age;?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
Related
I want to show a sweetalert after clicking the set button but it won't function. This is my index page and the set button can function but it won't show the sweet alert. what might be the problem and what should I do?
index.php
<form method='post' action='updataStatus.php'>
<button type='submit' name='but_update' class="inline-block float ml-2 mt-1 btn-group pull-right btn-danger btn-sm">SET</button><button type="submit" id="dataExport" name="dataExport" value="Export to excel" class="inline-block float ml-2 mt-1 btn-group pull-right btn-info btn-sm">Export</button>
<div class="table-responsive">
<br>
<tbody><table class="table table-hover table-bordered" id="sampleTable2">
<thead>
<tr>
<th><input type="checkbox" class="select-all checkbox" name="select-all" id="checkAll" /></th>
<th>Name</th>
<th>Scholarship Program</th>
<th>Course</th>
<th>Semester</th>
<th>Allowance</th>
</tr>
</thead>
<?php
require_once "connection.php";
$query = "SELECT * FROM allowance";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result) ){
$id = $row['id'];
$Name = $row['Name'];
$Scholarship = $row['Scholarship'];
$Course = $row['Course'];
$Semester = $row['Semester'];
$statusAllowance = $row['statusAllowance'];
?>
<tr>
<!-- Checkbox -->
<td><input type='checkbox' name='update[]' value='<?= $id ?>' ></td>
<td><p name="Name"><?php echo $row['Name']; ?></p></td>
<td><p name="Scholarship"><?php echo $row['Scholarship'] ?></p></td>
<td><p name="Course"><?php echo $row['Course'] ?></p></td>
<td><p name="Semester"><?php echo $row['Semester'] ?></p></td>
<td><p name='statusAllowance_<?= $id ?>'><?php echo $row['statusAllowance'] ?></td>
</tr>
<
?php
}
?>
</table>
</tbody>
<?php
if(isset($_SESSION['success']) && $_SESSION['success'] !='')
{
?>
<script type="text/javascript">
swal({
title: "<?php echo $_SESSION['success']; ?>",
icon: "<?php echo $_SESSION['status_code']; ?>",
button: "yissh",
});
</script>
<?php
unset($_SESSION['success']);
}
?>
This is my code on the edit part and this works, only the alert won't show up.
updataStatus.php
<?php
require_once "connection.php";
if(isset($_POST['but_update'])){
if(isset($_POST['update'])){
foreach($_POST['update'] as $id){
$statusAllowance = 'Received';
if($statusAllowance != '' ){
$updateUser = "UPDATE allowance SET statusAllowance='".$statusAllowance."' WHERE id=".$id;
$query_run = mysqli_query($conn,$updateUser);
if($query_run){
$_SESSION['success'] = "YOUR DATA UPDATED";
header('Location: tracking.php');
}else{
$_SESSION['success'] = "YOUR DATA IS NOT UPDATED";
header('Location: tracking.php');
}
}
}
}
}
?>
considering you have not implemented another function to call sweetalert; by default, it should be Swal.fire({}) not just swal({})
https://sweetalert2.github.io/
I'd like to get an interactive block in my page that onchange of one of the 3 search fields only reloads the div 'mydata' and reruns the query with a new filter. I know it probably can be done with ajax but i'm stuck in finding the right piece of code.
Here's my testcode
Main php file users2.php:
<head>
<title>Test</title>
<script src="../jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script>
<script src="../jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<script>
$.ready(function() {
// create the on change event
$('#search_name').on('change', function() {
// get the new information from the server
$.ajax({
url: 'users_functions2.php?id=' + $('#search_name').val(),
success: function(data){
// this code is run when you get the reply;
$('#mydata').html(data);
}
});
});
});
</script>
</head>
<body>
<?PHP
include '../conf/config.inc.php';
include 'users_functions2.php';
?>
</body>
And here the include file users_functions2.php:
<?php
echo "<div id='mydata'>";
echo "<table><tr><th>ID</th><th>Name</th><th>City</th></tr>";
echo "<tr>";
echo "<td><input type=text placeholder='search' name=search_id</td>";
echo "<td><input type=text placeholder='search' name=search_name</td>";
echo "<td><input type=text placeholder='search' name=search_city</td>";
echo "</tr>";
$sql="select id, name, city from users;";
if (isset($_GET['search_name'])) { $sql .= "WHERE vo_name LIKE \"%".$_GET['search_name']."%\""; }
$res = my_query($sql);
while($row = mysqli_fetch_array($res)) {
echo "<tr><td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['city']."</td></tr>";
}
echo "</table>";
echo "</div>";
?>
Hope Chris is ok with this, i'd like my question being answered with a working example:
File 1:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js" integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
// create the on change event
$('#search_name').on('change', function() {
// get the new information from the server
$.ajax({
url: 'users_functions2.php?search_name=' + $('#search_name').val(),
success: function(data){
// this code is run when you get the reply;
$('#mydata').html(data);
}
});
});
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th><th>Name</th><th>City</th>
</tr>
<tr>
<th><input type=text placeholder='search' name=search_id></th>
<th><input type=text placeholder='search' id='search_name' name=search_name></th>
<th><input type=text placeholder='search' name=search_city></th>
</tr>
</thead>
<tbody id="mydata">
<?PHP
include 'users_functions2.php';
?>
</tbody>
</table>
</div>
</body>
File 2:
<?php
include '../conf/config.inc.php';
$sql="SELECT id, `name`, city FROM users";
$search_name = filter_input(INPUT_GET, 'search_name');
if ($search_name) {
$sql .= " WHERE vo_name LIKE \"%$search_name%\"";
}
$res = my_query($sql);
while($row = mysqli_fetch_array($res)) {
extract($row);
echo "<tr><td>$id</td><td>$name</td><td>$city</td></tr>";
}
?>
<html>
<head>
<link rel="stylesheet" href="js/jquery-ui-themes-1.11.1/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.11.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $('input#departmentID').val();
alert(departmentID);
});
});
</script>
</head>
<body>
<?php
//db connection
$query = "SELECT *
FROM department
ORDER BY dept_ID ASC";
$result = mysqli_query($dbc, $query);
$total_department = mysqli_num_rows($result);
if($total_department > 0)
{
?>
<table width="600" border="1" cellpadding="0" cellspacing="0" style="border-collapse:collapse">
<tr>
<td width="80" align="center">ID</td>
<td width="300" align="center">Department</td>
<td width="220" align="center">Action</td>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td align="center"><?php echo $row['dept_ID']; ?></td>
<td align="center"><?php echo $row['dept_name']; ?></td>
<td>
<button class="buttonsPromptConfirmDeleteDepartment">Delete</button>
<input type="hidden" id="departmentID" value="<?php echo $row['dept_ID']; ?>" />
</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
department table
dept_ID dept_name
1 Account
2 Finance
3 Marketing
Assume that my department table only have 3 records.
My requirement is the following:
- Click 1st delete button, show department ID = 1
- Click 2nd delete button, show department ID = 2
- Click 3rd delete button, show department ID = 3
However from my code, I can't meet my requirement. The department ID output that I get is 1 no matter what button I clicked.
Can someone help me?
No need to use a hidden input, you could just use the button tag instead:
<?php while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td align="center"><?php echo $row['dept_ID']; ?></td>
<td align="center"><?php echo $row['dept_name']; ?></td>
<td>
<button type="submit" name="departmentID" class="buttonsPromptConfirmDeleteDepartment" value="<?php echo $row['dept_ID']; ?>">Delete</button>
</td>
</tr>
<?php } ?>
Of course, in the PHP script that does the form processing, access the POST index like you normally would:
$id = $_POST['departmentID'];
// some processes next to it
Note: Don't forget the <form> tag.
Additional Note: Don't forget to use prepared statements:
$sql = 'DELETE FROM department WHERE dept_ID = ?';
$stmt = $dbc->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
// some idea, use error checking when necessary
// $dbc->error
Change
id="departmentID"
to
class="departmentID" and
Change
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $('input#departmentID').val();
alert(departmentID);
});
});
to
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $(this).next('input.departmentID').val();
alert(departmentID);
});
});
first of all dept_id in while loop and you are using same id for all dept..
another thing you can get dept_id upon button click using jquery.. like this
$('.buttonsPromptConfirmDeleteDepartment').click(function(){
dept_id = $(this).next('input').val();
})
Why is it that I cant pass a value from my PHP code to an OnClick function on my button to my javascript function depCheck2()? I would like to redirect it to 2 different pages depending on the value it carries. Could anyone please help me?
<html>
<head>
<?php
$company_id = $_GET['cont'];
$query = "SELECT count(Department_ID) as countDep FROM department WHERE Company_ID=$company_id";
$result = mysql_query($query, $db) or die(mysql_error($db));
$row = mysql_fetch_array($result);
extract($row);
?>
<script>
function depCheck2(x){
var CountRow = '<?php echo "$countDep";?>';
if (CountRow>0){
window.location.assign("editEvent.php?id="+x"");
}
else{
window.location.assign("editEvent.php2?id="+x"");
}
}
</script>
</head>
<body>
<?php
include("config.php");
$company_id = $_GET['cont'];
$query = "select * from event_details where Company_ID=".$company_id." ORDER BY EventDetails_ID DESC";
$result=mysql_query($query, $db) or die(mysql_error($db));
echo "<table border=1 width='1000'>";
echo "<tr><th>Serial Number</th><th>Status</th><th>Event Type</th><th>Date of Event</th><th>End Date</th><th>Details</th></tr>";
while ($row = mysql_fetch_array($result))
{
extract($row);
echo "
<tr>
<td align='center'>$EventDetails_ID</td>
<td align='center'>$Status</td>
<td align='center'>$EventType</td>
<td align='center'>$StartDate</td>
<td align='center'>$EndDate</td>
<td align='center'>
<input type='button' value='Details' class='btn btn-large btn-primary' onClick='depCheck2(\''.$EventDetails_ID.'\')'>
</td>
</tr>
";
}
?>
</table>
</body>
</html>
At first: <?php echo "$countDep";?> contains $countDep which is not defined in PHP.
It is only present in the DB Query but you haven't assigned it to any variable from the $result
Then window.location.assign("editEvent.php?id="+x""); the syntax is wrong.
You have extra quotes at the end.
It should be window.location.assign("editEvent.php?id="+x);
Try this one:
window.location.href ="editEvent.php2?id="+x;
i have this form, when user clicks on the submit button, a script open a popup where i need to print the radio button value. My problem is the printed value on the popup window: "on" but the result should be a number (selected person's id)
My PHP Code:
<form method="post" action="edit.php" onsubmit="target_popup(this,'edit.php')"><input type="submit" value="Modifica Giocatore" /><br /><br /><br />
<?php
//my queries (work)
?>
<table cellspacing="2" cellpadding="2">
<tr>
<th></th>
<th>Name</th>
<th>Surname</th>
</tr>
<?php
$i=0;
while ($i < $num) {
$id=mysql_result($results,$i,"ID");
$name=mysql_result($results,$i,"Name");
$surname=mysql_result($results,$i,"Surname");
?>
<tr>
<td><input type="radio" name="radioEdit" value"<?= $id; ?>" /><?= $id; ?></td>
<td><?=$name?></td>
<td><?=$surname?></td>
</tr>
<?php
$i++;
}
?>
<?php
echo "</table></form>"
?>
And this is my script:
function target_popup(form,page)
{
window.open(page, 'formpopup', 'left=100,top=100,width=600,height=400,menubar,toolbar,resizable');
form.target = 'formpopup';
}
edit.php file:
<?php
$prova = $_POST['radioEdit'];
echo $prova;
?>
Thanks.
The only way I could get this to work was to use sessions.
Here is what I could test without setting up an entire DB.
PHP
<?php
session_start();
$id="12345"; // test ID number
// works with sessions
$prova = $_POST['radioEdit'] = $_SESSION['id'] = $id;
echo $prova;
?>
<form method="post" action="edit.php" onsubmit="target_popup(this,'edit.php')">
<td><input type="radio" name="radioEdit" value"<?php echo $id; ?>" /><?= $id; ?></td>
<input type="submit" value="Modifica Giocatore" />
</form>
<script>
function target_popup(form,page)
{
window.open(page, 'formpopup', 'left=100,top=100,width=600,height=400,menubar,toolbar,resizable');
form.target = 'formpopup';
}
</script>
edit.php
<?php
session_start();
echo $_SESSION['id'];
echo $id;
echo "<br>";
var_dump($_SESSION['id']);
?>
What happens when you echo $id? Are you sure that it returns a value? Also isn't <?= ;?> considered really old and deprecated PHP? You should be using <?php echo ;?>