I have a page where there are check boxes getting loaded dynamicaly so i dont know the number of check boxes (maximum of 50) and out of those check boxes users can select any number between 1 to 50 of checkboxes and can submit the form and on the action page i need get the values of all the checkboxes and insert them to database after checking for unoqueness like this
FIRST PAGE (FORM)
<?php while($the_DEATA_ARE_90=mysqli_fetch_array($getDOCS_30all)){ ?>
<div class="This_LISy_Lisy678" id="MAINDIV_DELEE<?=$the_DEATA_ARE_90['dcid']?>">
<div class="CHeck_IS_BOC">
<input type="checkbox" name="selecteddocx[]" value="<?=$the_DEATA_ARE_90['dcid']?>x<?=$the_DEATA_ARE_90['name']?>" id="check_docname<?=$the_DEATA_ARE_90['dcid']?>"/>
on the action page i am having this code
$selecteddocx = (isset($_POST['selecteddocx']) ? $_POST['selecteddocx'] : '');
$doocx = array();
$docxid = array();
foreach($_POST['selecteddocx'] as $value){
$str = explode("x",$value,2);
$doocx[] = $str[0];
$docxid[] = $str[1];
echo=implode(",", $doocx); // i need to print this for some reasons
echo implode(", ", $docxid); // i need to print this for some reasons
i am having this query to insert the coma sepertaed vales into database
i am converting the values of checkboxes into coma seperated values
$shaeredata=mysqli_query($conn,"insert into docs (dcid,pid) values ('$dcid','$pid')");
i i know i can insert the values into database in one shot like
$shaeredata=mysqli_query($conn,"insert into docs (dcid,pid) values ('$dcid','$pid'),('$dcid2','$pid'),('$dcid3','$pid'),('$dcid4','$pid')");
but i dont know how to do this as i am having the values in coma seperated (please note pid is same)
if checking of dcid can be done per pid then it will be great what i mean is thet insert only is dcid is not shared with pid (dcid already exists for that pid)
Related
I have a huge multistep form with data for multiple tables in mysql db. For every field my html is like-
input type="text" name="names" value="" // value set using php echo
On submit at php I am doing this for all the fields of my form-
$name=$_POST['names'] ?? ' '
to avoid unidentified index and unidentified variable
Then i update my first table and write log that its updated.
$query=mysqli_query($con,"UPDATE teacherpersonal set name='$name' ... where id=$id");
write_mysql_log("teacherpersonal updated", "facultydetails", $id).
I have defined write_mysql_log.
And similarly i update all the remaining tables with either the updated values or blank ("") values.
Since you can see that update query always executes even if the fields are not changed. Hence it is always logged that the tables are updated. But that's not what I want. I want to update only those fields in the table which are changed and remaining stay intact and log only those tables which are thus updated. Many tables won't be updated this way as the user might change only few details.
Using jquery and php.
My write_mysql_log is
function write_mysql_log($message, $db, $faculty_id)
{
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"facultydetails");
// Construct query
$sql = "INSERT INTO my_log (message, faculty_id) VALUES('$message', '$faculty_id')";
$query=mysqli_query($con, $sql);
// Execute query and save data
if($query) {
echo 'written to the database';
}
else {
echo 'Unable to write to the database';
}
}
This you can achieve in 2 different ways.
1) With the help of jQuery check the values which are updated, post only those values to the php script
2)At the time of updating the check the current values with the updated one based on that criteria update the db tables.
solution 1 is less time taking process compare to the other.
You need to update only the user edited value, by doing this you can achieve it;
$oldvalue = array("username" => "green", "email" => "green#mail.com","dob" => "111");
$newvalue = array( "email" => "green#mail.com","dob" => "111","username" => "blue");
$updates = array_diff($newvalue, $oldvalue);
$implodeArray = implode(', ', $updates);
$sql = ("UPDATE user WHERE userID=$userID SET $implodeArray");
mysql_query($sql,$this->_db) or die(mysql_error());
mysql_close();
Output:
$updates = array_diff($newvalue, $oldvalue);
will have:
Array ( [username] => blue )
which is changed one
Ok after considering many options like-
create json object for old and new data and then compare and check which values changed and update that table and log it.
Or create a php array with old and new data and check diff then do the same (as suggested by Ram Karuppaiah)
Or a bad idea to have a flag on every input and then mark which ones have changed using onkeyup jquery event then try to update only those fields tables.
So finally what i did is that i let the form get submitted with all the data. As earlier i am taking the data in php as $name=$_POST['names'] ?? ' ' (blank if nothing is submitted or if something submitted then its value).
Before update statement in php, i am querying the table and comparing the database values with the values i got, if all same i dont do anything. If not then i update the table with the new values and log the change.
I am trying to do the following:
If ID is not found inside the array 'hardware', delete all values where ID doesn't exist from the hardware array.
The issue I encountered is that, where I am able to delete one value at a time using the following:
foreach ($this->hardware AS $hardware){
if(!in_array($hardware['ID'],$hardwareList)){ // checks if hardware id is not on the hardware list
$query = 'DELETE FROM hardware_map WHERE ID='.$hardware['ID'];
$db->setQuery( $query );
$result = $db->loadResult();
}
}
It will not remove multiple values, if I delete all of them at once inside the textarea field.
<textarea id="hardwareTextArea" name="hardwareTextArea"><?php
foreach($this->hardware AS $hardware){
echo $hardware['name']."\n";
?></textarea>
Any help is appreciated on how to delete multiple values from the list at once if I delete all the values from the textarea.
You can first find the IDs that you want to remove them, then use one query by using IN:
DELETE FROM hardware_map WHERE ID IN (id1,id2, ...)
I have a text input box where you can type tags seperated by commas. I want to store these tags separately in a table but I have no idea how to do that.
I know I have to seperate the tags after they are posted so I now have this
$array = explode(',', $_POST['tag']);
Is this a good start and how do I have to go on after that?
Creating array from your input field as in your code
$array = explode(',', $_POST['tag']);
Create a mysql multi insert query using foreach loop
simillar to this:
$id=mysqli_insert_id($con);//get your project id here
$sql="";
foreach($array as $tag_name){
//modify below to add $id along with $tag_name
$sql.="('{$id}','{$tag_name}'),"; // you need to remove last comma else it will throw mysql error
}
if($sql!=""){
//rtrim to remove last ',' from string.
$sql=rtrim($sql,',');
$sql="INSERT INTO tags_tbl (project_id,tag) VALUES {$sql};"`
}
now use mysqli_query($con,$sql) to insert values in database
I have 4 tables named wheels, tires, oil_change, other_servicing.
Now, I have an order form for the person that comes for a car checkup. I want to have all of these 4 options in a form. So say someone comes for new wheels but not for tires, oil change, and other servicing and they will leave the other fields blank. And then you might have a scenario where all four fields are filled up. So how do i submit each to their respective tables from that one form?
The form will submit to a single php script. In the php you must do 4 separate queries to put the data into the correct tables. For example if you have this in php:
$wheels = $_REQUEST['wheels'];
$tires = $_REQUEST['tires'];
$oil_ch = $_REQUEST['oil_change'];
$other = $_REQUEST['other_servicing'];
mysql_query("INSERT INTO wheels (wheels) VALUES $wheels");
mysql_query("INSERT INTO tires (tires) VALUES $tires");
mysql_query("INSERT INTO oil_change (oil_change) VALUES $oil_ch");
mysql_query("INSERT INTO other_servicing (other_servicing) VALUES $other");
Of course I don't know the schemas of your tables but this is just an example of how you have to split it into 4 queries.
However, I would suggest to you that rather than have 4 tables for this, just have one table and make each of these a column instead. There may be other details I don't know about which would necessitate separate tables but with the info you have given seems like it would be simpler.
This shouldn't present any problem. The PHP page that receives the form data can run as many queries as you want. The skeleton for the code would be something like:
if($_POST['wheels']) { //if they filled in the field for wheels...
mysql_query("insert into wheels...");
}
if($_POST['tires']) { //if they filled in the field for tires...
mysql_query("insert into tires...");
}
if($_POST['oil_change']) { //if they filled in the field for oil_change...
mysql_query("insert into oil_change...");
}
... etc
for each form you would have something like this:
if($_POST['wheels']){mysql_query("INSERT INTO wheel_table (column1) VALUES (" . 'mysql_real_escape_string($_POST['wheels']) . "')")
this checks if the form element has been set, or has a value, and if it does, it creates a new row in the corresponding table.
if the form element's name is not 'wheels', you'll have the change $_POST['wheels'] to $_POST['form_element_name'] and if the table's name is not wheel_table, you'll have to change that and same with the column name.
this all has to be wrapped in a
In the form action you will specify the php file that will process the form.
In the php script file you will make tests of what parts of the forms are used and inserted in the respective table.
Try to separate the tests and the inserts of each table, to be easier for you.
This could be useful
if(isset($_POST['submit'])) // assuming you have submit button with name 'submit'
{
$fields['wheels'] = isset($_POST['wheels']) ? $_POST['wheels'] : null;
$fields['tires'] = isset($_POST['tires']) ? $_POST['tires'] : null;
$fields['oil_change'] = isset($_POST['oil_change']) ? $_POST['oil_change'] : null;
$fields['other_servicing'] = isset($_POST['other_servicing']) ? $_POST['other_servicing'] : null;
$q="";
foreach($fieldsas $key=>$val)
{
if($val!==null)
{
$q="insert into ".$key." values('".mysql_real_escape_string($val)."')";
mysql_query($q);
}
}
if($q==="") echo " Please fill up at least one field !";
}
This is just the core idea, using this you can execute multiple queries if user submits more than one fields at once and you may have to add other values (i.e. user_id).
I have a form that allows users to tag an image, choose a location from a drop-down, & upload the image. The tagging takes place by allowing multiple values, separated by commas, to be entered into a field.
This code is successfully inputting the comma delimited list to individual rows:
$categories = $_POST['bib'];
$categories = explode(",", $categories);
foreach($categories as $category) {
$category = trim($category); // Remove possible whitespace
$sql = "INSERT INTO athletes (bib) VALUES ('%s')";
$sql = sprintf($sql, mysql_real_escape_string($category));
mysql_query($sql);
}
However, it is not adding the additional content (location from drop-down list & image filename). For query purposes I need to be able to use both the 'bib' tag and the 'location' to be attached to images to allow users to search.
Before implementing the comma-separated option, this code was working to insert all of the data:
mysql_query("INSERT INTO `athletes` VALUES ('$id', '$bib', '$race','$new_file_name')") ;
So, basically I'm trying to merge the functionality of the two.
You need to use MySQL's UPDATE statement to update data in an existing row.