Insert Comma Separated Values into MYSQL + Additional Form Data - php

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.

Related

speed up text based many-to-many updating

TL;DR;
Is there a faster way of updating m:m records looping one by one, when ids are not known.
This is about using tags.
On the front-end, I've got forms that use text based input to list and update tags.
When the form is submitted a user record needs to have the tags updated by deleting and creating records in the m:m table
There are multiple tag types, so there are multiple tag input fields, but all are stored in same table.
because the current system is using the tags as string, once the form passes the input data back to the server, it is a CSV string.
The plan (plan because I'm updating from storing as a string) is to
join all tags $tags = implode(',', array_merge($tagset1, $tagset2));
get individual tags $update_tags = explode(',',$tags);
delete all tags for user in m:m user_tag table
loop through $update_tags as $tag_name
find tag_id from $tag_name
add record to m:m user_tag table for user_id and tag_id combination
in the past I've seen issues where the deleting happens, but some un-handled error causes updates not to go through. I suspect this can be mitigated by implementing rollbacks.
While the tag count for updating is fairly low on both sides (user will have less than 15, and there are less than 1000 tags total) I'm concerned about the looping aspect of this, as past experience has been a great indicator that sql within a loop is a great thing to avoid.
this is what I ended up doing ...
it's a bit different from what I intended.
I explode the string and compare to the view result (as array) and do two array_diff operations, one to find deletes and one to find insert.
there is one query for each type of operation, lookup user tags, insert user tags, delete user tags.
The only duplicate is the query that looks up tag ids based on the tag name, in which case it's not looping anyway.
public function update_tags($user_id, $tags)
{
// convert tags string to array
$update_tags = explode(',',$tags);
// find user's tags
$user_tag_view_reslt = $user_tag_view->find(array("user_id = ?", $user_id));
// reduce to array with tag names only
$user_tag_view_reslt = array_column( $user_tag_view_reslt, 'tag_name');
$remove_tags = array_diff($user_tag_view_reslt, $update_tags);
$insert_tags = array_diff($update_tags, $user_tag_view_reslt);
$this->remove_user_tags($user_id, $remove_tags);
$this->insert_user_tags($user_id, $insert_tags);
}
public function remove_user_tags($user_id, $tags_array)
{
$tags_string = "'".implode("','",$tags_array)."'";
$tag_model = new \Model\Tag();
$rows = $db->exec("SELECT tag_id FROM tag WHERE tag_name in($tags_string) ");
$delete_tag_ids = implode(',',array_column($rows,'tag_id'));
// check if there are any rows to insert before doing so
if($delete_tag_ids != ''){
$exec = $db->exec("DELETE FROM `user_tag` WHERE user_id = $user_id AND tag_id in ($delete_tag_ids);");
}
}
public function insert_user_tags($user_id, $tags_array)
{
$tags_string = "'".implode("','",$tags_array)."'";
$tag_model = new \Model\Tag();
$rows = $db->exec("SELECT tag_id FROM tag WHERE tag_name in($tags_string) ");
$insert_tag_ids = implode(',',array_column($rows,'tag_id'));
$sql_vals = array();
foreach($rows as $row){
array_push($sql_vals,"($user_id, ".$row['tag_id']." )");
}
$sql_vals_str = implode($sql_vals,",");
// check if there are any rows to insert before doing so
if($insert_tag_ids != ''){
$exec = $db->exec("INSERT INTO `user_tag` (user_id, tag_id) VALUES $sql_vals_str;");
}
}
requires PHP 5.5 or grater (due to array_column), it also won't work without adjusting and accommodating for the models whose code is not shown

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)

If multiple hardware not found, delete all values from list

I am trying to do the following:
If ID is not found inside the array 'hardware', delete all values where ID doesn't exist from the hardware array.
The issue I encountered is that, where I am able to delete one value at a time using the following:
foreach ($this->hardware AS $hardware){
if(!in_array($hardware['ID'],$hardwareList)){ // checks if hardware id is not on the hardware list
$query = 'DELETE FROM hardware_map WHERE ID='.$hardware['ID'];
$db->setQuery( $query );
$result = $db->loadResult();
}
}
It will not remove multiple values, if I delete all of them at once inside the textarea field.
<textarea id="hardwareTextArea" name="hardwareTextArea"><?php
foreach($this->hardware AS $hardware){
echo $hardware['name']."\n";
?></textarea>
Any help is appreciated on how to delete multiple values from the list at once if I delete all the values from the textarea.
You can first find the IDs that you want to remove them, then use one query by using IN:
DELETE FROM hardware_map WHERE ID IN (id1,id2, ...)

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

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

text input (seperated by comma) mysql input as array

I have a form where I am trying to implement a tag system.
It is just an:
<input type="text"/>
with values separated by commas.
e.g. "John,Mary,Ben,Steven,George"
(The list can be as long as the user wants it to be.)
I want to take that list and insert it into my database as an array (where users can add more tags later if they want). I suppose it doesn't have to be an array, that is just what seems will work best.
So, my question is how to take that list, turn it into an array, echo the array (values separated by commas), add more values later, and make the array searchable for other users. I know this question seems elementary, but no matter how much reading I do, I just can't seem to wrap my brain around how it all works. Once I think I have it figured out, something goes wrong. A simple example would be really appreciated. Thanks!
Here's what I got so far:
$DBCONNECT
$artisttags = $info['artisttags'];
$full_name = $info['full_name'];
$tel = $info['tel'];
$mainint = $info['maininst'];
if(isset($_POST['submit'])) {
$tags = $_POST['tags'];
if($artisttags == NULL) {
$artisttagsarray = array($full_name, $tel, $maininst);
array_push($artisttagsarray,$tags);
mysql_query("UPDATE users SET artisttags='$artisttagsarray' WHERE id='$id'");
print_r($artisttagsarray); //to see if I did it right
die();
} else {
array_push($artisttags,$tags);
mysql_query("UPDATE users SET artisttags='$artisttags' WHERE id='$id'");
echo $tags;
echo " <br/>";
echo $artisttags;
die();
}
}
Create a new table, let's call it "tags":
tags
- userid
- artisttag
Each user may have multiple rows in this table (with one different tag on each row). When querying you use a JOIN operation to combine the two tables. For example:
SELECT username, artisttag
FROM users, tags
WHERE users.userid = tags.userid
AND users.userid = 4711
This will give you all information about the user with id 4711.
Relational database systems are built for this type of work so it will not waste space and performance. In fact, this is the optimal way of doing it if you want to be able to search the tags.

Categories