update database with checkbox - php

My database table has 2 fields: id (int) and state (enum -> 0,1).
What I need to do is to update my database (my state field) with the state of a checkbox (0 for empty, 1 for checked).
To show each of the fields in my database, I use a loop:
Loop:
<?php
foreach ( $posts_array as $module )
{
?>
<h2><?php echo $module->titre; ?></h2>
<input type="checkbox" name="chkbx_<?php echo $module->id; ?>"> id="chkbx_<?php echo $module->id; ?>" class="onoffswitch-checkbox"> On/Off <br />
<?php
}
?>
My update file:
foreach ($_GET['onoffswitch-checkbox'] as $id => $state)
{
// $_GET['onoffswitch-checkbox'] = class for all my checkboxed
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;
}
Where I need help is the AJAX part of the code. I'm guessing it looks something like this, but it doesn't seem to work:
AJAX
$(document).ready(function() {
$("onoffswitch-checkbox").click(function() {
var id = $(this).attr('id');
$("#state_span").load("module_update.php?"+id);
}
}
I've been looking around, seen a few examples where the we could do so with a submit button, but none where the information is automatically recorded when clicking the checkbox.

Try this:
AJAX
$(document).ready(function() {
$(".onoffswitch-checkbox").click(function() {
var id = this.id; //changed here also, just because jQuery is not needed here
var state = this.checked ? 1 : 0;
$("#state_span").load("module_update.php?id="+id+"&state="+state);
}
}
Changed 3 things:
added a dot in $("onoffswitch-checkbox") so its now $(".onoffswitch-checkbox")
added id= after module_update.php? and before id value.
since you need state also I added that also with a & to separate the values for $_GET in php to separate them
PHP
I don't know what you mean with $_GET['onoffswitch-checkbox'] in the php, maybe a mistake? My suggestion does not need it anyway, neither does your mysql query.
Since you will be only clicking one at a time I see no need for the foreach loop in php, so you could do this:
$id = $_GET['id'];
$state= $_GET['state'];
// $_GET['onoffswitch-checkbox'] ?? I don't think you need this...
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;

Related

Creating Link For User To Delete Row

I'd like to ask two things for this particular user ability. The first is how to delete a row upon user clicking a button. The second is....would this be a good idea? How can I create a safe environment for someone to do this. This is what I've got so far :
<?php
include_once "db_conx.php";
if($_POST['wall'] == "post") {
//open if($_POST['wall'] == "post")
$id = mysqli_real_escape_string($db_conx, trim($_POST['id1']));
if($id == " ")
{
exit();
}
else
$sql = "SELECT FROM courseprogress WHERE userid='$id' LIMIT 1";
$results = mysqli_query($db_conx, $sql);
$sidebar = mysqli_num_rows($results);
if($sidebar > 0) {
//close if($sidebar > 0)
while($row = mysqli_fetch_assoc($results))
{
$sql = mysqli_query("DELETE FROM courseprogress WHERE userid='$id'");
$results = mysqli_query($db_conx, $sql);
}
//close if($sidebar > 0)
}
else
{
echo 'Already Complete!';
echo "<pre>";
var_dump($sql);
echo "</pre><br>";
}
//close if($_POST['wall'] == "post")
}
?>
Right now I'm in the process of dumping out variables, but can't seem to get my id variable right.
The idea is to "start over" in a sense. The table holds the user progression and settings. Once they've decided they need to start over they will be allowed to do so by simply deleting the row. When the begin again the row will be created again.
A little more information:
The small form script I was trying to use is:
<div class="userInfoContain"><div class="positionRight"><div id="form"> <form><div class="submit"><input type="hidden" id="id" value="'.$id.'" /><input type="submit" name="button" id="button" value="Start Over" onclick="return false" onmousedown="javascript:wall();"/><img src="images/loading.gif" alt="" width="15" height="15" id="loadingstart" /></div></form></div></div></div>
<script type="text/javascript">
$(document).ready(function(){
$('#loadingstart').hide();
});
function wall(){
$('#loadingstart').show();
var id = $('#id').val();
var URL = "./includes/start-over-user.php"; /////post.php will be equal the variable "comment"
$.post(URL,{wall:"post",id1:id},function(data){//parameter wall will be equal "post", name1 will be equal to the var "name" and comment1 will be equal to the var "comment"
$("#result").prepend(data).show();// the result will be placed above the the #result div
$('#loadingstart').hide();
});
}
</script>
1) Safely allow user to delete: The safest way is to not allow delete permissions on the MySQL user that is being used by the website. A method called soft delete is much safer for deleting rows in MySQL tables. This involves adding a column named "is_deleted" to the table where you are making this update. When is_deleted is set to 0, allow the row to act normally. When a user sets is_deleted to 1, it should act as if it doesn't exist. In this example, I am assuming you have set $is_deleted to the column is_deleted in your table:
if($is_deleted == '1')
{
// Don't display
}
else
{
// Display
}
2) How to implement: The best way to do this is with:
UPDATE tablename SET is_deleted = '1' WHERE id = '".$id."'
which should be executed through AJAX command or a link that will execute the MySQL query.
to delete I advice you to use ajax , it's perfect and you can have more control on this action
the other Problem i need more explanation i didn't understand you good

Displaying output of php within jquery colorbox ... getting undefined index error

I hope someone can help me, I have created a simple html form with drop down menu's, the drop down menus are populated from a mysql data base, the user must select from two drop downs and this will then display the data ( both selections make the sql query)
This all works correctly within the HTML however I am trying to jazz it up a bit and have the output display within a jquery colorbox (popup).
I am not sure how to format the syntax for the jquery function .. this is what I have so far
<script>
$(document).ready(function(){
$(".inline").colorbox({inline:true, width:"50%"});
$("input#formsubmit").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
return url;
}, innerWidth:920, innerHeight:"86%", iframe:true});
});
</script>
This correctly launches the colorbox pop up and fires the php "action" from my form but the $_POST attributes are not sent across and I just get an unidentified index error from mysql.
Can some one please help me ?
Im sure its something simple, but I cant figure it out.
Many thanks
Adding PHP ...
<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("verify") or die(mysql_error());
$result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$_POST[product]' AND CustomerType = '$_POST[customer]'")
or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['Entitlement'] ;
echo "<br />";
}
?>
Can you please tell how may this code works with you :)
<?php $result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$_POST[product]' AND CustomerType = '$_POST[customer]'");?>
You have 2 error the first one the single quote beside the index in your post variable and must be like this $_POST['product'],$_POST['customer'] then the second error is that you must encapsulate your variable inside the string as following {$_POST['product']},{$_POST['customer']}
Try these work around then tell me the result :)
try this
<?php
// Checking for valid post data
if (isset($_POST['product']) && isset($_POST['customer']) && !empty($_POST['product']) && !empty($_POST['customer'])) {
// Cleaning post data
$proudct = mysql_escape_string($_POST['product']);
$customer = mysql_escape_string($_POST['customer']);
// db connnection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("verify") or die(mysql_error());
// Quering
$result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$proudct' AND CustomerType = '$customer'") or die(mysql_error());
// Printing result
while ($row = mysql_fetch_array($result)) {
echo $row['Entitlement'];
echo "<br />";
}
}
?>

Update value in MySQL via AJAX/PHP when a dynamically created checkbox is clicked?

I am creating an admin panel for a project that I am working on. It will list a bunch of entries in a table and each row will have a checkbox in it. This checkbox will be used to activate an entry to be displayed on the website.
I am setting the id and name of the checkbox with data from the MySQL database. For example..
<input type="checkbox" class="active" name="active<?php echo $id; ?>" id="active<?php echo $id; ?>" <?php if ($active == 1): ?>checked="checked"<?php endif; ?> value="<?php echo $id; ?>">
For the entry with ID of 5 it will look like this..
<input type="checkbox" class="active" name="active5" id="active5" checked="checked" value="5">
I need to set this up so that when you check a box or uncheck it that it updates the "active" value in the database. How do I grab the value of each checkbox, when clicked, and send that value to the MySQL database. I can do this easily if I know the checkboxes name beforehand, but since the name is partly generated from the database I'm not sure how to write the code to determine which entry gets the active value.
Here is my jQuery..
$("input.active").click(function() {
// store the values from the form checkbox box, then send via ajax below
var check_active = $(this).is(':checked') ? 1 : 0;
var check_id = $(this).attr('value');
console.log(check_active);
console.log(check_id);
$.ajax({
type: "POST",
url: "http://nowfoods.marketspacecom.com/nextstep/ajax.php",
data: {id: check_id, active: check_active},
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return true;
});
Here is the PHP..
<?php
include("dbinfo.inc.php");
mysql_connect($server,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// CLIENT INFORMATION
$active = mysql_real_escape_string($_POST['active']);
$id = mysql_real_escape_string($_POST['id']);
$addEntry = "UPDATE entries SET active = '$active' WHERE id = '$id'";
mysql_query($addEntry) or die(mysql_error());
mysql_close();
?>
You could add a class to the input and set the value to the id instead:
<input class="active" type="checkbox" name="active5" id="active5" value="5" checked="checked">
Then, change your jQuery:
$("input.active").click(function() {
// store the values from the form checkbox box, then send via ajax below
var check_active = $(this).is(':checked') ? 1 : 0;
var check_id = $(this).attr('value');
$.ajax({
type: "POST",
url: "http://nowfoods.marketspacecom.com/nextstep/ajax.php",
data: {id: check_id, active: check_active}
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return true;
});
As for PHP:
<?php
include("dbinfo.inc.php");
mysql_connect($server,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// CLIENT INFORMATION
$active = mysql_real_escape_string($_POST['active']);
$id = mysql_real_escape_string($_POST['id']);
// WHERE id=16 is just for testing purposes. Need to dynamically find which checkbox was checked and use that info to tell the query which ID to update.
$addEntry = "UPDATE entries SET active = '$active' WHERE id = '$id'";
mysql_query($addEntry) or die(mysql_error());
mysql_close();
?>
This should be what you're looking for. There may be some minor syntax issues, because I'm writing this off the top of my head, but I hope you get the general idea. :-)
This is wrong:
var active = $('#active').attr('value');
You need to check the clicked element and you have to check whether it is checked or not (the value doesn't really matter that much unless you use it to pass the ID):
var active = $(this).is(':checked'); // the checkbox is checked (boolean)
You can set it to an integer value like:
var active = $(this).is(':checked') ? 1 : 0;
Which is short for:
if ($(this).is(':checked')) {
var active = 1;
} else {
var active = 0;
}
And in php you need process you user input correctly:
$active = (int) $_POST['active'];
Edit: It seems you have a space that should not be there in your edited code, does it work when you set:
...
data: {"active=": check_active, "id": check_id},
...
Also, as both values are integers / should be integers, there is no real use escaping them for the database using a string function, you should test for integers or at the very least cast them to integers:
// CLIENT INFORMATION
$active = (int) $_POST['active'];
$id = (int) $_POST['id'];

submit one or another query

I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app.
I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present,
the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are
obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my
understanding (and guess-ology).
I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php,
etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other.
Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up)
cheers, s
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
and:
<form id="invoiceData" method="post" action="/html/form.php">
When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this:
<form
id="invoiceData"
method="post"
action="/html/form.php?ID=<?php echo $_GET['ID']; ?>"
>
This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure.
Hope this helps!
$_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to
<form id="invoiceData" method="post" action="/html/form.php?ID=12">
Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.

How to check a check box if it's value is in DATABASE. PHP

I have inserted some check box values in mysql database using PHP
And in the below image i have fetch the values:
Now i need the o/p like the below image: The values which i inserted in the database should be checked
Hope now its clear.
Thanks in advance..
You should have a table of available options (in this case, something like a cities table), and then a user-to-cities look-up table. Then you can loop over the cities, but also fetch which cities the user has checked.
A sample, without knowing your database structure, would be as follows:
$uid = $_SESSION['user']['id']; // your logged in user's ID
$cities = array();
// get an array of cities
$sql = "SELECT id, name FROM cities";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$cities[$row->id] = $row->name;
}
// get an array of cities user has checked
$sql = "SELECT DISTINCT city_id FROM users_cities WHERE user_id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->city_id;
}
// this would be templated in a real world situation
foreach ($cities as $id => $name) {
$checked = "";
// check box if user has selected this city
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="city[]" value="'.$id.'" '.$checked.'/>';
}
If I understand you question properly, the obvious and simplest approach is that you need to fetch records from database and when producing HTML [in a loop ot something similar] check if that value exists in array to results. You haven't given us any examples of your DB structure or code, so you must figure it our yourself how to do it.
Usually, you insert the values into the database. After inserting, you should have access to the same values again. It's not clear how you set up your script, so let's assume you redirect to another script.
What you need to do is retrieve the values for the checkboxes from your database again. Then you know which are selected. This can be used to determine if your checkbox need to be checked or not.
Note:
I assume here that the result of your query is an array with
the selected Ids as a value.
I assume here that your fields are stored in the result of
some query and is basically an array
with Field Id as key and Field Name
as Value.
E.g., something like this:
<?php
// Retrieve values from database.
$resultArray = ... some code ... ;
?>
<?php foreach ($field_types as $field_name => $field_value): ?>
<input type="checkbox" name="<?php echo $field_name; ?>" value="<?php echo $field_value ?>" <?php if (in_array($field_name, $resultArray)) { echo 'checked'; }/>
<?php endforeach; ?>
This results in a checkbox which is checked, if the field_name is inside the result array (with your already checked results). Otherwise they're just rendered as unchecked checkboxes. Hope this is clear enough.

Categories