I am using this auto complete form, that gets the data from 1 table,
now i am using that form to insert data from its table to another table.
here is my SQL for the inserting into the table "products"
$image = addslashes(file_get_contents($_FILES['prod_pic']['tmp_name']));
$sql="INSERT INTO `inventory` (`prod_brand`,`prod_name`,`prod_category`,`prod_price`,`prod_desc`,`prod_quantity`,`prod_pic`)
VALUES
('$_POST[prod_brand]','".mysql_real_escape_string($_POST['prod_name'])."','$_POST[prod_category]' ,'$_POST[prod_price]',
'".mysql_real_escape_string($_POST['prod_desc'])."','$_POST[prod_quantity]','{$image}')";
the prod_category is the column i need to fill. I have data from the table named "categories" with column name "categories"
so how do i input the data from categories to the column = prod_category in the products table?
Check example and try this way...may it's help you.
INSERT INTO student (s_id, s_name, s_email)
SELECT t_id, t_name, t_email FROM teacher
WHERE teaher.tid='25';
As i understand in POST['prod_category '] contain string, like you have text input. The best way to do what you need - is change category for select in html, like this
<select>
foreach(categories as $category){
<option value='category->id' >category1->name </option>
}
</select>
Then you will get in post category id from the table named "categories"
If you dont like it your should replace '$_POST[prod_category]' from youre query to subquery
select id from categories where categories = '$_POST[prod_category]'
Related
I'm having a problem with a MySQL query that uses inner and left joins. The problem is that, where the foreign key in the primary table is blank in the case of a NULL-permitted field, the query doesn't read all the fields in the primary table.
My task is to organize a list of recordings with MySQL, some of which are live recordings while others are studio recordings. For the purposes of this question, I'm simplifying the table structure as follows:
table name: recordings
fields:
recording_id INT AUTO-INCREMENT
recording_name VARCHAR NOT NULL
artist_id INT NOT NULL FOREIGN KEY
event_id INT NULL FOREIGN KEY
table name: artists
fields:
artist_id INT AUTO-INCREMENT
artist_name VARCHAR NOT NULL
table name: events
fields:
event_id INT AUTO-INCREMENT
event VARCHAR NOT NULL
venue_id INT NOT NULL FOREIGN KEY
table_name: venues
fields:
venue_id INT AUTO-INCREMENT
venue_name VARCHAR NOT NULL
address VARCHAR NOT NULL
Where a recording was done live, I want the option to give details of the event where the recording was done, and if it was a studio recording, I leave the event field blank. In other words, in the recordings table event_id is an optional field, but artist_id is always required.
To edit an existing record in the recordings table, I have a form with three fields (again simplified):
<form>
<input name="recording_name" type="text" value="<?php $recording_name ?>" />
<select name="artist_id">
<option>Select option</option>
<option <?php $selected ?> value="1">Artist 1</option>
etc.
</select>
<select name="event_id">
<option>Select option</option>
<option <?php $selected ?> value="1">Venue 1</option>
etc.
</select>
</form>
I use the $selected variable to display the option corresponding with the existing value pulled from the database in the form's dropdown list, like so:
$selected = ($existing_value == $option_id ? 'selected="selected" : '');
Now, to get the existing values of the form I have the following SQL query:
$recording_sql =
'SELECT * FROM recordings
INNER JOIN artists ON recordings.artist_id = artists.artist_id
LEFT JOIN events ON recordings.event_id = events.event_id
LEFT JOIN venues ON events.venue_id = venues.venue_id'
Then, to populate the two dropdowns:
$artist_sql =
'SELECT * FROM artists'
$event_sql =
SELECT * FROM events
INNER JOIN venues ON events.venue_id = venues.venue_id
My PHP code looks something like this:
function buildForm($result){
$data = $result->fetch_array($MYSQLI_ASSOC))
$form = '<input name="recording_id" type="hidden" value="'.$data['recording_id'].'" />';
$form .='<input name="recording_name" type="text" value="'.$data['recording_name'].'" />';
$form .= buildSelectBox('artists', $data['artist_id']);
$form .= buildSelectBox('events', $data['event_id']);
return $form;
}
function buildSelectBox($table, $existing_id = NULL){
//run SQL to pull data from relevant table (i.e. $artist_sql, or $event_sql which includes join to 'venues')
//Loop through $mysqli_result to build each option
while(etc....){
$selected = ($existing_id == $option_id ? 'selected="selected" : '');
$options_list .= '<option'.$selected.'value="'.$id.'">'.$artist_name.'</option>';
}
return $options_list;
}
This works fine if both foreign keys have values. However, when the event_id field is blank in recordings, it doesn't read the other foreign key either. It reads the text field, recording_name, fine though. In other words, the result set I get for $recordings_sql contains only the value of the recording_name field, while both foreign keys are returned blank, even though one is not blank. I've tried all the join permutations (left, inner, right) in different combinations, but none of them give the desired result.
I'm stumped! Thank you in advance for any help!
I spent most of yesterday trying to reproduce the problem with a simplified version of my application, and eventually I did. It turns out that the first foreign key (artist_id in my simplified example), was repeated in another table lower down in a series of joins that start with the second foreign key (event_id in my simplified example). So, my guess is that, if 'event_id' is null, 'artist_id' gets overwritten by a null value because the query will return empty values for everything after 'event_id' if it is empty. So, the problem isn't with how LEFT JOIN works, but rather with the repetition of the first foreign key in a subsidiary table that depends on a second foreign key that is allowed to be null. I evidently need to revisit my table structure...
Many thanks for all the suggestions!
category --> `cat_id`,`name`
sub_category --> `sub_cat_id`,`name`
category_subcategory_association --> `cat_sub_cat_id`,`cat_id`,`sub_cat_id`
order_master --> `order_id`,`cat_sub_cat_id`,`cat_id`,`sub_cat_id`,`order_name`
These are the database tables which iam having while adding the orders into order_master table if we give cat_id,sub_cat_id while inserting into the table it should check the whether these ids are present in the association table or not,if the id is present in association table then we should get that association id and should insert into the orders table.
How can we do this can anyone help me
Thanks in advance.
You just need to check if it exists, if not - insert it into the the db and fetch the newest id.
I.E:
$cat_name = ; // your code
$sub_cat_name =; // your code
$query = mysql_query("SELECT cat_id FROM `category` AS `c` WHERE name = '$cat_name'");
if(!mysql_num_rows($query)) {
mysql_query("INSERT INTO category (name) VALUES ('$cat_name')");
$cat_id = mysql_insert_id();
} else
$cat_id = mysql_fetch_array($query);
// now do the same for the sub category and then insert it into to order_master
this is a general code, you need to customize it into your framework's standards.
hope it helped
you implement the checks via a select statement:
http://dev.mysql.com/doc/refman/5.1/de/select.html
running multiple sql queries, eg. a mixture of select and update statements requires you some knowledge on:
http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-model.html
http://php.net/manual/de/mysqli.multi-query.php
I'm new to both PHP and MySQL and I have a pretty complicated task to do for my current know-how. It goes like this:
I'm trying to create a data-driven website with a hand made CMS that will allow a user with no knowledge of web design/web development to manage it. Where I'm stuck is when I try to create a query to handle the data inserted to the database. It is a bookstore and I'm inserting books in the database. I thought of creating 3 tables, one to store the books themselves, one to store the categories these books belong to (f.e. literature, mystery, fantasy, etc) and, since the relation between these two tables is many-to-many relationship, I also created a lookup table to link these two, using 2 columns populated with 2 foreign keys representing the IDs of the two tables.
The problem is I can't find how to insert multiple rows with same ID (the book ID) on one column and different second column (the category ID). The categories will be picked in an HTML form via checkboxes. I' ve seen in several posts here I need to make an array in PHP script to store the data from the checkboxes the user picked, but I have absolutely no clue on how to structure the query that will turn these checkboxes into multiple MySQL table rows.
I've seen people suggesting imploding the values, but that would store multiple values in one row, or am I mistaken? Because that is not what I want, I want (if f.e. the user checked 3 categories checkboxes) to create 3 rows in the lookup table.
Thanks in advance for your time seeing my question.
$categories = array(1,2,3,4);
$bookId = 5;
foreach ($categories as $categoryId) {
$data = array(
'book_id' => (int)$bookId,
'category_id' => (int)$categoryId
);
$query = "INSERT INTO `lookup` SET ";
$fields = array();
foreach ($data as $field => $value) {
$fields[] = "`$field` = '$value'";
}
$fields = implode(', ', $fields);
$query .= $fields;
mysql_query($query);
}
You can build up an insert using implode to insert many rows. Something like this:-
<?php
$Category = 123;
$Books = array(1,2,3,4,5,6,7,8,9,10);
$sql = "INSERT INTO book_category_link(NULL, category_id, book_id)
VALUES ($Category".implode("),($category", $Books).")";
?>
Or if you want to use the existing tables to get the ids then something like this:-
<?php
$Category = (123, 456, 789);
$Books = array(1,2,3,4,5,6,7,8,9,10);
$sql = "INSERT INTO book_category_link(NULL, category_id, book_id)
SELECT NULL, categories.id, books.id
FROM books
CROSS JOIN categories
WHERE books.id IN (".implode(",", $Books).")
AND categories.id IN (".implode(",", $Category).")";
?>
It's really simple. First you insert the the book into the books table and then get the ID of it. Let's say for this example it is the ID 5.
Lets say you have the following categorie id's from the checkboxes: array(21, 42, 64);
Now you can construct a query like this to insert them into the lookup table:
INSERT INTO `lookup` (book_id, category_id') VALUES (5, 21), (5, 42), (5, 64);
No, you can't insert into multiple tables in one MySQL command. You can however use transactions.
INSERT ...
SELECT LAST_INSERT_ID() INTO #mysql_variable_here;
INSERT INTO table2 (#mysql_variable_here, ...);
INSERT INTO table3 (#mysql_variable_here, ...);
if you want to add multiple rows inserted then u can use the syntax
INSERT INTO table (col1, col2) VALUES ('value', 'value'), (value, 'value');
The very basic idea is to iterate a loop on the categories submitted and run an insert query containing category ID and book ID into the lookup table.
$bookID= $_POST['bookid'];
foreach ($categories as $category) {
mysql_query("INSERT INTO lookup(bookid,categoryid) values($bookID,$catetory)");
}
I am using Php to insert values into MySQL table.
What i am trying to do is:
There are three columns that i have to check. 'namel1', 'namel2' and 'namel3'.
Conditions:
If '$name' does't exist in any of the three column then put value in 'namel1'.
If '$name' exist in 'namel1' then put value in 'namel2' and if 'namel2' contains the value then put it in 'namel3'.
My current MySQL query to insert name and image path is this i want to modify it to meet above conditions:
$chk_img_db = mysql_query("select * from cvapptable where img_path='$cvh_myimg_url'");
if(mysql_num_rows($chk_img_db)<1) {
mysql_query("insert into cvapptable(namel1,img_path) values ('$name','$cvh_myimg_url')");
}
I unable to get any solution from web.
Please help. Thank you.
It's not easy to find on the net because it's a situation you shouldn't get yourself into.
You should consider normalizing the table.
Instead of having a table with the columns:
cvapp: id | img_path | namel1 | namel2 | namel3
Consider changing it to two tables:
cvapp: id | img_path
names: id | cvapp_id | name
To then select every name, you just do a query like so:
SELECT name
FROM cvapp INNER JOIN names on cvapp.id = names.cvapp_id
WHERE <condition>
That way, you can have as many names as you want, and it's much easier to insert a new one:
INSERT INTO names (cvapp_id, name) VALUES (56, "Name 1");
INSERT INTO names (cvapp_id, name) VALUES (56, "Name 2");
INSERT INTO names (cvapp_id, name) VALUES (56, "Name 3");
you can try self join and search column of you tables
I have two tables:
contacts
phonetypes
In my add action, i populate a dropdown box from the phonetypes table (which has only 1 column, namely phone_type).
My contacts table has the fields: l_name, f_name, phone_type and number.
I have the dropdown's displayField as phone_type. Based on the selection in the dropdown I try to insert the phone_types field in the contacts table, but it inserts the id from the phonetypes table. But I want to insert the values and not the id...
Any help is appreciated.
My view code:
echo $this->Form->create('Contact');
echo $this->Form->input('last_name', array('type'=>'text', 'size'=>10));
echo $this->Form->input('first_name');
echo $this->Form->select('phonetypes.phone_type',array('phone_type'=>'phone_type','options'=>$phone_type,'default'=>'phone_type'));
echo $this->Form->input('phone_number');
echo $this->Form->end('Save Entry');
The better question is, if you are not using an ID for the primary key in the phone types table, why even use the database, why not just use a static array? If you want to use the database, you should ad the ID column and store the ID in the contacts table that references the phone type. Then to get the drop data you would do the following:
$this->set('phone_types', $this->PhoneType->find('list));
Then in the view, the form field will look like:
echo $this->Form->input('phone_type', array('options'=> $phone_types));
If you do NOT want to use the ID in the table, then just eliminate the table and set up a static array:
$this->set('phone_types', array('Home' => 'Home', 'Cell' => 'Cell', 'Work' => 'Work'));