connection table for overcoming the checkbox problem - php

i have a php form with text box,radiobutton and checkboxes.I have connected it to the databse , the values are getting stored into the database except the checkbox values.I want to enter all the checkbox values into the database.I want an backend such that it links to two tables.the text box and the radio button values are to be stored in the first table and the id's of the selected checkbox values in the other table.

u can store only that value in database which is checked, but you can not store all value of check box with same name attribute, because by checking that checkbox, that value is proceed to next page via POST/GET
but if u want all value of check box ( multiple check box) then use name array like below
<form action="checkbox.php" method="post">
<input type="checkbox" name="checkbox[]" value="a">
<input type="checkbox" name="checkbox[]" value="b">
<input type="checkbox" name="checkbox[]" value="c">
<input type="checkbox" name="checkbox[]" value="d">
<br>
<br>
<input type="submit" name="Submit" value="Submit">
</form>
<?
/* and in your checkbox.php you do this: */
if(isset($_POST['Submit']))
{
for ($i=0; $i<count($_POST['checkbox']);$i++) {
echo "<br />value $i = ".$_POST['checkbox'][$i];
}
}
?>

a connection table can be created (i.e A single php page connection is given to two tables of the same database)the code ia as follows. this code should be given as backend to the php page.
$dbhost = "localhost:3306"; // usually is localhost, but if not sure, check with your hosting company, if you are with webune leave as localhost
$dbuser = "root"; // change to your database password
$dbpass = "mysql"; // change to your database password
$dbname = "probe_config"; // provide your database name
$db_table = "mapping"; // leave this as is
$conn = mysql_connect("$dbhost", "$dbuser", "$dbpass");
$select = mysql_select_db("$dbname");
//selecting the urls
$selected = $_POST['urlSelect'];
if (count($selected) > 0)
{
for ($i=0;$i<count($selected);$i++) {
echo "$selected[$i] <br />";
}
}
$timeout=$_POST['timeout'] ;
$wait=$_POST['wait'];
$clearcache=$_POST['clearcache'];
$name=$_POST['name'];
$replication=$_POST['replication'];
//inserting into the databse
$query = "INSERT INTO webmeasurementsuite (wait, timeout, clearcache, name, replication)
values ($wait, $timeout, '$clearcache', '$name', $replication)";
if (!mysql_query($query,$conn))
{
die('Error: ' . mysql_error());
}
else
{
echo "1 record added to WMS";
$query = "SELECT wms_id FROM webmeasurementsuite ORDER BY wms_id DESC LIMIT 1";
if (!($result=mysql_query($query,$conn)))
{
die('Error: ' . mysql_error());
}
else
{
$row = mysql_fetch_assoc($result);
$id=$row['wms_id'];
$selected = $_POST['urlSelect'];
if (count($selected) > 0)
{
for ($i=0;$i<count($selected);$i++) {
$urlentry=$urlentry.", ";
if($i==0)
{
$urlentry="";
$j++;
}
$urlentry=$urlentry .$selected[$i];
}
}
echo $urlentry;
echo '<br />id='.$id;
//insert for the second table
$query= "INSERT INTO mapping(wms_Id, wm_Id) values ($id, '$urlentry')";
if (!mysql_query($query,$conn))
{
die('Error: ' . mysql_error());
}
else
{
echo "Mapping Done";
}
}
}
mysql_close($conn);
?>

Related

mysql updating data only where post contains data

i have a simple form in html where user selects and ID from the table on the website (required data) and then he can / or not change 2 fields. First is a dropdown list of 2 values (strings), and the second is number of open spots!
So if a user leaves both fields empty and click send by mistake nothing should happen. If a user only changes one of the fields only that one should change!
I have checked every forum and almost all posts in here and i still cannot get it to work.
<form action="viv_settings_tecaji.php" method="post">
Datum termina (izberi ID):
<input type="number" name="ID" required><br><br>
<!--Sprememba tega datuma (če ne želiš spremenit pusti prazno):
<input type="date" name="nov_datum"><br><br>-->
Sprememba statusa (če želiš da ostane isto vpiši trenutni status!:
<select name="STATUS">
<option></option>
<option value="zaprt">Zaprt</option>
<option value="odprt">Odprt</option>
</select><br><br>
Sprememba števila odprtih mest
<input type="number" name="st_odprtih_mest"><br><br>
<input type="submit">
</form><br>
php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "viverius_education";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$update_status = $_POST['STATUS'];
$update_st_odprtih_mest = $_POST['st_odprtih_mest'];
$update_ID = $_POST['ID'];
if (empty($update_status) AND empty($update_status)){
header('Location: viv_settings_tecaji_main.php'); exit;
}
else{
$sql = "UPDATE razpisani_tecaji
SET
STATUS = IF('$update_status'='',STATUS,'$update_status'),
ST_ODPRTIH_MEST = IF('$update_st_odprtih_mest'='',STATUS,'$update_st_odprtih_mest'),
WHERE ID_TECAJA = $update_ID";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
header('Location: viv_settings_tecaji_main.php'); exit;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}$conn->close();
?>
A decent form example would be like the following
<form action='' method='post'>
<input type='text' name='field1' required>
<select name='fieldSelect'>
<option value='value1'>Value1</option>
<option value='value2'>Value2</option>
</select>
<input type='submit' name='send'>
</form>
then the PHP would be like
<?php
if(isset($_POST['send'] && (!empty($_POST['field1']) || !empty($_POST['fieldSelect']))){
$field1 = $_POST['field1'];
$fieldSelect = $_POST['fieldSelect'];
//YOUR SQL CODE
} else {
echo "Please Insert Some Data";
}
?>
In brief:
Give your Submit button a name
Check if the submit button is clicked or not by if(isset($_POST['submit-button-name'])){}
define your form's $_POST variables with names.
Continue with SQL.
There are a couple of ways you can avoid inserting "empty" records in your database. It depends if you want to do it in the client-side (before the form submits) or server-side (when the form is submitted to the server).
I'll show you how to do it server-side, since you posted your php script.
In viv_settings_tecaji.php
...
$update_status = $_POST['STATUS'];
$update_st_odprtih_mest = $_POST['st_odprtih_mest'];
$update_ID = $_POST['ID'];
if($update_status == "" || $update_st_odprtih_mest == "" || $update_ID == ""){
die("One of the form fields was empty");
}
...
That would kill your script if any of the form fields was empty. Potentially, you could check for null or use PHP's empty() function.
I hope this helps!
So i manege to get it to work using the following code. So for the part if user leaves both field empty i will put together a script for at least 1 to be required.
$sql = "UPDATE razpisani_tecaji
SET
STATUS = IF(LENGTH('$update_status')=0, STATUS, '$update_status'),
ST_ODPRTIH_MEST = IF(LENGTH('$update_st_odprtih_mest')=0, ST_ODPRTIH_MEST, '$update_st_odprtih_mest')
WHERE ID_TECAJA = $update_ID";

How do I get a value from dynamically created form in a dropdown menu using PHP?

I'm trying to build an application that will direct a user to a different website based upon what zip code they enter. In order to narrow it down, in some instances, a user may need to select from a dynamically created drop down list of street names. The application uses PHP and a mySQL database. The issue that I'm having is detailed in the code comments under the PHP section. If possible, please provide a PHP driven solution. If jQuery, Javascript, AJAX, etc. are the only alternatives, please give me some example of how I would implement it with this example. Thanks!
Here's a snippet of the HTML:
<div id="mybox">
<form method="post">
<input type="text" name="zipcode">
<input type="submit" value="Enter Zip Code" name="submitzip">
</form>
</div>
Here is the PHP called by clicking the Submit button:
<?php
if (isset($_POST['submitzip'])) {
ZipLookup(); }
function ZipLookup() {
$zipcode = $_POST["zipcode"];
$zipcode = trim($zipcode);
if (strlen($zipcode) != 5) {
echo ("<strong>Please enter a valid five digit Zip Code.</strong>");
}
else {
$servername = "ip here";
$username = "username here";
$password = "password here";
$dbname = "dbname here";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ZipCode, StreetName, URL FROM db table here WHERE ZipCode ='$zipcode'";
$result = $conn->query($sql);
if ($result->num_rows > 1) {
echo '<hr><p><strong>We service more than one area in ' .$zipcode. '. Please select your street name.</strong></p>';
echo '<form method="post">';
echo '<select name="streetname">';
while($row = $result->fetch_assoc()) {
echo '<option value="' . $row["URL"] . '">' . $row["StreetName"] . '</option>';
}
echo '</select> <input type="submit" value="Submit" name="submitname"> </form>';
echo '<p>If your street name is not listed, please contact us.</p>';
// THIS IS WHERE I HAVE PROBLEMS... Values from dropdown don't appear to be stored. When running var_dump, PHP exports the array from the first button. Clicking the dynamic submit button just reloads the page.
if (isset($_POST['submitname'])) {
$url = $_POST["streetname"];
wp_redirect($url); }
}
elseif ($result->num_rows == 1) {
while($row = $result->fetch_assoc()) {
$url = $row["URL"];
wp_redirect($url);}
}
else {
echo '<strong>We do not provide service to this area.</strong>';
$conn->close();
}
}
}
?>
The second form is posting back to this page and it doesn't appear the zip code is being passed with the second form

retrieving results from mySQL using options from selected check boxes

I have a simple form in PHP, having 4 check boxes. The user can select 0-4 number of checkboxes and based on their selection the results should differ.
Basically the four checkboxes represents the four campuses of a university- Campus A,B,C,D. and suppose if the user select 2 campuses say A and C. then I want to query the database based on the selection and retrieve the courses corresponding to those two campuses A and C. If the user selects only one campus then I want to retrieve courses in that single campus.
On mySQL, I have a Location table with the following schema (ID,Campus Name, City, State) with ID being the primary key. Also I have a course table with schema as Course(ID,CourseName,LocationID,Seatsleft). ID is the primary key and LocationID is the foreign key, which references ID of Location table.
My PHP code is as follows:
Here is the updated version of my code.
PHP form check box selecting different campuses
<body>
<?php
require 'connection.php';
if(isset($_POST['formSubmit']))
{
$aCampus = $_POST['campus'];
if(empty($aCampus))
{
echo("<p>You didn't select any campus.</p>\n");
}
else
{
$N = count($aCampus);
echo("<p>You selected $N campus(s): ");
for($i=0; $i < $N; $i++)
{
echo($aCampus[$i] . " ");
}
echo("</p>");
}
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
$where="1";
if(!empty($_POST['campus'])){
foreach ($_POST['campus'] as $campus){
$where=" LocationID='". $campus."'";
}
}
//$query = "SELECT `Name` FROM `course` WHERE LocationID=1";
$query="SELECT `Name` FROM `course` WHERE 1 AND (".$where.")";
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$coursename =$query_row['Name'];
echo $coursename. '<br/>';
}
} else {
echo mysql_error();
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
Which campus courses do you want to get access to?<br/>
<input type="checkbox" name="campus[]" value=1 />Campus A<br />
<input type="checkbox" name="campus[]" value=2 />Campus B<br />
<input type="checkbox" name="campus[]" value=3 />Campus C<br />
<input type="checkbox" name="campus[]" value=4 />Campus D
</p>
<input type="submit" name="formSubmit" value="Submit" />
</form>
</body>
</html>
My question is how do I take options from my PHP form and query the database to retrieve courses from the selected campuses only?
Please try with following simple query creator logic.
$whereArr =Array();
$whereArr[] = 1;
if(!empty($_POST['campus'])){
foreach ($_POST['campus'] as $campus){
$whereArr[]=" LocationID LIKE ',". $campus.",'";
}
}
$query="SELECT `Name` FROM `course` WHERE 1 AND(".implode(" OR ",$whereArr)." )";
Above code will work for following record:
289,"Math","2,3,",67
In this instance I would store the campuses as a comma delimited string in the database. Then you can use the FIND_IN_SET() function in mySQL to query based on that
for instance
a record for the course
203,"Biology","1,2,4",34
then you can
SELECT * FROM course WHERE FIND_IN_SET(4,locationid)
which will give you all of the records that have 4 in the "set"
Something like this :
$validoptions = array('A','B','C','D');
$allvalid = true;
foreach ($_POST['campus'] as $campus){
if (!in_array($campus,$validoptions)) $allvalid = false;
}
if (!$allvalid) {
echo 'Wrong campuses selected. Try again.';
exit;
}
$query = 'SELECT * FROM `Courses` WHERE ';
$query .= 'LocationID = \''.implode('\' OR LocationID = \'',$campuses).'\'';
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) die('Could not connect: ' . mysql_error());
mysql_select_db("databasename");
$res = mysql_query($query);
$data = array();
if ($res && mysql_num_rows()) {
$data = array();
while($d = mysql_fetch_array($res)) {
$data[] = $d;
}
}
if (count($data) > 0) {
echo 'No courses found !';
}else {
echo 'Courses found : ';
print_r($data);
}

Using Multiple Submit Buttons to Delete and Modify

I have an issue where I need to be able to use check boxes in order to delete and modify data in a mysql database.
What is the most efficient way of being able to use multiple submit buttons to either insert data based on what the user types into the text boxes, delete based on the check boxes selected, and modify based on the check boxes selected.
Here is the code I have so far:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Auto,Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
</table>
<tr><td><input type="submit" name="create" value="Add"/></td></tr>
<tr><td><input type="submit" name="delete" value="Delete"/></td></tr>
<tr><td><input type="submit" name="modify" value="Modify"/></td></tr>
</table>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info['Auto'];
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
if (isset($_POST['create'])) {
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
}
elseif (isset($_POST['delete'])) {
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql_delete = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result_delete = mysql_query($sql_delete);
}
if ($result_delete) {
echo $result_delete;
}
else {
echo "fail";
}
}
elseif (isset($_POST['modify'])) {
header('Location: modify_ticket.php');
}
mysql_close($conn);
?>
</form>
</BODY>
</HTML>
Insert.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
#header( 'Location: ticket_history.php' );
?>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result = mysql_query($sql);
}
header( 'Location: ticket_history.php' );
?>
Any help is appreciated!
Thank you!
Another way to do it is your submit button's have the same name,
So:
<input type="submit" name="submit" value="Delete" />
<input type="submit" name="submit" value="Edit" />
PHP:
switch(strtolower($_POST['submit'])){
case "delete":
// delete logic
break;
case "edit":
// edit logic
break;
}
I would take the insert and delete code and put it on top of the main file instead of having them into files. the simplest way would be to submit the form to itself and based on the submit button clicked run the code block
if($_POST['create']){
// insert code
}
elseif($_POST['delete']){
// delete code
}
continue the logic of if/else/elseif to handle all the cases. This strikes me as the simplest way to get done what you want to do.
Edit:
Not sure but seems like you are handling the $_POST['create'] etc after the HTML code. You should always do that sort of processing BEFORE the html rendering and even before the query to get the records you want to display, this way your get query will always bring up to date results.
When you use multiple submit buttons, you can use PHP to determine which button was pressed. Based on this, you can have your application do different things with the data.
It's not clear what you want to accomplish with multiple buttons. Perhaps you could give more detail.
[Edit]
Looking over your code in detail, it is plain to see that it is quickly becoming a maintenance nightmare. Even if your app is tiny and you don't want to code use MVC pattern, you I still recommend using classes and separating presentation from application logic and from data access. Then it's much easier to maintain the application(fix bugs) and make changes.
If you are building anything more than a trivial script, I recommend using one of the excellent PHP frameworks:
http://framework.zend.com/
http://www.symfony-project.org/
http://codeigniter.com/
http://cakephp.org/
and many more: http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#PHP
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Auto,Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
if (isset($_POST['create'])) {
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
}
elseif (isset($_POST['delete'])) {
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql_delete = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result_delete = mysql_query($sql_delete);
}
if ($result_delete) {
echo $result_delete;
}
else {
echo "fail";
}
}
elseif (isset($_POST['modify'])) {
header('Location: modify_ticket.php');
}
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
</table>
<tr><td><input type="submit" name="create" value="Add"/></td></tr>
<tr><td><input type="submit" name="delete" value="Delete"/></td></tr>
<tr><td><input type="submit" name="modify" value="Modify"/></td></tr>
</table>
</table>
I modified the code a little bit and THIS WILL WORK; however, it only works on the SECOND click.
When I select something and click DELETE, it will not delete, but when I do it again it will
Why is this? Thoughts?
Take the code for deletion and insertion above the select, so that the desired deletion of updation is done before you show the data.

mysql not updating from php form

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.

Categories