Updating MySQL Database with checkboxes and PHP - javascript

I am trying to update a MySQL database with checkboxes and PHP. I have read a lot of code examples online and read many questions on here but I seem to be stuck at the last hurdle.
My code first queries MySQL to bring back a list of users and then a checkbox (which is either 0 or 1 in MySQL) next to each one, indicating whether or not the user is completed.
What I am wanting to do is when the checkbox is checked, for that to update the MySQL database and update the column with 1, or if it is unchecked, for it to change the column to 2.
Here is my code so far:
HTML Snippet (Checkboxes):
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Firstname'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['Department'] . "</td>";
echo "<td>" . $row['RequestedBy'] . "</td>";
echo "<td>" . $row['StartDate'] . "</td>";
echo "<td class='tbl-chk'> <input type='checkbox' name='WSCompleted' value='"; echo $row['ID'] . "'" ; if ($row['WSCompleted']=='1') { echo "checked='checked'";} echo "/></td>";
Here is my jQuery that successfully retrieves the values and IDs and then posts them:
$(document).ready(function(){
$('input[name=WSCompleted]').click(function(){
var wsCompleted = $(this).is(':checked') ? 1 : 0;
var wsCompletedID = $(this).attr('value');
$.ajax({
type: "POST",
url: "/usr-handler.php",
data: {id: wsCompletedID, wsCompleted: wsCompleted},
success: function(){
$('div.success').fadeIn();
}
});
return true;
});
});
And finally here is a snippet of my PHP:
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['wsCompletedID'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
I am setting the value of the checkbox to what is actually the row ID in MySQL, then I can use the checkbox value to select the correct row in MySQL, and update it.
The problem I am having is that currently, how the code is, I get the following response from FireBug:
Unidentified index: WSCompletedID
After looking online it was suggested to change:
$id = $_POST['wsCompletedID'];
To:
$id = (ISSET($_POST['wsCompletedID']));
But doing so clears the error message, but then doesn't actually update the value on MySQL.
If I manually set the $id to something, the update works, but obviously that isn't right as it would only ever update the ID I have chosen it to.
I am completely stumped as to what is causing the problem. I have tried finding out online but cannot get anywhere with it.
Any help is greatly appreciated.
Thank you

You are loading data here in your javascript AJAX code
data: {id: wsCompletedID, wsCompleted: wsCompleted},
This will create the following $_POST array
id => whatever was in wsCompletedID
wsCompleted => whatever was in wsCompleted
So your PHP code should be looking for $_POST['id'] and $_POST['wsCompleted'] as these are the names you have given in your data:...
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['id'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
HOWEVER: Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements

Related

Not able to store ajax variables in session array

I am making a cart-mechanism with jquery, ajax and php. The problem is that the text in the html element aren't getting appended to the session array. This is my ajax code:
$(document).ready(function(){
$("#cart").on("click", function(){
var name = $("#name").text();
var cost = $("#cost").text();
$.ajax({
type:"post",
data:"name="+name+"&cost="+cost,
url:"senddata.php",
success:function(data){
$("#info").html(data);
}
});
});
});
This is my html displayed with php:
function getData()
{
require_once('../config.php');
$query = mysqli_query($conn, "SELECT p_name, p_cost, p_pic, p_desc FROM products");
while($row = mysqli_fetch_assoc($query))
{
echo "<form><tr>";
echo "<td id='name' name='name'>" . $row['p_name'] . "</td>";
echo "<td id='cost' cost='cost'>" . $row['p_cost'] . "</td>";
echo "<td>" . $row['p_pic'] . "</td>";
echo "<td>" . $row['p_desc'] . "</td>";
echo "<td id='cart'><input type='button' id='submit' value='Add To Cart'></td><tr></form>";
}
mysqli_close($conn);
}
And finally, this is where I have stored the ajax variables in a session array:
session_start();
$_SESSION['cart_name'] = array();
array_push($_SESSION['cart_name'], $_POST['name']);
var_dump($_SESSION['cart_name']);
$_SESSION['cart_cost'] = array();
array_push($_SESSION['cart_cost'], $_POST['cost']);
var_dump($_SESSION['cart_cost']);
I am getting no error whatsoever but the items get appended to the array the first time, but after that, the variables don't get appended at all.
Variables does not appended because you initialize every time the
$_SESSION['cart_name'] = array();
$_SESSION['cart_cost'] = array();
That means that every time before you push the new data you empty the SESSION var.

How using ajax can update mysql database from dropdown menu

As the question suggest can you tell me how i can update mysql database using a dropdown menu with the help of ajax. I want to update my database with out reloading my whole webpage.When a user click edit button the selected option from the drop down list is updated. After searching a while i found some tutorials for this method and took ajax codes from there. But when i tried those in my database; it didn't worked out. Below is the sample code for my php script, parent file contains both ajax script and php code in a single php file called samefile.php. Below script only contains the problematic codes, some html and php codes are intentionally removed.
//THIS AJAX SCRIPT FETCHES VALUES FROM THE SELECTED DROPDOWN
<script>
function get_da(str){
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:$("#dropdown").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
}
);
</script>
///////////////////////////////FIRST BLOCK//////////////////
<?php
//THIS PHP SCRIPT GENERATES DROP DOWN VALUES FROM DATABASE
echo "<select name='dropdown' onChange='get_da(this.value)'>";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
/////////////////////////////SECOND BLOCK//////////////////////////////
//THIS PHP SCRIPT VALIDATES THE SELECTED DROPOWN VALUE AND PASS THOSE VALES FOR FURTHER PROCESSING.
if(isset($_REQUEST['dropdown1']))
{
$name=get_the_selected_dropdown_name; //i dont know how to fetch name from dropdown menu
$sql = "UPDATE table SET name = '$name' WHERE id =10";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
//////////////////////////////THIRD BLOCK////////////////////////////////////
?>
I believe this is how my above script works. when a user select a particular option from the drop down menu this function onChange='get_da(this.value)' sends the value (both id and name) to ajax query. in ajax query the drop down values are collected (both id and name) and renames as dropdown1 (data: { dropdown1:$("#dropdown").val()}) and pass it to php script inside the same file. Php script confirms the request from ajax using this if(isset($_REQUEST['dropdown1'])) and the script inside will be executed.
Please forgive me if i made a mess of my code. I suck at java script and ajax so am not sure whether my coding is right for those scripts. if possible can you suggest any other scripts for updating mysql database using ajax drop down list.
EDITED
ID DROPDOWN VALUE
1 ROY
2 TOM
3 CHASE
4 THOMAS
5 GEORGE
6 MICHAEL
have tried by printing the value you are sending in ajax request. You are passing this.value to your function get_da(str). But I think you are using it anywhere , In ajax post you are sending the value like
data: {dropdown1:$('#dropdown').val()}
But this will not post your selected vaule from dropdown, Try like this:
<script>
function get_da(this){
var id = $("#dropdown option:selected").val();
var selectedName = $("#dropdown option:selected").text();
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:id, name:selectedName}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
//drawVisualization();
},
});
}
</script>
Hope this will work.
Your dropdown script should be like this:
<?php
echo "<select name="dropdown" onchange="get_da()" id="dropdown">";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
This will send your selected value from drop down to your samefile.php.And also you are not doing good with your php script it should be like:
if(isset($_REQUEST['dropdown1']))
{
$id=$_REQUEST['dropdown1'];
$name=$_REQUEST['name'];
$sql = "UPDATE table SET name = '$name' WHERE id ='$id'";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
?>

How to retrieve data from .php and display in <select> within Cordova hybrid app?

I am writing a hybrid app using Visual Studio with Cordova exetnstion and trying to pull data from www.a.com/b.php
My b.php code is:
<?php
// Connect to database server
mysql_connect("http://www.yo.com", "ya", "ye") or die (mysql_error());
// Select database
mysql_select_db("oh") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Properties ORDER BY number DESC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
echo '<select name="Address" id="address_search" style="width:282px; display:block;" required>';
while($row = mysql_fetch_array($rs))
{
// Write the value of the full address including unit code, address, city, state, zipcode (which is now in the array $row)
echo '<option value="'. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .'">'
. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .
'</option>';
}
echo '</select>';
// Close the database connection
mysql_close();?>
I already add select tag form directly in php code, but I don't know how to display the whole select box (with options being retrieved data) in .html.
Any help or tutorial? Thanks.
I have solved this issue like this:
First, in the server side-code (php in this case), in "file.php", I have an array with the database elements and I do the following:
$arrayElements = json_encode($arrayElements );
echo $_GET['jsoncallback'] . '(' . $arrayElements . ');';
After that, in the app js code, I use jQuery method $.getJSON() for getting the php array we prepare before. When the function get the server answer, then execute the code inside. Note that the variable "respuestaServer" is the array you have sent from php file, so you can go throw it with a loop and taking its values to your select (if you need to pass variables to your php file and receive them via GET just add the js variables inside the {}, in this example I send the variable datosUsuario and in php I receive it $_GET['usuario']).
var archivoValidacion = "http://example.com/file.php?jsoncallback=?";
var select = document.getElementById("idSelect");
$.getJSON( archivoValidacion, { usuario:datosUsuario ,password:datosPassword})
.done(function(respuestaServer) {
for(var i = 0; i < respuestaServer.length;i++){
var option = document.createElement("option");
var textNode = document.createTextNode(respuestaServer[i]);
option.appendChild(textNode);
select.appendChild(option);
}
})
I hope this can help you. If you have some questions just tweet me #ulisesveraes ;)
it is not clear how you call this code
I suppose you do this with jQuery ajax function
so your code will like something this
$('box-selector').load('b.php');

Javascript Countdown Display in Php Table [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a db table with several fields and i want to make a countdown with the integer value of one of the fields (as minutes). How can i loop and display the countdown of each of those rows in a php table using these values and adding or subtracting time in the process if I need to?
Table.php
$sql="SELECT * FROM List where depName='Admisiones' and personStatus='Espera'";
$result=mysqli_query($con, $sql);
echo "<table border='15' cellpadding='10' cellspacing='3' bordercolor='00FF00'>
<tr>
<th>Turno</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Segundo Apellido</th>
<th>Id Studiante</th>
<th>Status</th>
<th>Multiples Motivos</th>
<th>Tiempo Categoria</th>
<th>Tiempo Estimando</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['listNum'] . "</td>";
echo "<td>" . $row['personName'] . "</td>";
echo "<td>" . $row['personLast'] . "</td>";
echo "<td>" . $row['secondLast'] . "</td>";
echo "<td>" . $row['stuId'] . "</td>";
echo "<td>" . $row['personStatus'] . "</td>";
echo "<td>" . $row['manyMotive'] . "</td>";
echo "<td>" . $row['categoryTime'] . "</td>";
echo "<td>" . $row['estimatedTime']"</td>"; //USE THE CLOCK.PHP TO MAKE A COUNTDOWN FOR EACH ESTIMATED TIME.
//And have the ability to add or substrac time if needed.
echo "</tr>";
}
echo "</table>";
Clock.php
<script>
$('.countdown').each(function(){
var minutes = $(this).data('minutes');
var count = $(this); //countdown
var id = $(this).id;
$(this).countdown({
date : Date.now() + (minutes * 60000),
refresh : 1000
});
setInterval(function(count)
var minuteValue = count.text();
$.ajax({
url : 'TEST.php', //I created to make the test..
type : 'POST',
data : {currentMin : minuteValue, id:id},
success : function(response){
console.log(response);
}
});
});
});
TEST.php
<?php
include 'Connection.php';
$minValue = mysqli_real_escape_string($con, $_POST['minuteValue']);
$ID = mysqli_real_escape_string($con, $_POST['id']);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql ="Update List SET estimatedTime='$minValue' WHERE listNum='$ID'";
mysqli_query($con,$sql);
mysqli_close($con);
?>
OK, here's how I would do it. I would delete clock.php and use something more sophisticated. For example this js plugin:
http://rendro.github.io/countdown/
Download the file and include it in your <head> tag. Make sure you include jquery before that.
Inside your table.php change this line:
echo "<td>" . $row['estimatedTime']"</td>";
to:
echo "<td><div class=\'countdown\' data-minutes=\'{$row['categoryTime']}\' id=\{$row['id']'\'></div></td>";
Basically your html for that countdown field has to look like this (PS:30 is dynamic number coming from 'categoryTime') :
<td><div class="countdown" data-minutes="30" id="16"></div></td>
In footer of that page or in your javascript file include this script:
<script>
$('.countdown').each(function(){
var minutes = $(this).data('minutes');
var id = $(this).id;
$(this).countdown({
date : Date.now() + (minutes * 60000),
refresh : 60000
});
var minuteValue = $(this).text();
setInterval(function(){
$.ajax({
url : 'url/to/php/file', //php file that updates your DB. Take the values from POST VAR.
type : 'POST',
data : {currentMin : minuteValue, id:id},
success : function(response){
console.log(response);
}
});
});
});
</script>
With this, you will loop thru each .countdown element, get its minutes from data-minutes attr, and tell the countdown plugin when timer should expire by adding those minutes to Date.now() value.
EDIT after your comment:
What you are looking for is node.js. That would be perfect for you. But I've updated the code anyways. It is not tested so I don't know if that's gonna work. It should be something like that. The only issue could (MAYBE) be in setting interval for each row in your table.
EDIT2
in php file, run query that updates rows in db
depending on your DB, see if you can get number of rows affected
if affected rows > 0, echo 1, otherwise echo 0
in Firebug (or similar) check the console message to see output of your php or any other errors
This might help you find where the problem lies

Dynamic way to get a list of ticked checkboxes on a php generated page

I've got a webpage that returns a dynamic number of rows from a mysql db, which is output to the webpage via table, of which the first column is a checkbox via the following code:
while($row = mysql_fetch_array($result))
{
$id = $row['circuit_id'];
echo "<tr>";
echo "<td align=\"center\"><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=" . $row['circuit_id'] . "></td>";
if ($row['status_name'] == 'Disconnected') {
echo "<td><font color=\"red\">" . $row['status_name'] . "</font></td>";
} else {
echo "<td>" . $row['status_name'] . "</td>";
};
echo "<td>" . $row['circuit_name'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td><img src=\"images/icons/application_edit.png \"></td>";
echo "<td><img src=\"images/icons/note_add.png \"></td>";
echo "</tr>";
}
echo "</table>";
below this data presentation, I've added a few HTML buttons (one of which is shown below) that will allow the user to do 'mass' updates on the shown data, in this particular case to change the status from one state to another via the checkbox selection.
echo "<table align=\"center\">";
echo "<tr>";
echo "<td>Set status to Migrated for selected records</td><td><img src=\"images/icons/application_edit.png \"></td>";
echo "</tr>";
echo "</table>";
Is there a way to get the list of checkboxes that have been selected without changing everything to forms, and using a simple html based button to submit the request to the server?
I've been looking for an online solution for something like this via javascript but haven't managed to find anything that matches what I need.
Thanks
I've tried to piece together a few bits and pieces to get where I need to be, but am not making much progress at all, here's the current code:
var obj = {}
$('#click').on('click', function() {
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('id');
obj[name] = $(this).is(':checked') ? 1 : 0;
});
$.each(obj, function(key, value) {
alert(key + ' : ' + value);
});
console.log(obj);
});​
how do I get the list of 'true' ie. ticked boxes into a string and update the button with a 'new' url?
Any help is appreciated...
jQuery has the option to select all checkboxes and submit them in the background via AJAX..
jQuery Selectors: http://api.jquery.com/category/selectors/
jQuery AJAX: http://api.jquery.com/jQuery.ajax/
Good luck and hope this helps you!

Categories

Resources