mysql not updating from php form - php

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.

Related

Clicking the checkbox and changing database Boolean value in php

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
});
});

PHP Search Script for Website

Alright, So i am trying to code a little PHP Search Script for My website so users can simply do a search from a artist name, song name or a city.
My table in my database has 'city', 'artist' and 'city'.
Here is my form:
<div id="search">
<form name="search" method="post" action="../searchDb.php">
<input type="text" name="find" placeholder="What are we searching for ?"/> in
<Select NAME="field">
<Option VALUE="artist">Artist</option>
<Option VALUE="song">Song</option>
<Option VALUE="city">City</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
</div>
As you can see, there are three OPTION values (one for each column in my table).
Here is my PHP code:
<?php
$searching = "searching";
$find = "find";
$field = "field";
//this is to make sure the user entered content
if ($searching =="yes")
{
echo "<p><h2>Results</h2></p>";
//if user did not enter anything in the search box, give error
if ($find == "")
{
echo "<p>You forgot to enter a search term</p>";
}
include 'connect.php';
// strip whitespace, non case sensitive
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//perform search in specified field
$data = mysql_query("SELECT * FROM artists_table WHERE upper($field) LIKE'%$find%'");
//show results
while($result = mysql_fetch_array( $data ))
{
echo $result['artist'];
echo " ";
echo $result['song'];
echo "<br>";
echo $result['city'];
echo "<br>";
echo "<br>";
}
//counts results. ifnone. error
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//show user what he searched.
echo "<b>Searched For:</b> " .$find;
}
?>
My connect.php (that is included) works perfectly (i have that same file working on another page, no problems..So its safe to say thats not the problem).
When i do a test and run a search, it loads up my searchDb.php but NOTHING is displayed. Simply a white page...
Any help would be greatly appreciated. I am lost as to why or what is not working...
Thanks Guys !
If this is your code, then you are hardcoding $searching = "searching", but in your if you are checking if $searching =="yes", so none of the code will show.
<?php
$searching = "searching";
...
...
//this is to make sure the user entered content
if ($searching =="yes")
{
...
}
Edit-
My guess is that you wanted to do something like-
$searching = mysql_real_escape_string($_POST['searching']); // sanitized just to be consistant.
$find = mysql_real_escape_string($_POST['find']);
$field = mysql_real_escape_string($_POST['field']);
Note- you should not be writing new code with mysql_* functions. You should learn either mysqli_ or PDO - http://php.net/manual/en/mysqlinfo.api.choosing.php
Here are 2 ways to avoid getting the "Notice: Undefined variable"
Check if submit button was pushed
if (isset($_POST['search'])) {
$searching = mysql_real_escape_string($_POST['searching']); // sanitized just to be consistant.
$find = mysql_real_escape_string($_POST['find']);
$field = mysql_real_escape_string($_POST['field']);
}
Or check if each field is set, and set it to the value, and if not set to no/empty
if (isset($_POST['search'])) { // checks to see if the form submit button was pushed
$searching = isset($_POST['search']) ? mysql_real_escape_string($_POST['searching']) : 'no'; // sanitized just to be consistant.
$find = isset($_POST['find']) ? mysql_real_escape_string($_POST['find']) : '';
$field = isset($_POST['field']) ? mysql_real_escape_string($_POST['field']) : '';
}

Endless If-Else statements

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.

connection table for overcoming the checkbox problem

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);
?>

problems with update logic for a mysql db

I have the following PHP form, which posts back to a mysql database. My problem is that the update query seems to work, but is always overwritten with "checked". What I want to do is check is get the current value from the database, and then if there is a value in post, get that instead. Now...why is this not working? Do I need to have an else clause when checking if it is in _POST? If that's the case, do I even need to initilise the variable with $checkDeleted = "";?
<?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"];
}
$checkDeleted = "";
$con = mysqli_connect("localhost","user","pw", "db");
$getformdata = $con->query("select ARTICLE_NO, deleted from STATUS where ARTICLE_NO = '$pk'");
while ($row = mysqli_fetch_assoc($getformdata)) {
$ARTICLE_NO = $row['ARTICLE_NO'];
$checkDeleted = $row['deleted'];
}
$checkboxes = (isset($_POST['checkboxes'])? $_POST['checkboxes'] : array());
if (in_array('deleted', $checkboxes)) $checkDeleted = 'checked';
if($cmd=="submitinfo") {
if ($ARTICLE_NO == null) {
$statusQuery = "INSERT INTO STATUS VALUES (?, ?)";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("ss", $pk, $checkDeleted);
$statusInfo->execute();
$statusInfo->close();
} else {
print_r($con->error);
}
} else if ($ARTICLE_NO == $pk) {
$statusQuery = "UPDATE STATUS SET deleted = ? WHERE ARTICLE_NO = ?";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("ss", $checkDeleted, $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\">
<input type=\"checkbox\" name=\"checkboxes[]\" value=\"deleted\" ".$checkDeleted." />
<label for=\"deleted\">Delete</label>
<input type=\"hidden\" name=\"cmd\" value=\"submitinfo\" />
<input name=\"Submit\" type=\"submit\" value=\"submit\" />
</form>";
}
?>
I tried changing the line to set checkDeleted to the following, which made no difference..although it should?
if (in_array('deleted', $checkboxes)) {
$checkDeleted = 'checked';
} else {
$checkDeleted = '';
}
edit: OK, I have managed to get this to work, but only after changing to
$checkDeleted = in_array('deleted', $checkboxes) ? 'checked' : '';
as per the answer below, but this still did not work. For it to work I had to remove the database query, and replace it with one within the submitinfo branch, and one within the EditStatusData branch...why? Why is it not possible to have only one query?
if($cmd=="submitinfo") {
$getformdata = $con->query("select ARTICLE_NO from STATUS where ARTICLE_NO = '$pk'");
while ($row = mysqli_fetch_assoc($getformdata)) {
$ARTICLE_NO = $row['ARTICLE_NO'];
}
if ($ARTICLE_NO == null) { etc
and
if($cmd=="EditStatusData") {
$getformdata = $con->query("select deleted from STATUS where ARTICLE_NO = '$pk'");
while ($row = mysqli_fetch_assoc($getformdata)) {
$checkDeleted = $row['deleted'];
} etc
this is pretty much identical to your other question
mysql not updating from php form
there is nothing wrong with the code, it is working exactly as you want
What I want to do is get the current value from the database, and then if there is a value in post, get that instead.
case 1: html form with no tick
read from database $checkDeleted = 'checked'
if $_POST['checkboxes']['deleted'] is not set, leave $checkDeleted as is
writes 'checked' to database
case 2. html form with tick
read from database $checkDeleted = 'checked'
if $_POST['checkboxes']['deleted'] is set, change $checkDeleted = 'checked'
writes 'checked' to database
so no matter if you have a tick or not, once you have changed the database value to checked then, there is no way to change it
I will assume that what you want to do is always overwrite the database value with whatever the tick box is set to, in that case
replace this line
if (in_array('deleted', $checkboxes)) $checkDeleted = 'checked';
with this
$checkDeleted = in_array('deleted', $checkboxes) ? 'checked' : '';
This will only work if you're GET'ing data:
$getformdata = $con->query("select ARTICLE_NO, deleted from STATUS where ARTICLE_NO = '$pk'");
In your code $pk isn't set if your request is POST. You should also escape the $pk variable in this line as a user could put any data they liked in $_GET['pk'] and it could break your SQL query.

Categories