Endless If-Else statements - php

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.

Related

How to do a database check and depending on results either update or insert (keep getting a HTTP 500 error)

I am trying to build a way to do an input field update check that looks to see if a user input field is empty or not. And then depending on answer if it is empty or not do more checks. So for example if the input field is empty I want it to be ignored so rest of code runs, And if there is a value inside of the input field some more checks will be done to check if it is inside the database or not, and if it is not inside the database then it must be inserted into the database, and if it is already in then just update that field.
The table is a relational one to a main table where inf_id is the main table and userid is the relational one i am working in
So I have tried to do it in different way however I keep running into problems and each time I make a mistake or something that doesn't work I get a HTTP 500 error page saying it can't be reached. I have also tried to do a change the name in the input to other things to see if that effects and different layouts or such neither works I feel like it is something small that I am missing out on
also tired but i may have done it incorrectly since I never really used this before
IF EXISTS (SELECT count(*) FROM `table` WHERE inf_id = $infid)
BEGIN UPDATE GOES HERE END ELSE BEGIN INSERT GOES HERE END
This is my Code in the form to check the database has inputs, if it doesn't it creates a blank input. However If there is values in the database then it will echo it out
$vId = $_GET['i']; //this is the users unique ID that is send in the query string for testing purpose
if (mysqli_num_rows($rs_username) == 0 ){
echo '<input type="text" name="currentusername[]" class="currentusername" placeholder="Current Bikes" >';
} else {
while ($rs_bike_rows = mysqli_fetch_assoc($rs_bikes)) {
echo '<input type="text" name="currentusername[]" class="currentusername" value="' . $row['currentusername'] . '">';
echo '<input type="hidden" name="userid[]" value="' . $row['userid'] . '">';
echo '<button type="button" onclick="return deleteFromDbBike('. $rs_bike_rows['oid'] .', '. $vId .');">Delete</button>';
}
}
This is to sanitize the inputs that the users inputs in a process file
if (isset($_POST['currentusername']) && $_POST['currentusername'] !== '') {
$currentusername = $_POST['currentusername'];
$allusername = '';
foreach ($vcurrentbike as $users) {
$allusername .= $users. ' ';
}
if (filter_var($allusername , FILTER_SANITIZE_STRING) === null) {
$vValidation++;
}
} else {
$currentusername= '';
}
later on in the process file to then check the input value and update/insert it
$user = $_POST['userid'];
if ($currentusername != '') {
for ($i = 0; $i < count($user); $i++) {
$userid = $bike[$i];
$valueuser = $currentusername[$i];
$sqlcheck = "Select `inf_id` FROM usertable WHERE inf_id = $vId";
$resultcheck = mysqli_query($conn,$sqlcheck);
if (mysqli_num_rows($resultcheck) >= 1) {
$stmt = $conn->prepare("UPDATE usertable SET currentusername = ? WHERE inf_id = ? and userid = ?");
$stmt->bind_param("sii", $currentperson, $infid, $ownedid);
$currentperson = $valueuser ;
$infid = $vid;
$ownedid = $userid;
$stmt->execute();
//the update code works (tried and tested) just using
//exit to see where the code goes.
exit('1');
} else {
//this is where the insert value would be however I can
//never get it to echo 0 when it exits; instead i just get a HTTP 500;
exit('0');
}
};
} else {
exit('fails');
}
In the End I want it to be able to check if the user has inputted values and then depending on if they have or have not then either insert or update it. and if the user hasn't just ignore it. and move onto the next field
Edit
it basically has 2 levels to this statement
Level 1:
1.1) if user input is empty then ignore it completely.
1.2) if user input has a value check it against the database
Level 2:
2.1) if the value exists in database then update the values
2.2) if the values don't exists then insert it into the database.
Error I'm running into is that if the value is not in the database to begin with it will create an empty input field.
Now when a user then adds text to the empty field it wants to update it but it doesn't exists. so through out errors at me as there is nothing to update
The States of the input field can be :
1) empty with no value at all
2) Has a value now added so it is not in the db
3) has a value from initial submission of form that is in db
EDIT 2: add more button
<button type="button" onclick="addMoreRows('user')"> Add More Current Usernames</button>
<div id="currentuser"></div>
var itemTypes = {
user:{
maxLimit: 4,
currentCount: 1,
selector: '#currentuser',
newElement: '<div class="moreusersadd"><input type="text" name="currentusernameadd[]" class="currentusernameadd" placeholder="Current Bikes" ><button class="delete" onclick="deleteRow(this, \'user\')">Delete</button></div>'
}
}
function addMoreRows(type){
var item = itemTypes[type];
if (item.currentCount < item.maxLimit) {
item.currentCount++;
$(item.selector).append(item.newElement);
}
else {
alert('You Have Reached the limits')
}
}
function deleteRow(event, type){
$(event).parent('div').remove();
itemTypes[type].currentCount--;
};
I think this is kind of what you want.
I used my own users table as an example but you should be able to just change the queries to your own tables and columns.
If you have any issue with it just show us your full table structure and I can update it.
<?php
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
}
echo "<tr>";
echo "<td><input type='text' name='username' placeholder='Username'></td>";
echo "<td><input type='text' name='password' placeholder='Password'></td>";
echo "</tr>";
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
for($i=1; $i<=$count; $i++){
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i])){
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
}
}
if(isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
}
?>
Edit
So this now has the added header to refresh the page and update the table after each submit.
I also added a check to make sure the new fields weren't blank so it wasn't adding an empty row. And you can now also add as many input rows as you want.
<?php
session_start();
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
}
if(isset($_POST['no_of_inputs'])){
$_SESSION['new_number'] = $_POST['no_of_inputs'];
for($i=1; $i<=$_SESSION['new_number']; $i++){
echo "<tr>";
echo "<td><input type='text' name='new_username_".$i."' placeholder='Username'></td>";
echo "<td><input type='text' name='new_password_".$i."' placeholder='Password'></td>";
echo "</tr>";
}
}
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
echo "<form method='POST' action='test.php'>";
echo "Add <input type='number' name='no_of_inputs' onchange='this.form.submit()'> rows";
echo "</form>";
for($i=1; $i<=$count; $i++){
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i])){
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
}
}
if(isset($_SESSION['new_number'])){
for($i=1; $i<=$_SESSION['new_number']; $i++){
if((isset($_POST['new_username_'.$i]) && $_POST['new_username_'.$i]!="") && (isset($_POST['new_password_'.$i]) && $_POST['new_password_'.$i]!="")){
$username = $_POST['new_username_'.$i];
$password = $_POST['new_password_'.$i];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
header('location: test.php');
unset($_SESSION['new_number']);
}
}
}
?>
This works and is tested but if you want the basic table structure is:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
In regards to the connection you can change the queries from how I did them like so:
Instead of:
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
You could do something like this:
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$stmt->bind_param($username,$password);
$stmt->execute();

Button submit, gets the other buttons from the database

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']);
}
?>

Using PHP to submit a Vector onto MySQL to make a connection with 2 tables

i have a list of emails on a database, which are brought onto the screen, this is coming from a previous page where you choose the category to add emails into.
The idea is for the user to check in the emails he wants to add to a connecting table that will join those two.
But i seem to be having problems. I have tried editing the page where i think the problem is, which is the , but no clue as to how i should edit it.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$idcategoria = $_GET["id"];
$query = "SELECT nome,email,id FROM email";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo"<form id='formulario' name='formulario' method='post' onsubmit='return validar(this);' action='../inserir/inserirmailcat.php'>";
echo "<br>";
echo "<button type='submit'>Submeter</button>";
echo "<tr align='center'><td>Nome</td><td>Email</td><td>Adicionar a Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if($campo=="nome")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="email")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="id")
{
echo "<td><input name='nome[".$valor."]' type='checkbox' value='Adicionar'></td></tr>";
}
}
echo "<input type='hidden' name='categoria' value='".$idcategoria."'>";
echo "</form>\n";
}
echo "</table>\n";
echo"</center>";
?>
This first page receives the ID from the previous one, and it lists a series of emails, where i check out the ones i want to add to a new table. And i try to pass them through a vector.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$queryq = "SELECT id FROM email";
$resultsq = mysql_query($queryq) or die(mysql_error());
while ($rowq = mysql_fetch_assoc($resultsq)) {
foreach ($rowq as $campoq=>$valorq) {
$cat = $_POST["categoria"];
$username = $_POST['nome['.$valorq.']'];
if ($username != '')
{
$query = "INSERT INTO emailcategoria (email,categoria) VALUES ('".$username.",".$cat."')";
mysql_query($query) or die(mysql_error());
}
}
}
mysql_query($queryq) or die(mysql_error());
header("Location:../listar/listarcategoria.php");
?>
On this second page i try to add only the emails which have been selected onto a new table which will receive the email's ID and the category's ID, but it is giving me the following error "after a few different error's when i tried a diferent approach":
Notice: Undefined index: nome[8445] in C:\xampp\phpMyAdmin\trabalho\inserir\inserirmailcat.php on line 10
The error is given for all the email ID's.
UPDATED
Error is on this like
$username = $_POST['nome['".$valorq."']'];
Firstly, is it supposed to be 'nome' ?
Secondly change the syntax like this
$username = $_POST['nome['.$valorq.']'];
$username = $_POST['nome['".$valorq."']'];
Well that's wrong, as the syntax highlighting shows.
$username = $_POST['nome['.$valorq.']'];
Also, sanitise your input or (better) use prepared statements!
> xkcd

php retain an array checkbox

I'm a complete noob but I have searched everywhere and can't find a solution.
What I have is an array of courses that I pull from my database (e.g.:
maths, art, science). These can change so I must add new courses all the time.
When a user ticks 2 of 3 courses (for example) but fails to add his username, then after the validation I want those 2 checkboxes to keep their old tick, so he must refill only his username in order to proceed.
What I get are all the checkboxes ticked :{
I'm so confused.
<?PHP
$check="unchecked";
?>
<?PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
foreach ($_POST['cid'] as $cid ) {
$check="checked";
}
}
?>
<?PHP
$course_data = "SELECT * FROM course ORDER BY cname";
$get_course = mysql_query($course_data) or die (mysql_error());
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' $check>"; // here are the courses(checkboxes)
}
?>
You have to set your $checked variable independently for each checkbox.
$checkedBoxes = array();
foreach($cid as $id) {
$checkedBoxes[$id] = "checked='false'";
}
foreach ($_POST['cid'] as $cid) {
$checkedBoxes[$cid] = "checked='true'";
}
Then in your loop that outputs the checkboxes, print the corresponding $checked value.
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' {$checkedBoxes[$cid]}>"; // here are the courses(checkboxes)
}
Is this what you want?
<?PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$cid_array = $_POST['cid'];
/*foreach ($_POST['cid'] as $cid ) {
$check="checked";
}*/
}
?>
<?PHP
$course_data = "SELECT * FROM course ORDER BY cname";
$get_course = mysql_query($course_data) or die (mysql_error());
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
if(is_array($cid_array))
{
if(in_array($cid, $cid_array))
{
$check="checked='checked'";
}
else
{
$check="";
}
}
else//it is not array because nothing was checked
{
if($cid == $cid_array)
{
$check="checked='checked'";
}
else
{
$check="";
}
}
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' $check>"; // here are the courses(checkboxes)
}
?>

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