update_multiple_rows using ajax and php - javascript

please in need help in updating multiple rows based on dynamic data fetched from mysql database. I have implemented this using $_Post to udate.php file, but how can i do this using ajax.
//THIS SCRIPT FETCH FROM DATABASE
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("student") or die("Unable to select database");
$sql = "SELECT * FROM students ORDER BY id";
$result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
$i = 0;
echo '<table width="50%">';
echo '<tr>';
echo '<td>ID</td>';
echo '<td>Name</td>';
echo '<td>Address</td>';
echo '</tr>';
echo "<form name='form_update' method='post' action='update.php'>\n";
while ($students = mysql_fetch_array($result)) {
echo '<tr>';
echo "<td>{$students['id']}<input type='hidden' name='id[$i]'value='{$students['id']}' /></td>";
echo "<td>{$students['name']}</td>";
echo "<td><input type='text' size='40' name='address[$i]' value='{$students['address']}' /></td>";
echo '</tr>';
++$i;
}
echo '<tr>';
echo "<td><input type='submit' value='submit' /></td>";
echo '</tr>';
echo "</form>";
echo '</table>';
echo $i; ?>
</body>
// HERE IS THE UPDATE SCRIPT
// On clicking submit all rows are updated but i still cant achieve dis with ajax.
UPDATE.PHP
$size = count($_POST['address']);
$i = 0;
while ($i < $size) {
$address= $_POST['address'][$i];
$id = $_POST['id'][$i];
$query = "UPDATE students SET address = '$address' WHERE id = '$id' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
echo "$address<br /><br /><em>Updated!</em><br /><br />";
++$i;
}
?>
HERE IS WHAT I HAVE TRIED ON AJAX
function update(){
var j=0;
while(j< <?php echo $i ; ?>){
var id=$("#id" + j);
var address=$("#address" + j);
$.ajax(
{
url:"update.php",
type:"post",
data:{id:id.val(),address:address.val()},
success:function(response)
{
}
});
}
ANY HELP WILL BE APPRECIATED

You shouldn't need to loop and execute multiple POSTs. Simply serialize the form data and send it to the script, e.g.:
$.ajax({
url: 'update.php',
type: 'post',
data: $('#your-form-id').serialize(),
success:function(response){
// do something
}
});
Also, you should consider revising your PHP to prevent SQL injection: How can I prevent SQL injection in PHP?

Related

How can I access the values of a checkbox outside of the form action that it is declared in?

I successfully created a script that will delete the rows of a table if a checkbox is checked on that row (the checkbox holds the rowID). The checkboxes and button to delete these rows are inside of the same form tags. Now I want to create another button that uses the value of the checkboxes to do a different update statement, but the values of the checkboxes are not appearing in $_POST on this separate page.
Does anyone know how to make the checkbox values accessible outside of the form action it is inside of? Here is my reduced code for the delete that works:
The function below is called on PickTicket.php to display a table.
Function DisplayPickTicket() {
$conn = getDBConnection();
$sql = "SELECT * FROM dbo.BK_NotesRecord WHERE StatusID = 1 ";
$stmt = sqlsrv_query( $conn, $sql );
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true) );
}
echo '<form action="updatepickstatus.php" method="post">';
// Delete Checkbox header.
echo '<th class="table-header" style="width:5px;">';
echo 'Delete';
echo '</th>';
// Inventory number header.
echo '<th class="table-header" style="width:90px;">';
echo 'Inventory #';
echo '</th>';
//InventoryID Header
echo '<th class="table-header" style="width:40px;">';
echo 'InventoryID';
echo '</th>';
if (sqlsrv_has_rows($stmt)) {
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
echo '<tr>';
//Delete checkbox
echo '<td class="cell"><div class="cell">';
echo '<input type = "checkbox" name="chkbox[]" value= "' .$row['InventoryID'].
'">';
echo '</td>';
// Inventory#
echo '<td class="cell"><div class="cell">';
echo $row["InventoryNumber"];
echo '</td>';
// InventoryID.
echo '<td class="cell"><div class="cell">';
echo $row["InventoryID"];
echo '</td>';
}
}
echo "<tr>";
echo "<td>";
echo "<input type='submit' name='submit' Value='Remove'>";
echo '</form>';
echo "</td>";
echo "</tr>";
This is updatepickstatus.php:
<?php
$serverName = "(local)";
$connectionOptions = array("Database"=>"Powerlink");
$conn = sqlsrv_connect( $serverName, $connectionOptions);
if( $conn === false ) {
echo "Connection failed!<br>";
die( print_r( sqlsrv_errors(), true));
}
if (isset($_POST['chkbox'])) {
foreach($_POST['chkbox'] as $Update) {
$sql = "UPDATE BK_NotesRecord set StatusID = '2' WHERE InventoryID LIKE '".$Update."'";
$stmt = sqlsrv_query( $conn, $sql );
//echo '$ids';
}
}
print_r($_POST);
?>
^^I want to accomplish this same basic task, but outside of updatepickstatus.php. When applying similar logic to check the values of the selected checkboxes on a different I get an empty array. Any thoughts?
Try declaring a variable and passing the value you want to use to it then use sessions to move it where ever you want.

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

PHP table auto update the data but not the table

I have a game server which has a chat function and logs all players' chat messages to my database. I'm trying to create a table that automatically updates the data but not the table itself, this is because on my table I want a dropdown list of actions for each player (kick player from server, ban player, mute player, slap player etc.) but my JavaScript code at the moment refreshes the whole table every 5 seconds. So, if I open my dropdown list, when the table refreshes it will close the dropdown list, at the moment I've changed the dropdown list to a button because of this problem.
Here is my code:
Index page that displays the table:
<?php require 'session.php';
require 'header.php'; ?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#results').load('includes/online.php');
}, 3000); // refresh rate in milliseconds.
});
// ]]></script>
<div id="results">Loading data ...</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#results2').load('includes/chatlog.php');
}, 3000); // refresh rate in milliseconds.
});
// ]]></script>
<div id="results2">Loading data ...</div>
<?php
include 'database.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT *,current_clients.CID AS con_id FROM current_clients INNER JOIN groups ON current_clients.Level = groups.level Order By Team DESC, Score DESC";
$result = $conn->query($sql);
while( $row = mysql_fetch_array($result));
if ($result->num_rows > 0) {
echo "<div id=left>";
echo "<table class=table align=center><tr><th>ID</th><th>Name</th><th>Rank</th><th>Score</th><th>IP</th><th>Action</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
$id=$row['con_id'];
$ip=$row['IP'];
$team=$row['Team'];
// $team = str_replace("3","<tr bgcolor=midnightblue>",$team);
// $team = str_replace("2","<tr bgcolor=darkred>",$team);
// $team = str_replace("1","<tr bgcolor=grey>",$team);
$name=$row['ColorName'];
$group=$row['name'];
$name=htmlentities($name);
$name = str_replace("^0","</font><font color=black>",$name);
$name = str_replace("^1","</font><font color=red>",$name);
$name = str_replace("^2","</font><font color=lime>",$name);
$name = str_replace("^3","</font><font color=yellow>",$name);
$name = str_replace("^4","</font><font color=blue>",$name);
$name = str_replace("^5","</font><font color=aqua>",$name);
$name = str_replace("^6","</font><font color=#FF00FF>",$name);
$name = str_replace("^7","</font><font color=white>",$name);
$name = str_replace("^8","</font><font color=white>",$name);
$name = str_replace("^9","</font><font color=gray>",$name);
$score=$row['Score'];
//echo $team;
echo "<td align=center> $id </td>";
echo "<td align=center><a href='user.php?id=".$row["DBID"]."' > $name </a></td>";
echo "<td align=center> $group </td>";
echo "<td align=center> $score </td>";
echo "<td align=center> $ip </td>";
echo "<td align=center>";
echo "<form action=q3/slap.php?id=$id method=POST><button type=submit>Slap</button></form>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "<table class=table align=center><tr><th>ID</th><th>Name</th><th>Rank</th><th>Score</th><th>IP</th><th>Action</th></tr>";
echo "<tr>";
echo "<td>";
echo "There are no players online";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</div>";
}
$conn->close();
?>
My "online players" table is above.
You could store a timestamp on the server that you update each time a change is made on the database. Then, in your setInterval first fetch the last update time from the server and compare it to the one from when the page was loaded; if they are different refresh the page, otherwise do nothing.

loop list of input checkbox and get values

I am trying to get a table of names checked,
and send this array to a PHP page.
But I dont know how, I began by this code:
$(".ok").click(function(){
$("input[type='checkbox']:checked").each(function() {
var tt = $(this).val();
alert(tt);
});
});
echo "<table>";
foreach ($result as $data) {
echo "<tr>";
echo "<td><input type='checkbox' value='$data[0]' /></td><td>$data[0]</td>";
echo "</tr>";
}
echo "</table>";
Try..
$(".ok").click(function(){
//check if any are checked and if so redirect..
if($("input[type='checkbox']:checked").length > 0)
window.location.href = 'page.php?'+$("input[type='checkbox']:checked").serialize();
});
then in page.php..
$result = $_GET;
if(count($result)){
foreach($result as $data){
echo "<tr>";
echo "<td><input type='checkbox' value='$data' /></td><td>$data</td>";
echo "</tr>";
}
}

Clickable data displayed from mysql using PHP

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.

Categories

Resources