I have my database connected through my code, the column I'm trying to change is called "Sent".
The checkbox is inside a table so it's more organized.
I'm trying to do it so when the user clicks the checkbox the database gets automatically changed to 1 if its checked and to 0 if its unchecked. The variable conn is the connection I've made.
Here's what I have:
<?php
$execItems = $conn->query("SELECT Sent FROM Schools");
while($infoItems = $execItems->fetch_array())
{
echo "<tr><td>
<input type=\"checkbox\"".($infoItems['Sent']?' checked':'')."\" />
</td></tr>";
}
?>
You can try this like below.
<?php
$execItems = $conn->query("SELECT Sent FROM Schools");
while($infoItems = $execItems->fetch_array())
{
$checked = ($infoItems['Sent'] == 1 ? ' checked' : '');
echo "<tr><td>
<input type='checkbox' ".$checked."/>
</td></tr>";
}
?>
Call a function on onChange event
$(document).ready(function(){
var checked;
$(":checkbox").change(function(){
if($(this).attr("checked"))
{
checked=1;
}
else
{
checked=0;
}
//Call Ajax here to update in database
});
});
Related
I am trying to call a function in another page and getting : Uncaught ReferenceError: test is not defined
Two pages are index.php and functions.php
Code Blocks:
Index.php
if($result) {
// Make sure there are some files in there
if($result == '') {
echo '<h1>There are no files in the database</h1>';
}
else {
require './functions.php';
// Print the top of a table
echo '<table class="table-survey" style="margin-left: 50px; width: 1400px;">
<th>
<tr>
<td><b>CSSID</b></td>
<td><b>GROUP</b></td>
<td><b>Class</b></td>
<td><b>Gross Commission Amount</b></td>
<td><b>Name</b></td>
<td><b>Email Address</b></td>
<td><b>Email Received</b></td>
<td><b>Email Sent</b></td>
<td><b>Notes from December</b></td>
<td><b>Not Used For Business</td>
</tr>
</th>';
// Print each file
while ($row = mysql_fetch_assoc($result)) {
echo "
<tr>
<td>{$row['cssid']}</td>
<td>{$row['grp']}</td>
<td>{$row['css_class']}</td>
<td>$" . number_format($row['gross_commission_amount'], 2) . "</td>
<td>{$row['FName']} {$row['LName']}</td>
<td>{$row['email_address']}</td>
<td>{$row['email_received']}</td>
<td>{$row['email_sent']}</td>
<td>{$row['additional_notes']}</td>";
if($delemail == $row) {
echo "<td><form><input value={$row['email_address']} type='radio' name='selected_already' checked='checked'></input></form>/td>";
}
else{
echo "<td><form method='post' action='functions.php'><input value={$row['email_address']} type='radio' name='optradio' onchange='test(this.value);'></input></form></td>";
}
echo "</tr>";
functions.php
function test(){
if (!$link = mysql_connect('localhost', 'dummydata', 'dummydata')) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db('test_table', $link)) {
echo 'Could not select database';
exit;
}
if (isset($_POST['optradio'])) {
$sql = "update email_data set additional_notes_new = case when additional_notes_new is null then 'NOT USED FOR BUSINESS' else concat(additional_notes_new, 'NOT USED FOR BUSINESS') END WHERE email_address = '$delemail' and additional_notes_new NOT LIKE '%NOT USED FOR BUSINESS%'";
$result = mysql_query($sql,$link);
}
return false;
};
All of the POST and other data is working including the SQL statements before the pasted code. As soon as I click the radio button to call the function I get the error. Please excuse the code I am still learning.
you can do this:
onchange='test(this.value);'
to
onClick='$.post("somewhere.php",{posteddata:$(this).val()},function(){ })'
its will $_POST['posteddata'] to somewhere.php
Your test function is php, if you're doing an onchange call it will try and find a function called test in Javascript. If you want to call the test function trough an onclick event without refreshing the page you're looking for something called ajax more info on ajax can be found here : http://www.w3schools.com/php/php_ajax_php.asp
This is my code so far:
require_once 'functions.php';
// makes the connection to the server to get the state button names
$query = "SELECT state FROM state";
$result = $connection->query($query);
if ($result === false) {
// error mssg
echo "<p>Query fout.</p>";
}
// button of the state gets the buttons of the city
if (isset($_POST['state'])) $state = $_POST['state']; {
query = "SELECT city FROM city='$cityid'";
$result = $connection->query($query);
} if ($result === false) {
// geef nette foutmelding
echo "<p>Query fout.</p>";
}
<?php
//gives the result to Submit html
while ($row = $result->fetch_assoc()) {
echo "<input type ='submit' name='provincie' value='".$row['provincie']."'>";
}
$result->free();
?>
</for
I would like to have a form submit button that gives a variable to PHP, depending on that variable, other buttons are created in the same form. So you can select a country and than you can select the cities in that country. I have the first button up and running. I thought I could just use the same submit button with the same variables. Because php would just rewrite the variables if there is a new input. But I think its not that simple, I don't know how to Google this question or that it is even something I should do with PHP instead of JavaScript/jQuery and just let the buttons hide and display and only use the last one to give an input with PHP.
you need to do the query result separately, so there should be two while statements
not the best way but here is one way i would do it:
require_once 'functions.php';
$query = "SELECT state FROM state";
if($query->num_rows > 0){
while($row= $result->fetch_assoc()) {
echo "<input type ='submit' name='provincie' value='".$row['provincie']."' onclick="sendVal(this.value)" >";
}
}
<script type="text/javascript">
function sendVal(item) {
document.cookie="city=" + item + ";";
location.reload();
}
</script>
<?php
if(!is_null($_COOKIE['city'])){
$retrievedcities= "SELECT city FROM city WHERE city ='".$_COOKIE['city']."'";
$con->query($retrievedcities);
while ($row = $result->fetch_assoc()) {
echo "<input type ='submit' name='citybut' value='".$row['city']."'>";
}
unset($_COOKIE['city']);
}
?>
I have a checkbox that dynamically updates a MySQL database when it is checked/unchecked using PHP and Ajax.
I am now trying to pass the users name so that the Ajax script can update the database with the users full name.
I have the name held in a variable called $full_name. I cannot seem to get this working though. Please see the code below:
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function chkit(uid, chk) {
chk=document.getElementById("chk").checked;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: chk, record_id: uid, full_name: user},
success:function(data){
// successful request; do something with the div background color
if(data==1)
{
$("#replace").addClass("checked_div_status").removeClass("replace");//removing first class and adding second class
}
else
{
$("#replace").addClass("replace").removeClass("checked_div_status");//removing second class and adding first class
}
}
});
}
</script>
HTML:
<?php
$record_id = $_GET['veh_id'];
include '../dbconnect.php';
//fetching data from database
$select=mysql_fetch_array(mysql_query("select invoice_checked from vehicle_details where veh_id = '$record_id' "));
?>
<!--The checkbox whose enable to change div his background color and onclick call function to update database-->
<table width=“100%”>
<td id="replace2" class="<?php if($select['invoice_checked']==1) { echo 'checked_div_status2'; } else{ echo 'replace2'; } ?>">
<input name="chk2" type="checkbox" id="chk2" value="1" onclick="chkit2(<?php echo $record_id;?>,'chk2');" <?php if($select['invoice_checked']==1) { echo 'checked'; } else{ echo ''; } ?> />
Invoice Checked
</td>
</table>
Ajax.php:
<?php
mysql_connect("server", "username", "password") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
//here $get variable receive checkbox value true(1) either false(0)
$get=$_GET['chkYesNo'];
//here $get_id variable receive value of current id that you passed
$get_id=$_GET['record_id'];
$get_user=$_GET['full_name'];
if($get=="true")
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='1', check_user='".$get_user."' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
else
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='0', check_user='0' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
?>
Any help would be greatly received.
Thanks,
John
Some debug lession for you. Please, check my comments:
// Do not need to replicate your code, if the same things happens in it.
//instead, use a condition to set your variables, and use these variables later.
if ($get == "true") {
$hpi_registered = 1;
//Escape your variable to avoid sql injection
$checkUser = mysqli_real_escape_string($conn, $_GET["full_name"]);
} else {
$hpi_registered = 0;
$checkUser = 0;
}
//Store your query in a variable, so you can debug / dump it
//Let's dump it, see, what is your query, and try to run in directly in sql.
//Maybe it has syntax error.
$sql = "UPDATE vehicle_details SET"
. " hpi_registered='" . intval($hpi_registered) . "',"
. " check_user='" . $checkUser . "'"
. " WHERE veh_id='" . intval($get_id) . "'";
mysqli_query($conn, $sql);
//What happens, if you run it directly in sql? If this fails, now here is your
//error.
$sql = "SELECT hpi_registered"
. " FROM vehicle_details"
. " WHERE veh_id='" . intval($get_id) . "'";
//Do the same like previous query.
$res = mysqli_query($conn, $sql);
$select = mysqli_fetch_array($res);
echo $select['hpi_registered'];
DO NOT use mysql functions, because they are deprecated. Use mysqli or PDO instead.
Avoid sql injection by escaping your variables.
I'm trying to update the records whereby I found out that I will be doing alot of If-Else Statements for checking. For example, now i have 4 upload buttons inside my form. If the document has been attached, there would not be any upload button. But it is updated to the database, it will show errors because the user did not attached any document. Maybe I'll explain out in my code and will give a clearer picture.
Code for my form:
<form id = "update" action ="update.php">
//Code is repeated for all upload and download buttons just that one is for test, assign, and papers
<?php
if ($Attached== "No")
{
echo "<select name=\"Test\" id=\"Test\">";
echo "<option value=\"No\" selected=\"selected\">No</option>";
echo "<input name=\"Attached[test]\" id=\"Test\" type=\"file\"/>";
echo "</select>";
}
else
{
Button to download the document
$fullpath = "./documents/."$Test";
echo "<input type=\"hidden\" name=\"fullpath\" value=\"$fullpath \"/>";
echo "<input type=\"submit\" name=\"download\" value=\"download\"/>";
}
?>
</form>
Update.php code:
//So if i wish to update into my database sqlite3, i'll need to check as follows:
$test = $_POST['Attached[test]'];
$ID = 1;
$DB = = new PDO('sqlite:database/Test.DB');
If ($test != "")
{
$update = $DB->prepare('update test set test =?, assign =?, papers =?);
$execute = $update-> execute (array($test, $assign, $paper));
}
else if ($test == $test)
{
$update = $DB->prepare('update test set assign =?, papers =? where ID=?);
$execute = $update-> execute (array($assign, $paper));
}
else
{
moveuploaded_files();
}
So my question is how can i shorten my ife-else statement to check if the individual value actually exists in database already and don't update that particular column(s).
Kindly advise thanks
Code for my form:
<form id = "update" action ="update.php">
<?php
if ($Attached== "No")
{
echo "<select name=\"Test\" id=\"Test\">";
echo "<option value=\"No\" selected=\"selected\">No</option>";
echo "<input name=\"Attached[test]\" id=\"Test\" type=\"file\"/>";
echo "</select>";
}
else
{
Button to download the document
echo "<input type=\"submit\" name=\"download\" value=\"download\"/>";
}
?>
</form>
Update.php code:
<?php
$test = $_POST['Attached[test]'];
$DB = new PDO('sqlite:database/Test.DB');
if (!empty($test))
{
$update = $DB->prepare('update test set test =?, assign =?, papers =? WHERE idk = you tell me');
$execute = $update-> execute (array($test, $assign, $paper));
}
else
{
moveuploaded_files();
}
?>
use empty()
you dont need the $test == $test case becuase if the same then it will just update it to be the same.
I have a very simple PHP form, which shows a checkbox, and will store if it is checked or not in a database. This works for the initial inserting, but not for updating. I have tested cases where $saleid equals $pk and it does not enter the if branch to update...why?
<?php
error_reporting(E_ALL);
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
if (isset($_POST["cmd"]))
$cmd = $_POST["cmd"];
else die("Invalid URL");
if (isset($_GET["pk"])) { $pk = $_GET["pk"]; }
$checkfield = "";
$checkboxes = (isset($_POST['checkboxes'])? $_POST['checkboxes'] : array());
if (in_array('field', $checkboxes)) $checkfield = 'checked';
$con = mysqli_connect("localhost","user","", "db");
if (!$con) { echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error(); exit; }
$con->set_charset("utf8");
$getformdata = $con->query("select saleid, field from STATUS where saleid = '$pk'");
$saleid = "";
while ($row = mysqli_fetch_assoc($getformdata)) {
$saleid = $row['saleid'];
$checkfield = $row['field'];
}
if($cmd=="submitinfo") {
if ($saleid == null) {
$statusQuery = "INSERT INTO STATUS VALUES (?, ?)";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("sssssssssssss", $pk, $checkfield);
$statusInfo->execute();
$statusInfo->close();
} else {
print_r($con->error);
}
} else if ($saleid == $pk) {
$blah = "what";
$statusQuery = "UPDATE STATUS SET field = ? WHERE saleid = ?";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("ss", $checkfield, $pk);
$statusInfo->execute();
$statusInfo->close();
} else {
print_r($con->error);
}
}
}
if($cmd=="EditStatusData") {
echo "<form name=\"statusForm\" action=\"test.php?pk=".$pk."\" method=\"post\" enctype=\"multipart/form-data\">
<h1>Editing information for Auction No: ".$pk."</h1>
<input type=\"checkbox\" name=\"checkboxes[]\" value=\"field\" ".$checkfield." />
<label for=\"field\">Test</label>
<br />
<input type=\"hidden\" name=\"cmd\" value=\"submitinfo\" />
<input name=\"Submit\" type=\"submit\" value=\"submit\" />
</form>";
}
?>
well i created a table and ran your code and it works fine for me
the reason why it doesn't "look" like update is working, is because you are reading
$saleid and $checkfield from the database then building an update statement that puts the same two values back into the database
which probably isn't what you are wanting to do
this line here sets $checkfield to 'checked',
if (in_array('field', $checkboxes)) $checkfield = 'checked';
then you set $checkfield from the database (overwriting the value 'checked' )
while ($row = mysqli_fetch_assoc($getformdata)) {
$saleid = $row['saleid'];
$checkfield = $row['field'];
then you write the original value of checkfield back to the database
$statusInfo->bind_param("ss", $checkfield, $pk);
not sure if you can mix GET and POST type requests
maybe change this so that pk is passed back as a hidden field ?
echo "<form name=\"statusForm\" action=\"test.php?pk=".$pk."\" method=\"post\" enctype=\"multipart/form-data\">
eg, sort of like this
echo "<form name=\"statusForm\" action=\"test.php\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"hidden\" name=\"pk\" value=\"".$pk."\">
Here is what your HTML should look like:
<form id="aform" action="thisform.php" method="post">
<input type="checkbox" name="agree" value="yes" />
<input type="hidden" name="secret" value="shhh" />
<input type="submit" value="do it" />
</form>
With the above if you do:
print_r($_POST);
you will get an array that either has [agree] => 'yes' or nothing, depending on if they check the box, so no need to put the array brackets unless you have tons of boxes.
As for the SQL part, I suggest making the column a single integer type, where it can have either a 0 or 1. 0 for unchecked, 1 for checked. For the insert you would do something like:
$check_value = ($_POST['agree'] == 'yes') ? 1 : 0;
$secret_stuff = $_POST['secret'];
mysqli_query("Insert INTO sales_table (secret_column, agree_column)
VALUES ('$secret_stuff', '$check_value')");
That will get your checkbox into the table. To get it out, you should go with:
$results = mysqli_query("SELECT * from sales_table where secret_column = $secret_stuff")
while($row = mysqli_fetch_assoc($results)) {
$checked = ($row['agree_column'] == 1) ? "checked=\"checked\"" : "";
$secret_stuff = $row['secret_column];
}
?>
<form action=blah method=post id=blah>
<input type="checkbox" name="agree" value="yes" <?php echo $checked;?> />
</form>
Sorry, lost steam at the end. But that covers the front end and back end. Use a 1/0 switch, and just set some variable like $checked to the "checked='checked'" if it's a 1.
You're not setting the $pk variable unless isset($_GET["pk"]), yet you're still using it later in the query. This isn't a good idea, since depending on other circumstances, this can lead to bugs. What you want your logic to look like is this:
if pk is not set in form
insert new record
deal with error if insert failed
else
update existing record
check update count and deal with error if 0 records were updated
(perhaps by doing an insert of the missing record)
end
Just as a side note, it looks like the mysql REPLACE function would come in handy for you.
Also, when a checkbox is not checked, the value can be a tricky thing. I have written a function that sets the value to one, if the posted value is set, and zero if not...
function checkbox_value($name) {
return (isset($_POST[$name]) ? 1 : 0);
}
You can run your posted checkbox value throught that query and always get a one or a zero.