How to insert multiple selectbox item in one column - php

I have a select box which have multiple item select facility
<select multiple="" class="form-control" name="mul[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Here select box item generate dynamically from another table.so item amount can be increase or decrease.for this reason i cant use set data type.
Now i want to insert selected value in my database table.
MY table look like
id name item
1 first mul[] value
2 second mul[] value
I want to insert selected item in DB Table column named item.
Also i want to retrieve every row data.
view like
id name item
1 first 1,2,3
2 second 2,4
I tried
$select_value=$_POST['mul'];
$sql="insert into mytable (`id`, `name`, `item`) VALUES (null, 'Hallo',$select_value)";

Use php impload function.
http://www.w3schools.com/php/showphp.asp?filename=demo_func_string_implode
In your case it will b like
$select_value=implode(", ", $_POST['mul']);
$sql="insert into mytable (`id`, `name`, `item`) VALUES (null, 'Hallo',$select_value)";
Then insert it.. :)
Try this.. i hope it helps you

This will automatically changes array to string, with comma:
$select_value = join($_POST['mul'],',');

'implode' of php is the solution:
echo implode(",",$_POST['mul']);//here $_POST['mul'] = ['1','2','3']
It will output string "1,2,3", insert it your table.
Here is more info about implode implode
Also ,if you want to retrieve records from DB table using your option values then FIND_IN_SET() function of sql will be useful , the query will be :
SELECT * FROM mytable WHERE FIND_IN_SET('option_value',`item`) <>0

Related

Linking foreign keys between tables

I have two tables: TEMA e SOTTOTEMA.
In TEMA I have, as primary key, IDtema which is auto-increment.
I want it to be foreign key in the sottotema table and I wrote, in phpmyadmin, where I have my db,
ALTER TABLE sottotema ADD FOREIGN KEY (IDtema) REFERENCES tema (IDtema)
It doesn't give me errors, but the foreign key doesn't work.
I have predefined themes in a select option, and depending on the theme you choose, you can insert a sub-theme yourself.
<select id = "tema" name = "tema">
<option hidden></option>
<option value = "Animali"> Animali</option>
<option value = "Cucina"> Cucina </option>
<option value = "Sport"> Sport </option>
<option value = "Musica"> Musica </option>
<option value = "Cinema"> Cinema </option>
<option value = "Letteratura"> Letteratura </option>
</select></br>
<div id = "sottotema" style = "display:none">
<p id = "titolosottotema"> Sottotema </p>
<input type = "text" placeholder="Scrivi un sottotema" id = "st" name = "st"/>
</div>
All this obviously is inside a FORM and everything works, except for inserting the IDtema as a foreign key, in the sottotema table.
I report only the data entry queries in the db, but in my php code there is something else written, including the connection to the db obviously
<?php
$sottotema = $_POST['st'];
$query = "INSERT INTO sottotemi (nomeSottotema) VALUES ('$sottotema')";
$result = mysqli_query($mysqli, $query);
if (!$result){​​​​​​
echo "errore 1";
}​​​​​​ else {​​​​​​
$query2 = "INSERT INTO blog (titoloBlog,nomeSottotema,nomeUtente,sfondo, font, colorefont) VALUES ('$titoloblog','$sottotema',(SELECT nomeUtente FROM utentiregistrati WHERE nomeUtente = '$nomeutente'),'$sfondo','$font','$colore');";
$result2 = mysqli_query($mysqli, $query2);
if(!$result2){​​​​​​
echo 'errore 2';
}​​​​​​
?>
In the db I have already entered my predefined themes, so the idtema, primary key, is already associated with a specific theme (eg 1 - Animali, etc.).
Please help me I'm desperate !!!!!
For the foreign key to work you need to specify the foreign table identifier in the INSERT operation, otherwise the row would be orphan form the start. Instead of INSERT INTO sottotemi (nomeSottotema) VALUES ('$sottotema') you'll need to find identifier (IDtema) to the foreign table (tema) and also provide it in the INSERT operation as follows (NOTE this is a different format of the INSERT statement that consumes the results of a SELECT statement instead of using the VALUES() version):
INSERT INTO sottotemi
(nomeSottotema, IDtema)
SELECT
'$sottotema', T.IDtema
FROM tema AS T
WHERE T.nome = '$tema'

Value from table to <select> -> <option>

How I can insert values from database to <select> -> <option> in HTML?
Example:
I have table with ID_class and name of class. And I would like to user can choose <option> with value name of class.
<select>
<option>VALUE FROM TABLE</option>
...
</select>
I work with PDO and jQuery.
It's not obvious where you're getting stuck, but here are some snippets to help out.
First of all, your select needs a name and options need a value, so that the selected value can be accessed on the server side.
<select name='chooser'>
<option value='name-1'>...</option>
<option value='name-2'>...</option>
</select>
On the server side, your query should look something like this using PDO:
$insertData = $con->prepare('
INSERT INTO your_table
VALUES(
DEFAULT,
:name,
)
');
// the value of $_POST['chooser'] here is the value of the selected option (e.g. "name-2")
$insertData->bindValue('name', $_POST['chooser'], PDO::PARAM_STR);
$insertData->execute();

Avoid Duplicate IDs in PHP

EDIT: Question edited to be exact after Marcus reply
I am trying to practice library management and my page is for order where a book can be ordered as many time but same book should not be selected in two different selects on one page. On order page, I have multiple select dropdowns for book values coming from same database:
<select name="user">
<option value="1">Tony</option>
<option value="2">Gary</option>
<option value="3">Martin</option>
<option value="4">Austin</option>
<option value="5">Mark</option>
</select>
<select name="book[]">
<option value="1">Math</option>
<option value="2">Geography</option>
<option value="3">Science</option>
<option value="4">Spanish</option>
<option value="5">English</option>
</select>
<select name="book[]">
<option value="1">Math</option>
<option value="2">Geography</option>
<option value="3">Science</option>
<option value="4">Spanish</option>
<option value="5">English</option>
</select>
<select name="book[]">
<option value="1">Math</option>
<option value="2">Geography</option>
<option value="3">Science</option>
<option value="4">Spanish</option>
<option value="5">English</option>
</select>
And adding them in database table which has ID as auto increment for record and bookID to store book id. I am doing it with:
$userID = $_POST['user'];
foreach($_POST['book'] as $key=>$item_eid){
$bookID = intval($_POST['book'][$key]);
mysql_query ("Insert INTO user_books (bookID, userID) values ('$bookID', '$userID' )") or die(mysql_error());
}
I dont want to have two record of same book ID. In short, I want to avoid duplicate entries on bookID. I have tried "INSERT IGNORE INTO" but it did not work. Also, I want to show an error if duplicate entries are selected instead of just ignoring. Any thoughts on it?
Edit: Table structure:
CREATE TABLE IF NOT EXISTS user_books
(
ID int(11) NOT NULL AUTO_INCREMENT,
bookID int(11) NOT NULL,
userID int(11) NOT NULL,
added timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
)
ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;
The column needs to be UNIQUE. Right now there is no constraint on the column which is allowing it to have duplicate values. Change the column to UNIQUE:
ALTER TABLE user_books ADD UNIQUE (bookID);
This query will fail, however, if you already have duplicate values in the bookID column. If you don't care about the (automatic) removal of duplicate entries, use the following query instead:
ALTER IGNORE TABLE user_books ADD UNIQUE (bookID);
This will keep the first found entry of any duplicates, and delete the rest, ie. Imagine having 5 entries with bookID 100. The aforementioned query will keep the first entry with bookID 100, and delete the remaining 4 automatically.
Then you can use INSERT IGNORE INTO thereafter.

How to insert data from a table to another table

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]'

How to indentify which data is selected by user in selectbox (data is union of two tables)?

I have a need of display two diff. tables's data in one selectbox. so i use following query:
<select name="account[]" id="account" class="input" multiple size="3">
<option value="">Select</option>
<?php
global $mysqli;
$query = "SELECT `number` as num, `id` from `table1` where `account_id`='".$_SESSION['account_id']."' UNION ALL SELECT `number` as num, `id` from `table2` where `account_id`='".$_SESSION['account_id']."'";
$result = $mysqli->query($query) or die($mysqli->error);
while($row5 = $result->fetch_array(MYSQLI_ASSOC)){
?>
<option value="<?php echo $row5['id'];?>"><?php echo $row5['num'];?></option>
<?php }?>
</select>
so all data are fetch according to my need. But now i have a problem.
When i inserted user selected data, how to indentify that user selected data is from table1 or table2 ?
I have a some ideas:
(1) Create two diff. queries in selectbox and bind predifined value.
exa.:
<option value="table1.9999"><?php echo $row5['num'];?></option>
<option value="table2.2222"><?php echo $row5['num'];?></option>
(2) insert table2's id(here id is automatic inserted id primary key) maually.
like: id=10000
so i check that if id>10000 then it is from table2.
But the upper things is like petch. so what is the alternavites for do upper things.
Any ideas are welcome.Thanks in advance.
SIDE NOTE: table structure is good according to my need. so i cannot change whole table structure. But i can add fields in tables.
Just add a column to your SELECT statement, that specifies whether the data comes from table1 or table2:
SELECT `number` as num, `id`, "Table1" as source
from `table1`
where ...
UNION ALL
SELECT `number` as num, `id`, "Table2" as source
from `table2`
where ...
Then you can use this source column to determine if the record is from Table1 or Table2.
If you need a unique identifier across both tables, just concatenate the id with the table number. Something like this should work:
SELECT `number` as num, `id` & "-Table1" as uniqueid
...
Let's say you separated this functionalities, so now you have a php backend with delivers the query result as a json string
optionlist.php
global $mysqli;
$optionlist=array();
$query = "SELECT `number` as num, `id`, 'Table1' as source
from `table1`
where `account_id`='".$_SESSION['account_id']."'
UNION ALL
SELECT `number` as num, `id`, 'Table2' as source
from `table2`
where `account_id`='".$_SESSION['account_id']."'";
$result = $mysqli->query($query) or die($mysqli->error);
while($row5 = $result->fetch_array(MYSQLI_ASSOC)){
$optionlist[] = $row5;
}
echo json_encode($optionlist);
now in your mainfile you have an empty select box and a js to fill it up
main.html
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
jQuery(document).ready(function() {
jQuery.ajax({ url: 'optionlist.php'
dataType: 'json';
}).done(function(jsonlist) {
for(var i=0;i<jsonlist.length;i++) {
theoption=jsonlist[i];
jQuery('#account').append('<option rel="'+ theoption.source +" value="'+theoption.id+'">'+ theoption.num '</option>';
}
});
</script>
<select name="account[]" id="account" class="input" multiple size="3">
<option value="">Select</option>
</select>

Categories