I have a form that updates the adds to the table. This table is retrieved live. which means once submitting the form you can view the content on the table. I added a select option drop down on the table content. I am not sure how to get this info in back to mysql once the user chooses his option. As seen in the code my file is a PHP file.
my select option is updates by javascript but it does not update mysql.
Kindly guide me. Thank you
while($row = mysqli_fetch_assoc($resultset))
{
echo "<tr id=\"row\">
<td class=\"fname\" data-id1=".$row["contact_id"]." contenteditable>" . $row['fname'] ." </td>
<td class=\"lname\" data-id2=".$row["contact_id"]." contenteditable>" . $row['lname']. "</td>
<td>" . $row['contact']."</td>
<td>
<select id4=".$row['contact_id']." name=\"rsvp\" onchange = \"fetch_select(this.value)\">
<option name=\"not-done\" value=\"not-done\">Not done</option>
<option name=\"attending\" value=\"attending\">Attending</option>
<option name=\"not-attending\" value=\"not-attending\">Not-attending</option>
<option name=\"maybe\" value=\"maybe\" selected>Maybe</option>
</select>
</td>
<td><button id3=".$row['contact_id']." name=\"button\"><i class=\"fa fa-trash-o\" aria-hidden=\"true\"></i></button>
<tr>";
}
echo "</table>";
mysqli_close($con);
?>
$('select').on('change', function()
{
// Show an alert
alert( "The new value of the select is " + $(this).val() );
var id=$(this).attr("id4");
var val=$(this).val();
function fetch_select(val ,id)
{
$.ajax({
url:"updateselect.php",
method:"POST",
data:{rsvp:val , id:id},
dataType:"text",
success:function(data){
alert(data);
}
});
}
});
<?php
$connect = mysqli_connect("localhost", "root", "", "registration");
$id = $_POST["id"];
$rsvp = $_POST["val"];
$sql = "UPDATE guestlist SET rsvp ='".$rsvp."' WHERE contact_id='".$id."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Updated';
}
?>
You want to create a form surrounding your dropbox; now you can either submit it using ajax or just submit it to a different page, your call.
It would look something like this:
Note: Add a name param to your select so you can actually get it using $_POST and handle the data.
<form method="post" action="rsvp_handler.php">
<?php
while($row = mysqli_fetch_assoc($resultset))
{
echo "<tr id=\"row\">
<td class=\"fname\" data-id1=".$row["contact_id"]." contenteditable>" . $row['fname'] ." </td>
<td class=\"lname\" data-id2=".$row["contact_id"]." contenteditable>" . $row['lname']. "</td>
<td>" . $row['contact']."</td>
<td>
<select name='rsvp' id='rsvp'>
<option value=\"not-done\">Not done</option>
<option value=\"attending\">Attending</option>
<option value=\"not-attending\">Not-attending</option>
<option value=\"maybe\" selected>Maybe</option>
</select>
</td>
<td><button id3=".$row['contact_id']." name=\"button\"><i class=\"fa fa-trash-o\" aria-hidden=\"true\"></i></button>
<tr>";
}
echo "</table>";
mysqli_close($con);
?>
<button type="submit" name="submit">Submit</button>
</form>
Then for the rsvp_handler.php page just take the post result and then send the wanted data to your database:
if (isset($_POST['submit']))
{
$rsvp = $_POST['rsvp'];
//... any other elements
// create your query here
$sql = "INSERT INTO " . $table . " (rsvp, row2, row3) VALUES (?, ?, ?)";
// best way is to create prepared statements
if($stmt = $mysqli->prepare( $sql ))
{
// bind the params
$stmt->bind_param('sss', $rsvp, $val2, $val3);
// execute the query
$stmt->execute();
// close the connection
$stmt->close();
}
}
Hi I found the answer to the solutions.
My ajax need to have a separate function.
Related
<body>
<H1>4a</H1>
<form action="hw4b.php" method="post">
<?php
$con = mysqli_connect("localhost","[credential]","","[credential]")
or die("Failed to connect to database " . mysqli_error());
?>
<select name="id" value="id">
<script>
for (x=1;x<=101;x++)
{
document.write("<option value="+x+">"+
<?php echo mysqli_query($con, "SELECT LASTNAME FROM CUSTOMERS WHERE CUSTOMERID == "+x+";")?>
+"</option>");
}
</script>
</select>
<input type="submit" value="SEND IT">
</form>
</body>
So this should put the corresponding LASTNAME into the select, but it just fills every row with "NaN". I'm sure this is some stupid minor error, but I've been staring at it too long.
you should query the results of mysqli_query
do something like this:
<select name="id" value="id">
<?php
$query = mysqli_query($con, "SELECT LASTNAME FROM CUSTOMERS WHERE WHERE CUSTOMERID >=1 and CUSTOMERID <= 101 ;");
while ($row = mysqli_fetch_array($query))
echo "<option id='".$row['LASTNAME']."'>".$row['LASTNAME']."</option>";
?>
</select>
notes:
no need for javascript usage
please escape the query parameter
id of the option is the value that will be sent to the server, makes more since to send LASTNAME
avoid using a query at a loop
Note that your for cycle is in javascript (between <script> tags), yet you try to fill in some data in php.
Everything in PHP happens on server side, i.e. is interpreted, packed into a http response and returned to the client, where it is unpacked and javascript is executed.
You need to either put both into javascript, or both into php.
<select>
<?php
for ($i = 0; $i < 100; i++){
///make some select here
echo "<option value="$i"> ...output the select </option>"
}
?>
</select>
This way, all options are generated on server side and transferred to client as text
<select>
<option value="0">...</option>
<option value="1">...</option>
...
Other option is to export the database data into javascript, and then access it in javascript.
<script>
//or perhaps better
var myOtherData = <?=json_encode($somePHPData)?>;
</script>
//now you can use for loop with document.write and one of the variables you exported...
You need to be very careful and sure which execution happens on server, and which on client side.
There are several issues I think. You are using a comparison operator in the SELECT statement, it should just be =, not ==. Also, mysqli_query returns a mysqli_result, not a value like "Johnson" for LASTNAME. And, maybe most importantly, it doesn't make sense to do this with javascript since you're writing the values to the document before sending it to the browser anyway.
The code should look something like this (not tested)
<select name="id" value="id">
<?php
$query = 'SELECT LASTNAME, CUSTOMERID FROM CUSTOMERS WHERE CUSTOMERID >= 1 AND CUSTOMERID <= 101 ORDER BY CUSTOMERID ASC';
$result = mysqli_query($con, $query);
if (!$result) {
echo 'some error handling';
} else {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row['CUSTOMERID'] . '">' . $row['LASTNAME'] . '</option>';
}
}
?>
</select>
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']
I'm learning PHP and SQL and as exercise I'm working on a page that is actually something like admin panel for a website that lists movies. I'm using lampp and phpmyadmin where I have created a simple database that contains two tables, movie list and users list.
Because I'm beginner and my code is probably messy, I'm describing what I tried to achieve. There's login.php page where the only functionality is typing username and password. If info matches info from SQL table, user proceeds to adminpanel.php.
This page should load a list of movies and create a table with that data. At the end of each row I want two buttons, edit and delete. What I'm trying to achieve is to delete current row where delete button is clicked, for delete button. Edit button should show hidden form just for the row where button was clicked. This form would contain button that actually updates data in SQL table after filling form and clicking the button. (I haven't added function that shows form yet, I care about buttons much more) Form for adding movies at the end of the file works.
Here's adminpanel.php
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
<script type="text/javascript" src="changes.js"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></script>
<style type="text/css">
*{text-align: center;}
.skriveni_input{
display: none;
};
</style>
</head>
<?php
require_once('connection.php');
if(!isset($_POST['btnlogin'])){
exit;
}
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT usrname,password FROM usrs WHERE usrname='$username' AND password='$password' ";
$res = mysqli_query($conn,$query);
$rows = mysqli_num_rows($res);
if($rows == 1){
echo "Welcome ".$_POST['username']."<br><br>";
} else {
echo "<script>
alert('Wrong login info');
window.location.href='login.php';
</script>";
exit;
}
$query = "SELECT * FROM movies";
$result = $conn->query($query);
echo "<table align = center cellspacing = 0 border = 0;><thead><tr><th>Name</th><th>Year</th><th>Genre</th></tr></thead><tbody>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo '<td id="row_id" style="display:none;" value="'.$row["movie_id"].'">'.$row["movie_id"].'</td>';
echo '<td>'.$row["name"].'</td>';
echo '<td>'.$row["year"].'</td>';
echo '<td>'.$row["genre"].'</td>';
echo '<td><input type="submit" name="edit" value="edit" data-index="' . $row['movie_id'] . '" class="btnedit" id="btnedit"></input></td>';
echo '<td><input type="submit" name="delete" value="delete" class="btndlt" id="btndlt"></input></td>';
echo "</tr>";
echo "<tr>
<td><input type='text' class='hidden_input' id='hidden_name" . $row['movie_id'] . "'placeholder='hidden name'></input></td>
<td><input type='text' class='hidden_input' id='hidden_year" . $row['movie_id'] . "'placeholder='hidden year'></input></td>
<td><input type='text' class='hidden_input' id='hidden_genre" . $row['movie_id'] . "'placeholder='hidden genre'></input></td>
</tr>";
}
echo "</tbody></table>";
?>
<h3>Add movie form: </h3>
<form action="" method="POST">
<label for="movie_name">Movie name : </label>
<input type="text" name="movie_name" id="movie_name">
<br><br>
<label for="movie_year">Year: </label>
<input type="text" name="movie_year" id="movie_year">
<br><br>
<label for="movie_genre">Genre: </label>
<input type="text" name="movie_genre" id="movie_genre">
<br><br>
<input type="submit" name="submit_movie" id="submit_movie" value="Submit">
</form>
</html>
Here's my javascript file with ajax calls:
$(document).ready(function(e){
$('#submit_movie').click(function(e){
e.preventDefault();
var movie_name = $('#movie_name').val();
var movie_year = $('#movie_year').val();
var movie_genre = $('#movie_genre').val();
$.ajax({
type: 'POST',
data: {movie_name:movie_name, movie_year:movie_year, movie_genre:movie_genre},
url: "insert.php",
success: function(result){
alert('Movie ' + movie_name + ' (' + movie_year + ')' +' added successfully.');
document.location.reload();
}
})
});
$('.btnedit').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().html();
alert(id);
//unfinished function
})
$('.btndlt').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().prev().html();
e.preventDefault();
$.ajax({
type: 'POST',
data: {id:id},
url: 'delete_row.php',
success: function(result){
alert('Successfully deleted.');
document.location.reload();
}
})
})
});
Here's php page for adding a movie, insert.php (this one works, posting it just for more information) :
<?php
require_once('connection.php');
if($_REQUEST['movie_name']){
$name = $_REQUEST['movie_name'];
$year = $_REQUEST['movie_year'];
$genre = $_REQUEST['movie_genre'];
$sql = "INSERT INTO movies(name, year, genre) VALUES ('$name','$year','$genre')";
$query = mysqli_query($conn, $sql);
}
?>
Here's delete_row.php file for deleting entry with delete button:
<?php
require_once('connection.php');
$id = $_REQUEST['id'];
if(isset($_REQUEST['delete'])){
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
As you can probably see I was all over the place with php and ajax because I tried to implement multiple solutions or mix them to solve the problem.
At this stage when I click delete button I get alert message that says erasing is successful and adminpanel.php reloads with list of movies. However the movie is still there and in SQL database.
When I tried to debug delete_row.php I found out that index "id" is undefined every time even though I think I'm passing it with ajax call.
Edit
I should've said that security is not my concern right now, I do this exercise just for functionalities I described. :) Security is my next step, I am aware this code is not secure at all.
When I tried to debug delete_row.php I found out that index "id" is
undefined every time even though I think I'm passing it with ajax
call.
The reason this happens is probably because you're accessing delete_row.php directly through the browser, and because the form is not submitted (it will later through ajax) the $_REQUEST variable will always be undefined.
When debugging $_REQUEST (or $_POST) variables in the future, you should use Postman where you can actually request that php file sending your own POST arguments.
On your specific code, the query will never run because of this line:
if(isset($_REQUEST['delete']))
Which is checking for a delete variable that was never sent in the first place, hence will always resolve false
Use this code instead on delete_row.php:
<?php
require_once('connection.php');
if(isset($_REQUEST['id'])){
$id = $_REQUEST['id'];
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've looked through the existing questions and i don't believe they are answering my question.
I have created a table that gets populated using PHP and MySQL. I have got my add function working so the user can ADD a new row, however I would like the user to remove specific rows. Each row has a remove icon that I would like when clicked to remove ONLY that row.
Home.php (where table is created)
<table class="table table-bordered table-striped table-responsive">
<tr class="header">
<td>id</td>
<td>Rep</td>
<td>Date</td>
<td>Name</td>
<td>P_O</td>
<td>Due Date</td>
<td>Terms</td>
<td>Aging</td>
<td>Open Balance</td>
<td>remove</td>
</tr>
<?php
while($row = mysql_fetch_array($query))
{
$className ="";
if ($row['Aging'] >= 45) {
$className="danger";
}
else if($row['Aging'] >= 25 && $row['Aging'] <= 44) {
$className="warning";
}
echo "<tr class='$className'>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['Rep']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['P_O']."</td>";
echo "<td>".$row['Due_Date']."</td>";
echo "<td>".$row['Terms']."</td>";
echo "<td>".$row['Aging']."</td>";
echo "<td>".$row['Open_Balance']."</td>";
echo "<td><button type='button' class='btn btn-link'><i class='iconhover fa fa-check-circle fa-2x'></i></button></td>";
}
?>
</table>
This is the remove button:
<button type='button' class='btn btn-link'><i class='iconhover fa fa-check-circle fa-2x'></i></button>
I would like it to remove the row that its currently part of when clicked. Any help?
Here is my new code, however it still doesn't seem to be deleting the row
home.php:
while($row = mysql_fetch_array($query))
{
$className ="";
if ($row['Aging'] >= 45) {
$className="danger";
}
else if($row['Aging'] >= 25 && $row['Aging'] <= 44) {
$className="warning";
}
echo "<tr class='$className'>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['Rep']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['P_O']."</td>";
echo "<td>".$row['Due_Date']."</td>";
echo "<td>".$row['Terms']."</td>";
echo "<td>".$row['Aging']."</td>";
echo "<td>".$row['Open_Balance']."</td>";
echo "<td><button action='deletepage.php' method='POST' value='" .$row['id']. "' class='btn btn-danger'> Delete</button></td>";
}
deletepage.php:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_GET['id'])){
$userID = (int) $_GET['id'];
if(!empty($_GET['id'])) {
$delete = mysql_query("DELETE FROM Book1 WHERE id='$userID'");
}
if($delete) {
echo "Record deleted successfully";
}
else {
echo "Sorry, record could not be deleted";
}
}
You can do by directing it to the delete page like this:
Delete
Or with javascript AJAX call:
Delete
and use $.post to the deletion page
UPDATE:
the deletion page deletepage.php may contain the following:
<?php
require('dbconn.php');
if(isset($_POST['id'])){
$userID = (int) $_POST['id'];
if(!empty($_POST['id'])){
$delete = mysql_query("DELETE FROM users WHERE id='$userID'");
}
if($delete){
echo "Record deleted successfully";
}else{
echo "Sorry, record could not be deleted";
}
}
?>
users.php
<?php
require('dbconn.php');
$get = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($get)) {
echo '<p>';
echo $row['id'] . ' - ' . $row['user'];
?>
Delete
</p>
<?php } ?>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function confirmDeletion(id){
$.post('deletepage.php', { id:id }, function(data){
alert(data);
location.reload();
});
}
</script>
P.S:
It's very recommended to quit using mysql_query() in this way and instead use PDO to avoid SQL injection
I would change the button to include the value of the row id, by adding a value attribute to the button html:
value='" .$row['id']. "'
You can then capture the click event using jquery / javascript, and use an ajax call to remove the record from your database. It would look something like:
$('.btn-lnk').on('click',function() {
var id = $(this).val();
$.ajax({
type: "POST",
url: "yourPageThatDeletesRow.php",
data: { id: id },
success: function(response) {
if(response === 'success') {
//delete row showing on the page
$(this).closest('tr').remove();
} else {
//handle error
}
} //consider handling ajax error case
});
});
The ajax call will execute the code on yourPageThatDeletesRow.php. You can get the row id using $_POST['id'] and delete the data using that id. If the delete is successful, echo the string 'success'. Consider returning the error from the database if it's not successful, and handling that case in the return of the ajax
Here is a simplified JS Fiddle showing how the passing of the id and row deletion work.
You will need a delete button if your going to do it the way ive done it.
if (isset($_POST['delete'])){
$userid = $_POST['userid'];
$sql = "DELETE FROM users WHERE userid = '$userid';";
if ($conn->query($sql) === true){
//echo 'Click here to view modified patients';
}
}
Use this code:
<?php $temp_pre_ID = $row['id'];?>
<INPUT TYPE="button" onClick="window.location='home.php?Action=del&CusID=<?php echo $temp_pre_ID;?>'" value="Delete">
<div>
<script type="text/javascript">
$(document).ready(function(){
$('#selectstate').change(function() {
window.location = "dropexmpl.php?stateval=" + $(this).val();
});
$('#selectcity').change(function() {
window.location = "dropexmpl.php?cityval=" + $(this).val();
});
});
</div>
</script>
</head>
<body >
<div>
<?php
//state drop down
echo "<td"." id="."id_sel_state".">";
$con=mysql_connect("localhost","root","");
mysql_select_db("data_filter",$con);
$query=("SELECT id,state_name FROM state_details ");
$result = mysql_query ($query);
echo "<label id='statelab'>Select state : </label>"."<select name='filterstate'id='selectstate' onchange='getstateval()'>";
while ($nt = mysql_fetch_array($result)){
echo "<option value='".$nt['id']."'>".$nt['state_name']."</option>";
}
echo "</select>";
//city drop down
$statestrval= $_GET['stateval'];
echo "<td id='id_sel_city'>";
$query1="SELECT id,state_id,city_name FROM city_details WHERE state_id=".$statestrval.""; $result1 = mysql_query ($query1);
echo "<label>Select city : </label>"."<select name='filtercity' id='selectcity' >";
while ($nt = mysql_fetch_array($result1)){
echo "<option value='".$nt['id']."'>".$nt['city_name']."</option>";
}
echo "</select>";
//Zone drop down
$citystrval= $_GET['cityval'];
echo "<td id="."id_sel_zone".">";
$query2="SELECT id,city_id,zone_area FROM zone_details WHERE city_id=".$citystrval."";
$result2 = mysql_query ($query2);
echo "<label>Select industry zone : </label>"."<select name='filterzone' id='selectzone'>";
while ($nt = mysql_fetch_array($result2)){
echo "<option value='".$nt['id']."'>".$nt['zone_area']."</option>";
}
echo "</select>";
mysql_close($con);
?>
</div>
</form>
</body>
</html>
here i used 3 drop down state city and zone.it works but when page is reloaded with window.location code it show me the page with refresh effect how it solve by using ajax.
it should be like when i select the state is should be shows city list related to that state.when city is selected it should be shows the zone related to that city .but problem is when i go to select the city it change the state list and when i select zone it change the city list because of reloading of page how i can solve this problem.
I advise you to use AJAX, jQuery and avoid page refreshing.
Have a look to the jQuery documentation: http://api.jquery.com/jQuery.getJSON/