MySQL PHP array insert, multiple tables, not working - php

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.

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

How to Convert MySQL Column Value From Array to String

I am working on an existing HTML form used to collect data about a project and then inserts that project record into a MySQL database using PHP.
Inside the form, there is an input field named "staff[]". This field is a multi select element, that allows users to select more than one team member to handle the project.
<form action="" method="post">
<select multiple name="staff[]">
<option value="1">Mary</option>
<option value="2">Tyrone</option>
<option value="3">Rod</option>
<option value="4">Marcus</option>
<option value="5">David</option>
</select>
</form>
For example purposes, the user selects Tyrone, Rod and David for this particular project. If we insert the record at this point, the database only stores the first record value, which would be Tyrone's ID of 2. General practice is to store each instance in a separate table, however this is not our system and due to a restriction of 4 members for each project, management would prefer we insert a comma delimited array into each project's staff column for convenience.
In order to handle this issue, we've created a foreach loop that loops through the selected values from the dropdown menu, while ensuring a trailing comma doesn't exist:
// Add array into one variable
$staff_count = count($_POST['project_staff']);
$i = 0;
foreach($_POST['project_staff'] as $staff) {
if (++$i === $staff_count) {
$member_variable .= $staff;
} else {
$member_variable .= $staff . ", ";
}
}
After pressing the submit button, the above script is ran (which produces an array value of (2, 3, 5)) and the record is inserted into the 'projects' table with no issues.
HEREIN LIES THE PROBLEM.
Finally we have a view page, where we will call all employees assigned to a project, based on the query parameter, which would be the project ID. For example, if the previous project ID was 6, the following URL would be used:
site.com/project/view/?project=6
From this page, I am able to save the staff list using the following variable assignment:
$project = "SELECT * FROM projects WHERE project = 6";
$employee_chosen = $project['project_employee']
If the 'staff' column only accepted one employee (for example, just one value of 4), the variable would have a value of one number:
$project['project_employee'] (4)
I would then be able to run a secondary query for employees as such:
$employee_chosen = $project['project_employee']; (4)
query2 = "SELECT * FROM employees WHERE employee_ID = $employee_chosen";
This would very easily bring back the one employee that was entered in the "staff" column. However, we are dealing with an array in this column value (2, 3, 5) and so I have queried the following statement:
$employee_list = $project['project_staff']; (2,3,5)
$query_employees = "SELECT * FROM employees WHERE employee_id IN ($employee_list)";
When I run this query, I receive only the first result from the employee ID 2 (as initially stated with the HTML form).
However, if I use phpMyAdmin to directly type in the three numbers as a string:
$query_employees = "SELECT * FROM employees WHERE employee_id IN (2,3,5)";
I receive all three employee records.
Just to ensure that the column ARRAY was in fact behaving as a STRING, I initiated a var_dump on the value:
echo var_dump($project['project_staff']);
After which I received the following information:
string(7) "4, 5, 6"
Does anyone have any ideas?
I am satisfied with the idea that I am able to query the value, as before I received several non-object and array errors.
Thanks in advance for any assistance you may be able to provide.
I'm pretty sure from what you are saying that you are storing a string $employee_list that might be '2,3,4'. Then your IN ($employee_list) is really IN ('2,3,4') but what you really want is IN (2,3,4). There are various ways to get there but you could do
$employee_list = implode(','(explode(',', $employee_list));

How to combine "add" and "edit" forms into 1 "script"?

I've always found myself creating two separate php files/scripts for adding a certain data and editing this data. These files weren't that much different, so I figured there should be a way how to make them into one file.
Here I'll present a very simple example to illustrate my point:
add.php:
<?php
$title = $_POST['title']; // ignore the unescaped data, this is a simple example
$text = $_POST['text'];
mysqli_query($connection,
"INSERT INTO `articles` (`title`, `text`) VALUES ('$title', '$text')");
echo'
<form>
<input type="text" name="title" value="'.$_POST['title'].'" />
<input type="text" name="text" value="'.$_POST['text'].'" />
<input type="submit" value="Add" />
</form>
';
?>
edit.php:
<?php
$id = $_GET['id'];
$title = $_POST['title']; // ignore the unescaped data, this is a simple example
$text = $_POST['text'];
// save data
mysqli_query($connection,
"UPDATE `articles` SET `title` = '$title', `text` = '$text'
WHERE `id` = $id");
// get current data
$q = mysqli_query($connection,"SELECT * FROM `articles` WHERE `id` = $id");
$d = mysqli_fetch_array($q);
$title = $d['title'];
$text = $d['text'];
echo'
<form>
<input type="text" name="title" value="'.$title.'" />
<input type="text" name="text" value="'.$text.'" />
<input type="submit" value="Add" />
</form>
';
?>
As you can see, the add and edit forms/codes are very similar, except that:
add inserts the data, while edit updates it
add inserts $_POST values into the form (if there's an error, so that the submitted data remains in the form, while edit inserts the current database values into the form (after the save is complete and the page refreshes, so that the form has the current db values)
Can these two somehow be merged into one file/code, so that if I want to add/change the form values, I don't need to edit two files separately, but will change the form only once?
You can use a INSERT ON DUPLICATE KEY UPDATE which roughly gave you :
<?php
$id = $_GET['id'];
$title = $text = '';
if ($_POST)
{
$title = $_POST['title'];
$text = $_POST['text'];
// save data
$query = "INSERT INTO `articles` (`id`, `title`, `text`)
VALUES ('$id', '$title', '$text')
ON DUPLICATE KEYS UPDATE title = title, text = text"
mysqli_query($connection, $query);
}
else if ($id)
{
// get current data
$q = mysqli_query($connection, "SELECT * FROM `articles` WHERE `id` = $id");
$d = mysqli_fetch_array($q);
$title = $d['title'];
$text = $d['text'];
}
echo '
<form>
<input type="text" name="title" value="'.$title.'" />
<input type="text" name="text" value="'.$text.'" />
<input type="submit" value="Add" />
</form>';
If it's a POST and no $id present : a new row is inserted just like an INSERT.
If it's a POST and an $id is present : if $id already exist in the table than the row is updated otherwise it's an INSERT.
If you only have an $id : show the form with existing data in it.
If it's not a POST and $id isn't populated : show an empty form.
You could use a combination of GET and POST parameters do achieve what you want. Use the GET parameters to distinguish between edit and add, i.e. /post?action=add or /post?action=edit. Based on the value of $_GET['action'] you'd know whether to render an empty form to add a post or to populate the form in with data from the DB. Then you could have a hidden field in your form, which you'd fill in with the value of $_GET['action'] and so you'd be able to know whether to INSERT or UPDATE when processing the form after submitting it.
It might be worth though to start using some framework, i.e. CakePHP, CodeIgniter, Zend Framework, etc.
I tend to make an interface for inserting and updating data which has only one method for inserting and updating. The key point for that to work is the user form that is being submitted must contain the id of the row being updated.
public method save( Object obj )
if obj.id is in database
query = "update table set attrA = obj.a, attrB = obj.b where id=obj.id"
else if obj.id < 1
query = "insert into table (a,b,c) values (obj.a,obj.b,obj.c)"
This implies that when you create a new object to be submitted, it must have id initialized to 0 or -1 (1 is the first key row for a table with int primary keys). Likewise, a form in a html file must have an <input type=hidden value=row.id name=DBID> that is populated either with a default value (null, 0, -1) or a valid id of the object being edited.
Essentially this means that the user may update arbitrary rows in the table, but granted they have authenticated themselves, this should not be a problem. Also, it is usually enough to know that the id > 0 to to an INSERT, and UPDATE otherwise. It is not necessary to verify that the id being submitted is in the database table, because when you insert you do not set the id, but rather let the DB auto-increment the primary key.
update
wow so many silly typos after only 3 beers. I hope this is readable
Here's an idea how it should look like using OOP (in my opinion).
Let's assume you have some class that represents form element called FormElement.
Then you have some generic form that should support what? Let's assume MVC:
displaying itself
adding elements
setting default values
parsing request values
getting values
validating values
So you'll build yourself an interface like
interface IForm {
public function Display();
public function AddElement( FormElement $element);
public function SetValues( array);
public function FetchPostValues();
public function GetValues();
public function Validate();
}
Then, what's common for both those forms (let's say that you want to prohibit change of email)? Everything except FetchPostValues()
So you'll build a class with one pure virtual method which will do everything that is similar:
abstract class FormArticle implements IForm {
// All methods implemented except FetchPostValues
abstract public function FetchPostValues();
}
And then just build two small classes that will define how to fetch post data:
class FormArticleEdit extends FormArticle {
public function FetchPostValues(){
if( isset( $_POST['email'])){
throw new Exception('What are you trying to achieve?');
}
// ...
}
}
And one more tip (two actually):
Implement abstract class like FormAbstract that will provide all generic methods like AddElement(), Display(). This will save you copying of those general methods every time, but will still provide you with ability to start from scratch (when using database or so directly to cache items).
Rather use framework that already has model for reusing forms (Zend is my personal favorite).

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

Insert array values into database

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.

Categories