Insert array values into database - php

I have a form that lists module id and also sub_module_id, for example
ADMIN === is parent module ID
users=== sub module id
here admin appears in the menu and users inside admin
now inside the form i have used checkbox like
[]Admin
[]Users
for parent module ID admin
<input id='module_permission[]' onclick=\"selectall()\" type='checkbox' value='".$key."' name='module_permission[]' $val_checked ><b>".$val."</b><br> ";
for sub modules
<input type='checkbox' id='sub_module_permission[$l][]' name='sub_module_permission[$l][]' value='".$key1 ."' onclick=\"selectParent($l);\" $val_checked>".$val1."<br> ";
when i click in check box its id get post and i need to insert to databse but i am unabale to insert the sub _module id in database
to post
$module_id=$_post[module_permission]
foreach($module_id as $key=>$value){
$sql2 = "INSERT INTO user_permissions(permission_id, employee_cd,module_id) values
(PERMISSION_ID_seq.nextval,'$employee_cd','$value')";
$this->db->db_query($sql2);
}
for sub _modules
$sub_module_id =$_POST['sub_module_permission'];
print_r($sub_module_id);
foreach($sub_module_id as $sub_key=>$sub_value)
{
echo $sub_value[1];
$sql4 = "INSERT INTO user_permissions(permission_id, employee_cd,module_id) values
(PERMISSION_ID_seq.nextval,'$employee_cd','$sub_value')";
HERE parent module id value get inserted in database but not the sub_module
please help

so what prints out when you print_r($sub_module_id); and echo $sub_value[1];?
And what does your query string look like after the vars are subbed in? echo $sql4;
Try running the the query string directly in SQL rather than through PHP. This will let you know if you have a SQL error or a PHP error. If the SQL is fine, add some error checking to your PHP so you can see where it fails. Usually I wrap all queries in something like:
if(!$result=$mysqli->query($query))
throw new Exception($query. " " .$mysqli->error);
From your comments and the now properly formatted code, it's possible to see that you are not referring to the 2nd dimension of your submoduleid. In otherwords you are trying to sub an array into your SQL statement.
This is what you have:
$sub_module_id =$_POST['sub_module_permission']; //a 2d array
print_r($sub_module_id);
foreach($sub_module_id as $sub_key=>$sub_value){
echo $sub_value[1];
$sql4 = "INSERT INTO user_permissions(permission_id, employee_cd,module_id)
values(PERMISSION_ID_seq.nextval,'$employee_cd','$sub_value')";
}
And this is what you need:
$sub_module_id =$_POST['sub_module_permission']; //a 2d array
print_r($sub_module_id);
foreach($sub_module_id as $sub_key=>$sub_value_arr){ //values are an array not a scalar
echo $sub_value_arr[1];
$sub_value= $sub_value_arr[1]; //get scalar for SQL
$sql4 = "INSERT INTO user_permissions(permission_id, employee_cd,module_id)
values(PERMISSION_ID_seq.nextval,'$employee_cd','$sub_value')";
}

Unrelated, but if you're getting that input from a form (and really, even if you're not), it's always a good idea to sanitize your SQL.

Related

How do I insert an array into single field of my SQL table using PHP

I have checkbox entries that I am appending to a list by their html name, like so:
Choose no more than three categories:<br>
<input id='category1' type="checkbox" name="boxsize[]"
onclick="CountChecks('listone',3,this)" value="asian">Asian
<input id='category2' type="checkbox" name="boxsize[]"
onclick="CountChecks('listone',3,this)" value="asianFusion">Asian Fusion
I have many other checkboxes as well. I then implode this list by doing:
$sanentry=implode(',',$_REQUEST["boxsize"]);
When I echo $sanentry I get a list of the selected values in the following format: asian, asian fusion. However when I try to send these values to my ethnicity table in mysql the ethnicity column is empty. Here is the post method and query I am using to send these values to my table.
$sanethnicity=mysqli_real_escape_string($con, $_POST['$sanentry']);
$sql3="INSERT INTO
ethnicity(restaurant_id,ethnicity)VALUES('$sanrestid','$sanethnicity')";
if ($con->query($sql3) === TRUE) {
echo "New record in ethnicity table created \n";
} else {
die("Error: " . $sql3 . "<br>" . $con->error);
}
mysqli_close($con);
?>
There is no problem with my restaurant_id column as that is being updated fine but for every new row inserted the ethnicity column always comes up blank. Does anyone know what I'm doing wrong?
enter image description here
Guessing the variable name is wrong. should be $sanethnicity you've got $ethnicitydb in your query.
$sql3="INSERT INTO ethnicity(restaurant_id,ethnicity) VALUES('$sanrestid','$sanethnicity')";
Also, is this the field that has raw ethicity array? $_POST['$sanentry'] or has that been imploded. You probably want this:
$sanethnicity=mysqli_real_escape_string($con, $sanethnicity);
Since the $sanethnicity was prior imploded from seomthing like:
$sanethnicity = implode(',',$_REQUEST["boxsize"]);
In this line your trying to use $sanentry as an entry in $_POST...
$sanethnicity=mysqli_real_escape_string($con, $_POST['$sanentry']);
Should be
$sanethnicity=mysqli_real_escape_string($con, $sanentry);
Although - you should be looking into using prepared statements and bind variables.
If you want to store it without losing the array structure then you should use serialize

Update db tables of only updated fields of form- JQuery, PhP

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.

Proper way to manipulate database

My entry form I have an inventory database with tables like aluminium, iron etc... Each table contains a subcategory of items like aluminium_pala, iron_1.5inch and so on. The entry code is like this:
include("dbConnect.php");
$orderNo = $_POST["number"];
if(isset($_POST["mat1"])&&$_POST["mat1"]!=NULL)
{
$mat1 = $_POST["mat1"];
$selmat1 = $_POST["selmat1"];
$amtmat1 = $_POST["amtmat1"];
$query = "INSERT INTO $mat1 ($selmat1,orderNo) VALUES (-$amtmat1,$orderNo);";
if(!($result = $mysqli->query($query)))
print "<div class='error'>insertion failed. Check your data</div>";
}
if(isset($_POST["mat2"])&&$_POST["mat2"]!=NULL)
{
$mat2 = $_POST["mat2"];
$selmat2 = $_POST["selmat2"];
$amtmat2 = $_POST["amtmat2"];
$query = "INSERT INTO $mat2 ($selmat2,orderNo) VALUES (-$amtmat1,$orderNo);";
if(!($result = $mysqli->query($query)))
print "<div class='error'>insertion failed. Check your data</div>";
}... and it goes on till mat11
I am trying to collect each similar table (mat1, mat2..) and their corresponding item (selmat1, selmat2...) and bunch the all in one query. That is, instead of going
INSERT INTO al_openable (zPala,orderNo) VALUES (23,14);
INSERT INTO al_openable (outer,orderNo) VALUES (50,14);
I am trying to execute it like
INSERT INTO al_openable (zPala,outer,orderNo) VALUES (23,50,14);
I need this to avoid duplicate foreign key entry(for $orderNo). One idea I've been considering is to use UPDATE if the order number is pre-existing. Do you guys think this is a good idea? And if so, what will be the best way to execute it? If not, how would a more experienced programmer solve this conundrum?
I think this question is related to your query: Multiple Updates in MySQL
You may use ON DUPLICATE KEY UPDATE in combination with INSERT statement.

MySQL PHP array insert, multiple tables, not working

I'm trying to update a table of dishes with a new entry and cross reference it to an existing table of ingredients. For each dish added, the user is required to assign existing ingredients and the volume required on multiple lines. On submission, the Dish should be entered into the table 'Dishes' and the assigned ingredients should be entered into the 'DishIng' linked tabled.
My tables are set like this:
Table: "Dishes" Columns: DishID, DishName, Serves, etc...
Table: "DishIng" Columns: DishID, IngID, Volume
Table: "Ingredients" Columns: IngID, IngName, Packsize etc...
HTML:
DishID:
Name:
Catagory :
Serving:
SRP:
Method :
Source :
IngID:
Volume:
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
<li>IngID: <input type="text" name="IngID"></li>
<li>Volume: <input type="text" name="Volume"></li>
</ul>
<input type="submit">
</form>
Any suggestions for dymanically adding a row of ingredients in HTML would be very welcome.
PHP:
<?php
require_once('db_connect.php');
$DishID = mysqli_real_escape_string($con, $_POST['DishID']);
$DishName = mysqli_real_escape_string($con, $_POST['DishName']);
$DishCatID = mysqli_real_escape_string($con, $_POST['DishCatID']);
$Serving = mysqli_real_escape_string($con, $_POST['Serving']);
$SRP = mysqli_real_escape_string($con, $_POST['SRP']);
$Method = mysqli_real_escape_string($con, $_POST['Method']);
$SourceID = mysqli_real_escape_string($con, $_POST['SourceID']);
$IngID = mysqli_real_escape_string($con, $_POST['IngID']);
$Volume = mysqli_real_escape_string($con, $_POST['Volume']);
$array = array('$DishID', '$IngID', '$Volume');
$sql="INSERT INTO Dishes (DishID, DishName, DishCatID, Serving, SRP, Method, SourceID)
VALUES ('$DishID', '$DishName', '$DishCatID', '$Serving', '$SRP', '$Method', '$SourceID')";
$sql2 = "INSERT INTO DishIng (DishID, IngID, Volume) VALUES ('$DishID', '$IngID', '$Volume')";
$it = new ArrayIterator ( $array );
$cit = new CachingIterator ( $it );
foreach ($cit as $value)
{
$sql2 .= "('".$cit->key()."','" .$cit->current()."')";
if( $cit->hasNext() )
{
$sql2 .= ",";
}
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
if (!mysqli_query($con,$sql2)) {
die('Error: ' . mysqli_error($con));
}
echo "records added";
require_once('db_disconnect.php');
php?>
Currently on submit, it only updates the 'Dishes' table and gives me this message: '1 record addedError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('0','$DishID'),('1','$IngID'),('2','$Volume')' at line 1'
A high level of how you do this (although there are plenty of ways, this is just one with straight DB/PHP/HTML):
Your php will create a form to input the dish fields from the user.
Your php will then pull all of the ingredients from the ingredient table for that dish
Your php will iterate through the results returned from that query and for each result will:
Create a checkbox type input for the ingredient, and
Create a Text field type input for the ingredient and.
Create a Hidden field with the IngID
Once the user submits the form:
Your php will insert the to the dish table based on the dish fields on the form submitted.
Your php will iterate through the ingredients fields from the form submission and with each one will:
Determine if that ingredients checkbox is checked. If it is it will:
Insert into the DishIng table using the Hidden IngID field and the Volume field
Essentially, there is are two FOR loops. One to loop through the initial list of ingredients to make your form, and a second to loop through the form that is submitted. Each ingredient with a check mark will need it's own SQL INSERT statement to be added into the DishIng table.
How to iterate through SQL results in php: Iterate through Mysql Rows in PHP
How to iterate through Form fields in php: PHP loop through array of HTML textboxes
Because you are taking in user input and sticking it into a MySQL insert query, you'll also want to make sure you sanitize the inputs before submitting the query so you avoid some evil-doer from pulling some SQL injection and killing your DB.
Lastly: This is a pretty vague question so I anticipate it will be downvoted, and my response is also pretty vague. I only wrote it because it touches on an overall idea that is pretty common and is difficult to ask in a succinct way if you are just getting started with web development. You will probably get stuck quite a few times while writing this. Try narrowing down your problem to a single issue and take that issue/question to stackoverflow. You can also hit up Google, since everything you will need to do here has been written about on forums, blogs, wikis, and Q&A sites by a gajillion other folks.

How to insert entries into different tables from one page?

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).

Categories