Im trying to insert multiple data that has only been selected checkbox. But Unfortunately, It also inserted the the unselected checkbox and also getting duplicate data.
Here's the UI for selecting data.
Here's my code:
if(isset($check)){
$client = $_POST['client'];
$project = $_POST['project'];
$kit_no = $_POST['kit_no']; //array
$kit_desc = $_POST['kit_desc']; //array
for($i=0;$i<sizeof($check);$i++){
for($i=0;$i<sizeof($kit_no);$i++){
for($i=0;$i<sizeof($kit_desc);$i++){
$query=mysqli_query($con,"INSERT INTO tbltrainsets_kit(id, client, project, kit_no, kit_desc)VALUES(
'',
'".$client."',
'".$project."',
'".$kit_no[$i]."',
'".$kit_desc[$i]."'
)")or die(mysqli_error($con));
}
}
}
}
The output that I produce is like this: (Please see the actual pix below):
The unselected data ('NA') was inserted into the database. It should only be the item 'DTR4000037253' inserting into the database.
Thank you in advace. Please respect my questions. I'm still studying do please do not bash. :|
I found the solution for this. When I study my code I realized that all of the logic is wrong.
Here's my code:
if(isset($check)){ // verify if checkbox is checked
foreach($check as $selected){ // select each checkbox that was selected an
// select value from the column equal to the ID of the selected checkbox
$kit_no = $this->dbquery->modGetdynamicval('tblkit','id', $selected, 'kit_no');
$kit_desc = $this->dbquery->modGetdynamicval('tblkit','id', $selected, 'kit_desc');
$query=mysqli_query($con,"INSERT INTO tbltrainsets_kit(id, client, project, kit_no, kit_desc)
VALUES('', '".$client."','".$project."','".$kit_no."','".$kit_desc."')")or die(mysqli_error($con));
echo $selected."</br>";
echo $kit_no."</br>";
echo $kit_desc."</br>";
}//end for loop
I'm using CI framework for getting the value the other 2 variables that I want to insert.
Related
I have a contact list that I made with PHP, jQuery and Datatables, where I have inline editing, and as soon as you click outside of a cell it updates via Ajax. Everything about the update of field values work fine, but now I wanted to save who last updated a record, by saving the username from the current session, so I've done that and sent it to the update file as a $_POST, but it won't save. When I dump it out or echo it, I can see the value, so I know it does get posted, but it just won't save in the database and I can't figure out why.
Since I don't code a lot and have learned what I know by reading and copying stuff from Stackoverflow, I'm sure I'm missing something obvious, but I still need help and I want to learn.
I've tried all kinds of "' variants, and typing in "test" or something in the query or in the variable does save it, so I feel like something is wrong with the $_POST or sql syntax, but since I can dump it and echo it, I have no idea what's wrong.
Worth mentioning is that the first part of the SQL works fine, and updates the cell it's supposed to, so the query runs, but randomly returns either "Uppdaterad!" or "Invaild requests" every other time, but the value saves either way. If I remove the whole "new part" with "last updated by", it works every time and returns "Uppdaterad!" without any problems.
<?php
if(!empty($_POST))
{
// Database settings
include "config.php";
foreach($_POST as $field_name => $val)
{
// Clean post values
$field_contactid = strip_tags(trim($field_name));
$val = strip_tags(trim(mysqli_real_escape_string($con, $val)));
$currentuser = strip_tags(trim(mysqli_real_escape_string($con, $_POST['currentuser'])));
//var_dump($currentuser);
// From the fieldname:contact_id we need to get contact_id
$split_data = explode(':', $field_contactid);
$contact_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($contact_id) && !empty($field_name))
{
// Update the values
mysqli_query($con, "UPDATE contactlist SET $field_name = '$val', `last_updated_by` = '$currentuser' WHERE id = $contact_id") or mysqli_error($con);
//mysqli_query($con, "UPDATE contactlist SET $field_name = '$val' WHERE id = $contact_id") or mysqli_error($con);
echo "Uppdaterad!";
} else {
echo "Invalid Requests";
}
}
} else {
echo "Empty POST!";
}
?>
I am handling a database table, where I have a quantity field in it. The quantity is manipulated through a form where it is reduced. The record gets inserted in the table with the new value as a new record with new quantity(reduced) and through this table it is being fetched in the next form. Now the issue is that whenever I fetch the quantity the older record(record with original quantity) is fetched where as the record with new quantity should be fetched.
I tried updating the same record with new value but it is not updating.
Here is the code for the same :
$haha="SELECT quantity FROM ready_for_delivery WHERE joborderid='".$data['joborderno']."'";
$haharesult = mysqli_query($link,$haha);
if(mysqli_num_rows($haharesult)>0)
{
$sql1="UPDATE ready_for_delivery SET quantity='".$_POST['rp_qty']."' WHERE joborderid='".$_data['joborderno']."'";
$sq1result=mysqli_query($link,$sql1);
//echo "I am here";
}
else
{
$quantity="INSERT INTO `ready_for_delivery` (`joborderid`,`joborderdetailsid`,`datetime`, `quantity`) VALUES ('".$data['joborderno']."',' ', now(), '".$_POST['rp_qty']."');";
$res1 = mysqli_query($link,$quantity);
echo "done";
}
I am checking if there is any data in the table with specified job order no, if yes, update it else insert as a new record. Every time it inserts as new record. Please guide me. Thanks.
Remove ; from your first line, hope this will work .
$haha="SELECT quantity FROM ready_for_delivery WHERE joborderid='".$data['joborderno']."'"; //remove ;
//echo $haha;
$haharesult = mysqli_query($link,$haha);
if(mysqli_num_rows($haharesult>0))
{
$sql1="UPDATE ready_for_delivery SET quantity='".$_POST['rp_qty']."' WHERE joborderid='".$_data['joborderno']."'";
$sq1result=mysqli_query($link,$sql1);
//echo "I am here";
}
else
{
$quantity="INSERT INTO `ready_for_delivery` (`joborderid`,`joborderdetailsid`,`datetime`, `quantity`) VALUES ('".$data['joborderno']."',' ', now(), '".$_POST['rp_qty']."');";
$res1 = mysqli_query($link,$quantity);
echo "done";
}
In the mysqli_query you have $sql a query variable while the actual query is in the $haha var.
Also, did you check if variable $data['joborderno'] is not empty?
The error lies in this line of code:
if(mysqli_num_rows($haharesult>0))
the closing brackets is in the wrong place. Correct way:
if(mysqli_num_rows($haharesult)>0)
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'm having a little problem with the codes given below. When I'm using the name="staff_number[]" then it insert the record with everything ok even if it is already in the database table and when i use name="staff_number" it does check the record and also give me alert box but when insert the record if it is not in the database it stores only the first number of the staff number like the staff no is 12345 it stores only 1. can anyone help in this record i think there is only a minor issue what I'm not able to sort out.
PHP Code:
<select placeholder='Select' style="width:912px;" name="staff_number[]" multiple />
<?php
$query="SELECT * FROM staff";
$resulti=mysql_query($query);
while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['staff_no']?>"><?php echo $row['staff_name']?></option>
<?php } ?>
</select>
Mysql Code:
$prtCheck = $_POST['staff_number'];
$resultsa = mysql_query("SELECT * FROM staff where staff_no ='$prtCheck' ");
$num_rows = mysql_num_rows($resultsa);
if ($num_rows > 0) {
echo "<script>alert('Staff No $prtCheck Has Already Been Declared As CDP');</script>";
$msg=urlencode("Selected Staff ".$_POST['st_nona']." Already Been Declared As CDP");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Insert Query
$st_nonas = $_POST['st_nona'];
$t_result = $_POST['st_date'];
$p_result = $_POST['remarks'];
$arrayResult = explode(',', $t_result[0]);
$prrayResult = explode(',', $p_result[0]); $arrayStnona = $st_nonas;
$countStnona = count($arrayStnona);
for ($i = 0; $i < $countStnona; $i++) {
$_stnona = $arrayStnona[$i];
$_result = $arrayResult[$i];
$_presult = $prrayResult[$i];
mysql_query("INSERT INTO staff(st_no,date,remarks)
VALUES ('".$_stnona."', '".$_result."', '".$_presult."')");
$msg=urlencode("CDP Staff Has Been Added Successfully");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Your $_POST['staff_number'] is actually an array.
So you have to access it like $_POST['staff_number'][0] here, 0 is a index number.
If the name of select is staff_number[] then $prtCheck will be a array so your check query must be in a loop to make sure your check condition.
if the name is staff_number then the below code is fine.
The answer of amit is right but I will complete it.
Your HTML form give to your PHP an array due to the use of staff_number[] with [] that it seems legit with the "multiple" attribute.
So you have to loop on the given values, you do it with a for and a lot of useless variables without really checking it. From a long time, we have the FOREACH loop structure.
I could help you more if i know what is the 'st_nona', st_date' and 'remarks' values.
According to your question you are getting difficulty in storing the data. This question is related to $_POST array.
Like your question we have selected following ids from the select : 1,2,3,4
It is only storing 1.
This is due to you have not used the loop when inserting the data.
Like below:
<?php
foreach($_POST['staffnumber'] as $staffnumber){
$query=mysql_query("select * from staff where staff_number =".$staffnumber);
if(mysql_num_rows($query)>0){
//action you want to perform
}else{
//action you want to perform like entering records etc. as your wish
}
}
?>
And I would like to suggest you that use the unique keys in database for field and use PHP PDO for database, as it is secure and best for OOPs.
Let me know if you have any queries.
I'm having trouble with an array. It actually appears on a page: a form of several lines. Each line corresponds to a record in the database and so they all have a common denominator.
More thanks to javascript I can add fields on the fly.
The trouble I'm having is when recording data. In fact I thought at first I should delete everything, and then insert so I just the following query:
<?php if(isset($_POST['enreg']))
{
foreach($_POST['data'] as $data){
if (!empty($data['code_s'])){
$sql2="DELETE FROM scenarii WHERE code_s='".mysql_real_escape_string($_GET['code_s'])."'";
mysql_query($sql2) or die(__LINE__.mysql_error().$sql2);
$sql7 = '
INSERT INTO scenarii SET
code_s = "'.mysql_real_escape_string($data['code_s']).'",
titre = "'.mysql_real_escape_string($data['titre']).'",
action = "'.mysql_real_escape_string($data['action']).'",
libelle = "'.mysql_real_escape_string($data['libelle']).'",
jour = "'.mysql_real_escape_string($data['jour']).'"' ;
mysql_query($sql7) or die(__LINE__.mysql_error().$sql7);
}
}
}
?>
The worries is that the deleted information is not stored again (though they are in the post variable as they exist in the form of a form and are therefore the variables.
In fact it only saves the new rows from javascript.
The trouble is that I can not do an update just because there are new lines.
<?php if(isset($_POST['enreg']))
{
$sql2="DELETE FROM scenarii WHERE code_s='".mysql_real_escape_string($_GET['code_s'])."'";
mysql_query($sql2) or die(__LINE__.mysql_error().$sql2);
foreach($_POST['data'] as $data){
if (!empty($data['code_s'])){
$sql7 = '
INSERT INTO scenarii SET
code_s = "'.mysql_real_escape_string($data['code_s']).'",
titre = "'.mysql_real_escape_string($data['titre']).'",
action = "'.mysql_real_escape_string($data['action']).'",
libelle = "'.mysql_real_escape_string($data['libelle']).'",
jour = "'.mysql_real_escape_string($data['jour']).'"' ;
mysql_query($sql7) or die(__LINE__.mysql_error().$sql7);
}
}
}
?>
put your delete query before foreach loop
afeter several hours of testing Ive seen that the delete request was in the loop for each so it has deleted all after all reinjection that is why I only have the last input left evry time.
Now I've deleted all and reinjected all after. It works properly.
What I do not understand is that i did not see it before.
Thanks to everybody for the help.