Split comma-separated input box values and then store in database - php

I have a text input box where you can type tags seperated by commas. I want to store these tags separately in a table but I have no idea how to do that.
I know I have to seperate the tags after they are posted so I now have this
$array = explode(',', $_POST['tag']);
Is this a good start and how do I have to go on after that?

Creating array from your input field as in your code
$array = explode(',', $_POST['tag']);
Create a mysql multi insert query using foreach loop
simillar to this:
$id=mysqli_insert_id($con);//get your project id here
$sql="";
foreach($array as $tag_name){
//modify below to add $id along with $tag_name
$sql.="('{$id}','{$tag_name}'),"; // you need to remove last comma else it will throw mysql error
}
if($sql!=""){
//rtrim to remove last ',' from string.
$sql=rtrim($sql,',');
$sql="INSERT INTO tags_tbl (project_id,tag) VALUES {$sql};"`
}
now use mysqli_query($con,$sql) to insert values in database

Related

Adding multiple fields separated by comma into database PHP

Thank you in advance for any help given! I'm very new to PHP and would love some advice/help! i want many id fields separated by comma to be inputted into a database separately with the same resource id variable.
Find a link to a picture here! Here, a user enters many ids for the name, and only one ID for the resource, I would like all ids to be entered into the database with the same resource id beside it
//so this is creating the array to split up the ids
$array = explode(",", $id);
//finding length of array
$length = count($array);
//now we want to loop through this array, and pass in each variable to the db
for ($x = 0; $x < $length; $x++) {
$sqlinsert= "INSERT INTO ids_to_resources (id, resource_id)
VALUES ($id [$x], $resource_id)"
$result = mysqli_query($dbcon,$sqlinsert);
}
I think it could be something like this code above but it doesnt seem to be working for me...
In short i want a user to enter many ID fields and only one resource field, and for this to be inputed into the database separately. I hope this makes sense!
Thanks again for any help given!
To only answer your question and not questioning your database schema. Have a look at the following code:
$ids = explode(",", $id);
$inserts = array();
foreach ($ids as $id) {
$inserts[] = "($id,$resource_id)";
}
$query = "INSERT INTO ids_to_resources (id,resource_id) VALUES " . implode(',', $inserts) . ";";
You can insert multiple rows in one sql query by seperating them with a comma. The code should generate a query like this:
INSERT INTO ids_to_resources (id,resource_id) VALUES (1,4),(2,4),(3,4);
You would be better off creating a separate table which has a new row for each record... the columns would be ID, NINJA_ID, RESOURCE_ID. Then insert it that way. Put an Index on RESOURCE_ID. This way you can easily search through the database for specific records, updating and deleting would be a lot easier as well.
But if you insist on doing commas,
$comma_ids = implode("," $array);
You don't have semicolon after this line and you musnt't have a space between $id and [$x]
$sqlinsert= "INSERT INTO ids_to_resources (id, resource_id)
VALUES ($id[$x], $resource_id)";

using coma seperated values and inserting it into database in one shot

I have a page where there are check boxes getting loaded dynamicaly so i dont know the number of check boxes (maximum of 50) and out of those check boxes users can select any number between 1 to 50 of checkboxes and can submit the form and on the action page i need get the values of all the checkboxes and insert them to database after checking for unoqueness like this
FIRST PAGE (FORM)
<?php while($the_DEATA_ARE_90=mysqli_fetch_array($getDOCS_30all)){ ?>
<div class="This_LISy_Lisy678" id="MAINDIV_DELEE<?=$the_DEATA_ARE_90['dcid']?>">
<div class="CHeck_IS_BOC">
<input type="checkbox" name="selecteddocx[]" value="<?=$the_DEATA_ARE_90['dcid']?>x<?=$the_DEATA_ARE_90['name']?>" id="check_docname<?=$the_DEATA_ARE_90['dcid']?>"/>
on the action page i am having this code
$selecteddocx = (isset($_POST['selecteddocx']) ? $_POST['selecteddocx'] : '');
$doocx = array();
$docxid = array();
foreach($_POST['selecteddocx'] as $value){
$str = explode("x",$value,2);
$doocx[] = $str[0];
$docxid[] = $str[1];
echo=implode(",", $doocx); // i need to print this for some reasons
echo implode(", ", $docxid); // i need to print this for some reasons
i am having this query to insert the coma sepertaed vales into database
i am converting the values of checkboxes into coma seperated values
$shaeredata=mysqli_query($conn,"insert into docs (dcid,pid) values ('$dcid','$pid')");
i i know i can insert the values into database in one shot like
$shaeredata=mysqli_query($conn,"insert into docs (dcid,pid) values ('$dcid','$pid'),('$dcid2','$pid'),('$dcid3','$pid'),('$dcid4','$pid')");
but i dont know how to do this as i am having the values in coma seperated (please note pid is same)
if checking of dcid can be done per pid then it will be great what i mean is thet insert only is dcid is not shared with pid (dcid already exists for that pid)

how to insert multiple of values in a single field in mysql

i want to insert multiple values into a single field, i don't know how to achieve this i'm using a long-text data type field. And also tell me how to fetch these a value only one separate value at a time.
Insert Mutliple values in a single Field:
For inserting the flat no's in a single field, use implode and the values separated by comma.
$r=implode(",",$available);
$insert=mysql_query("insert into flatdetails(available) value ('$r')")
For retrieve the values from database use, explode to separate out all the values..
For Retrieve the values using
$i=explode(",",$r);
<?php
$select_tbl=mysql_query("select * from flatdetails",$conn);
while($fetch=mysql_fetch_object($select_tbl))
{
$r=$fetch->available;
$i=explode(",",$r);
echo $i[0]."</br>";
}
?>
As far as my knowledge goes, MySQL does not have any data types that could help your use case. Well, actually it has a "set" data type, but it only allows for up to 60-something members if I recall correctly.
You can try using BLOB as your column type and store serialized data in there (i.e. JSON, protocol buffers).
However, I would recommend that you re-evaluate your DB's design. You're breaking the first normal form, and it's a sign that you're doing something wrong.
Use json_encode to encode the content and then store it in db field and when you retrieve the value then use json_decode ( Same like wordpress )
Its not a good idea to store multiple values into a single column. If you really want to do that store your strings as coma separated. And when reading back from database you can use php explode function. Php explode
I'll give you another option to store
Assume your strings are str1,str2,str3
First if you use your method it will be like below. which is not a good idea i think.
I think following is the good method
I think you should use Array and Implode functionality of PHP. Create an array and implode it by comma. For example---
Suppose you have three fields then get values of these input fields and make an array.
$arr = array(); // Declare an array
$arr[] = $_POST['FirstField'];
$arr[] = $_POST['SecondField'];
$arr[] = $_POST['ThirdField'];
// As more as you have input fields.
Then make it a string like
$insertValue = implode(',',$arr); // This will create a string containing all your fields values and you can save it in single field.
Just use this single variable in your insert query.
Hope this will help you.
db connect file with PDO save as config.php
<?php
$dbhost = 'localhost';
$dbname = 'clsrepair';
$dbuser = 'root';
$dbpass = '';
try {
$db = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection error: ".$e->getMessage();
}
?>
then in you desire file:
if(isset($_POST['your_form']))
{
try {
$leavingEquipment = implode(', ', $_POST['leavingEquipment']);
$statement = $db->prepare("INSERT INTO orderForm (orderNo,leavingEquipment) VALUES (?,?)");
$statement->execute(array($_POST['orderNo'],$leavingEquipment));
$success_message = "Order's has been inserted successfully.";
}
catch(Exception $e) {
$error_message = $e->getMessage();
}
}
try adding additional field to your apartmat table wher you writte for example 1 for rented (not available)
0 for available
query all apartments accordint to 0 and you got your list of all available appartments.

cast text field to array in mysql select query

I have a table in MySQL database. In that table there is a text field called 'selection' that hold numbered values, separated by a pipe char (example: 44|5|23|546|.....). I also have a php array: $values = array(63,35,7,5);
I need to refer to the 'selection' field as array of options (separated by '|') and select only the rows that contain at least one of the number in $values array.
I hope i explained my problem accurately enough, because my English is very poor... Thanks.
If you want to get row that contains at least one number in $values array, the SQL looks like this:
$values = array(63,35,7,5);
foreach ($values as $value) {
$sql = "select * from tablename where selection like '%{$value}|%' or '%|{$value}%'";
}
If the values in the array are in the appropriate order for search already, you can build your query with something like this:
$selection_searched = implode('|', $values);
$query = "SELECT * FROM your_table WHERE selection = '$selection_searched'";
Beware that you would probably want to validate the array $values fisrt, to check if it isn't empty, etc. Check out the manual for: http://php.net/implode

Insert Comma Separated Values into MYSQL + Additional Form Data

I have a form that allows users to tag an image, choose a location from a drop-down, & upload the image. The tagging takes place by allowing multiple values, separated by commas, to be entered into a field.
This code is successfully inputting the comma delimited list to individual rows:
$categories = $_POST['bib'];
$categories = explode(",", $categories);
foreach($categories as $category) {
$category = trim($category); // Remove possible whitespace
$sql = "INSERT INTO athletes (bib) VALUES ('%s')";
$sql = sprintf($sql, mysql_real_escape_string($category));
mysql_query($sql);
}
However, it is not adding the additional content (location from drop-down list & image filename). For query purposes I need to be able to use both the 'bib' tag and the 'location' to be attached to images to allow users to search.
Before implementing the comma-separated option, this code was working to insert all of the data:
mysql_query("INSERT INTO `athletes` VALUES ('$id', '$bib', '$race','$new_file_name')") ;
So, basically I'm trying to merge the functionality of the two.
You need to use MySQL's UPDATE statement to update data in an existing row.

Categories