How to Convert MySQL Column Value From Array to String - php

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

Related

PHP: Automated data insertion to two connected tables from one form

So, I've been looking for a solution to my case, but I've kept finding only partial and not quite solving-the-matter kind of answers.
First, let me describe what I'm trying to achieve.
In my database I have two tables: PLACES and PLACES_CATEGORIES which are connected by a third table PLACES_A_CATEGORIES in an entity many to many. That is because a PLACE can be characterised by one or more CATEGORIES (but it can also have no CATEGORIES at all).
I want to add data send in one form to two tables: PLACES and PLACES_A_CATEGORIES. The user has all the categories listed with checkboxes and he may (but doesnt have to) check one or more of them.
I automated the display of those checkboxes so it reacts accordingly to changes in database (like adding or removing categories). This part works just fine, but let me show the code for you as it may be useful in solving the real issue:
$query = "SELECT name FROM places_categories";
$result = $connection->query($query);
$category_no = $result->num_rows;
echo "Categories of places:";
for ($j = 0; $j < $category_no; ++$j)
{
$category = $result->fetch_assoc()['name'];
echo '<br><input type="checkbox" id="'.$category.'" name="places_categories" value="'.$category.'"><label for="'.$category.'">'.$category.'</label><br>';
}
So, let's return to the problem. I want to:
always add data (only one row) to the table PLACES
add as many rows of data to the table PLACES_A_CATEGORIES as many checkboxes have been checked
So, let me now show you how I've tried to solve the matter and below I'll explain what and why I've done.
if ($everything_OK==true)//Hurra, everything is ok, lets add the place to the database
{
mysqli_query($connection, "SET NAMES utf8");//need it for special characters
//Adding multiple rows of data to database
$query = "SELECT name FROM places_categories";
$result = $connection->query($query);
$category_no = $result->num_rows;
for ($j = 0; $j < $category_no; ++$j)
{
$category[$j] = $result->fetch_assoc()['name'];
if ($_POST['places_categories'] == $category[$j])
{
//counts number of records in table PLACES
$query1 = "SELECT name FROM places";
$result1 = $connection->query($query1);
$places_no = $result1->num_rows;
$places_no += 1;
//looks for category_id in table places_categories where the name matches the current value from form
$query2 = "SELECT category_id FROM places_categories WHERE name='$category[$j]'";
$result2 = $connection->query($query2);
$what_category_id = mysqli_fetch_array($result2);
$connection->query("INSERT INTO places_a_categories VALUES ('$places_no', '$what_category_id')");
}
}
if ($connection->query("INSERT INTO places VALUES (NULL, 0, 0, 0, '$name', '$wysokosc', '$zajawka', '$zatloczenie', '$data_dodania', '$data_edycji', '$szer_geo', '$dlu_geo', '$tytul', '$opis', '$adres', '$tresc')"))
{
echo "Test!";
}
else
{
throw new Exception($connection->error);
}
}
Okay, explanations:
The part which inserts data to the table PLACES works just fine. It
adds data to the database according to what user has added in a form.
No help needed here.
Because of the before-mentioned automation of
table CATEGORIES I want to check how many of categories actually are
in the database. The first part of the code was supposed to do this.
with instruction FOR I assign every existing category to an array with a value equal to the name of the category in the database
then with instruction IF I want to add ass many rows of data to the table PLACES_A_CATEGORIES as many checkboxes have been checked
first value $places_no equals to id of the place which is being added to another table
second value $what_category_id looks for category_id in table PLACES_CATEGORIES where the name matches the current value got from the checkbox
And what are the results? Data is added to the table PLACES with no problem at all. But there is nothing added to the second table. Furthermore, I get no error message of any kind. It's probably some stupid error I just can't see... Any ideas? What have I done wrong?

Undesired data insertion to database

An employee can claim the amount of money spent on official duty from the employer.
I am working on a website in which after a staff filled in the official duty activity (details), staff is then shown a dynamic form in which they can add/remove transport/meal/hotel claim, depending on how long (days) it takes to complete the duty. Here is the design I came up with.
Here is the output . TransportID 8 & 9 should be in the same row as activityID 11. Is there a way to insert > 1 primary keys into a field?
foreach ( $_POST["dates"] as $index=>$date ) {
$origin = $_POST["origins"][$index];
$destination = $_POST["destinations"][$index];
$cost = $_POST["costs"][$index];
//Insert into transport table
$sql_transport1 = sprintf("INSERT INTO tbl_transport (Date, Origin, Destination, Cost) VALUES ('%s','%s','%s','%s')",
mysql_real_escape_string($date),
mysql_real_escape_string($origin),
mysql_real_escape_string($destination),
mysql_real_escape_string($cost));
$result_transport1 = $db->query($sql_transport1);
$inserted_transport_id1 = $db->last_insert_id();
//Insert into transport_mainclaim table
$sql_transport_mainclaim1 = sprintf("INSERT INTO tbl_transport_mainclaim (claimID, transportID) VALUES ('%s','%s')",
mysql_real_escape_string($inserted_mainclaim_id1),
mysql_real_escape_string($inserted_transport_id1));
$result_transport_mainclaim1 = $db->query($sql_transport_mainclaim1);
$all_transport_id = implode(",",$inserted_transport_id1);
//Insert into mainclaim table
$sql_mainclaim = sprintf("INSERT INTO tbl_mainclaim (activityID, transportID, IC) VALUES ('%s','%s','%s')",
mysql_real_escape_string($inserted_activity_id),
mysql_real_escape_string($all_transport_id),
mysql_real_escape_string($_SESSION['IC']));
$result_mainclaim = $db->query($sql_mainclaim);
$inserted_mainclaim_id = $db->last_insert_id();
}
I have tried using $all_transport_ID = implode(",",$inserted_transport_id1);to separate IDs with comma but failed to do so.
Is the database structure wrongly designed? Please guide me as I want to get this right.
Sorry I couldn't comment on your post because of reputation but I think you gave the wrong link. Your code is operating on table tbl_transport whereas the link you gave shows table named tbl_mainclaim.
Regardless of that,you are trying to insert two integer values 8 and 9 in the column of integer type on the same row as activity id with int value 11. How are you planning to store that?
UPDATE: I think the way which you are implementing this code is wrong. If i am correct your variable $inserted_transport_id is an array whereas in this line you are treating it as a variable. $inserted_transport_id1 = $db->last_insert_id();
As you are using implode which combines array into a string , here you are treating it as an array.
$all_transport_id = implode(",",$inserted_transport_id1);
So I am not sure what you are trying to implement. Its not clear what you are trying to do with that foreach loop for whole SQL.
And if your application permits, you can remove tbl_transport_mainclaim,tbl_meal_mainclaim,tbl_hotel_mainclaim and directly assign foreign key of the tables tbl_transport,tbl_hotel,tbl_meal which references to the respective columns on the tbl_mainclaim.
I might be able to help you with your further explaination about what you are trying to implement in this page.
Don't escape $all_transport_id; do escape (or verify that they are numeric) the values in $inserted_transport_id1.
In the future, do this to help with debugging:
echo $sql_mainclaim;

Get data from exploded values

I have been trying to get data from exploded values, but I am failing miserably and I am completely clueless despite all the researching I've been doing.
This is how the code looks like:
$array = explode(",", $hos['prop_owner']);
list($a) = $array;
$gu = $db->prepare("SELECT * FROM users WHERE user_id = :id");
$gu->execute(array(':id' => $a));
$dau = $gu->fetch();
echo $hos['prop_name']."<br><small>";
if(end($array)){
echo "<a href='/user/view/".$dau['user_id']."' style='color:#".$dau['user_colour']."'>".$dau['user_name']."</a></small><br>";
} else {
echo "<a href='/user/view/".$dau['user_id']."' style='color:#".$dau['user_colour']."'>".$dau['user_name']."</a>,";
}
Currently, the database field $hos['prop_owner'] contains the values "2,20" which are IDs of users (this field can potentially contain more IDs in the future). What I want to do is get all the user data from the exploded values, in this case 2 and 20, and then echo the information out in order as well.
Re-explanation:
I have a field in my database called prop_owner which is supposed to contain an unlimited number of user IDs, seperated by comma. Format: 1,2,3,4.
I want to take the value from this field, then somehow separate the user IDs and separately retrieve the usernames and echo them out.
Example result: Darren, Eva, Miles, Lisbeth
I hope I explained myself good enough to understand where I am trying to go with this.
Thanks in advance!
First of all the query will be like
SELECT * FROM users WHERE user_id in (2,20)
You need the data of both the users so the query will return all the data of all the ids that are being passed here..
You can directly pass here but you need to take care of security... or may be you can check how to pass values securely in such queries ...

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.

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

Categories