I've searched quite a bit for this but nothing has seem to to come up which is strange because I think it would be something that's something quite easy to implement. Basically I have a list of items which the user selects, what I want to do is update the values in the database according to the checkboxes selected basically the following scenarios:
The id assigned in the checkbox array is already in the DB and nothing needs to happen, or can be updated with the same value.
The id assigned in the checkbox array needs to be added to the database.
The id ISN't assigned in the checkbox array and therefor must be deleted from the DB.
has anyone got any code they worked with that does this?
EDIT:
the table is simple with two things being updated:
id_text and id_product
array coming from $_POST is:
Array ( [text] =>
Array ( [0] => 8 [1] => 1 [2] => 2 ) // the values that need to be inserted, updated, or deleted if they don't exist here.
[textValue] => ALL OF THEM
[id] => 33 // the 'id_product value'
[update] => update )
True, without any code or database squema is pretty hard to help, but if I understand correctly you can just:
Delete all values on DB.
Loop through the ids passed in POST or GET and insert them on DB.
Do an replace for every id passed. Replace behaves like insert i the entry does not exist and like update if it exists. I can not give you more details becuase I do not know your table structure
Delete all items that have a id that is not in your array. you can select those with "in":
...WHERE id_product NOT IN (1,3,5,8) AND......
you can easily generate this by using
$idCondition = 'id_product NOT IN (' . implode(',',$yourArrayName) . ')';
About REPLACE:
http://dev.mysql.com/doc/refman/5.1/de/replace.html
About IN:
http://www.webdevelopersnotes.com/tutorials/sql/tutorial_mysql_in_and_between.php3
EDIT: I just realized that some people might have objections on my deinition of REPLACE. What REPLACE actually does is deleting the row if it already exists and then do an INSERT.
Related
First of all, I'm happy to see people helping people here :D.
I got also a small issue sadly,
DB 1 contains:
UUID and much values.
DB 2 contains:
UUID and again many other values.
what I want is
[0] => Array
(
[UUID] => 96
[DB1 values]
[DB2 values]
)
i thought that will work with array_combine but that isn't true sadly because then i miss some db1 values
here database images:
--EDIT--
Your picture helped. You can handle that at the SQL Level
SELECT Login.*, Location.*
FROM Login
LEFT JOIN Location ON Login.UUID=Location.UUID
GROUP BY Login.UUID
Then the resulting data in PHP will already be correctly formatted.
Notice that I chose table Login to drive the query, could have also chosen the Location table. depends on the underlying structure
I have a variable in $_POST that looks like this:
[genre_id] => Array
(
[0] => 1
[1] => 3
)
I have a block of php code like this:
foreach ($_POST["genre_id"] as $key => $value) {
$genre_query = "UPDATE books_genres SET genre_id = $value WHERE book_id = $book_id";
$genre_result = mysqli_query($connection, $genre_query);
if ($genre_result && mysqli_affected_rows($connection) >= 0) {
echo("Genre Update: Sucess<br>");
} else {
echo("Genre Update: Fail<br>");
}
}
The table called books_genres is an junction table because of a many to many relationship. This means some of the $book_id will be duplicated. What's clearly happening is that each and every row with the specified book_id is being updated each time. Should I have another column in my books_genres table? Even then I'm not sure how I would reference that index? Or should I be writing the query different somehow?
The point of a junction table is that you don't need to update anything ever. It has the key from both tables right? The key isn't changing in your table is it? Unless you have denormalized your structures you really don't need to update junction tables except in pretty rare scenarios. If a given book was classified as "classical" and then gets reclassified as "horror" you would delete the classical entry and insert the horror entry. Perhaps posting the ddl and some sample data would help in explaining this.
What's clearly happening is that each and every row with the specified
book_id is being updated each time.
But that is exactly what you've asked MySQL engine to do!
Please remember, the SQL is a declarative language, not imperative.
So instead of showing the code, declare you intentions!
Tell yourself and us what you intend to update.
In other words, define a record set the "update" should hit.
Having that, you'd easily derive the "where" clause you need to narrow the operation.
I'm working within Laravel Spark and am inserting values into a MySQL table. I'm performing a series of inserts such as
DB::table('nameOfTable')->insert(['id' => $user['id']]);
DB::table('nameOfTable')->insert(['name' => $user['name']]);
The values are being inserted into the table properly, but each value is being placed on its own row. There's got to be a simple reason, but I haven't found any luck doing searches. Thanks in advance.
Each line of code you have in your question was designed to insert a row by itself. In order to insert more than one value in the same row (AKA insert various column values in the same row), all you have to do is include more values inside the array that is being passed to the insert function:
DB::table('nameOfTable')->insert(['id' => $user['id'],'name' => $user['name']]);
The previous line of code should work fine. I personally prefer to write the code as follows since it is cleaner to read for us mortals xD:
DB::table('nameOfTable')->insert(array(
'id' => $user['id'],
'name' => $user['name']
));
Hello everyone and thank you for viewing this question.
Since someone asked what i am doing this for, here is the answer:
An artist asked me to make him a web app to store all his new concerts etc.. Now, when it comes to add the Instruments, artists etc, i could have 10 instruments, or maybe 100.. Everything is set into a form.. Some data is fixed like location, time etc, but this other fields are added dynamically using DOM..
I am building a system in which the user set up a form to be stored on a database like:
Name,Surname,field_1
//Lets say that this is the "fixed" part of the form
//But the user should be able to add 'n' other fields with no limit
//Therefore my problem is that i would end up with a row made of, lets say,
//4 colums
//And another one of, maybe, 100 columns
//
//Then i will need to access these rows, and row one should have 4 cols, row two 100..
//This can't be done in a "traditional" way since each row should have the
//same amount of cols
//
//I thought to create a new table for each submission
//but this doesn't really make that much sense to me..
//
//Storing all the possible fields in a single one and then
//access them through an array ? That would require too much, even since my fields
//should have the possibility to be edited..
//Each field is a mixture of variables then, like
//field1:a=12,field2:b=18.. too complex
Any help would be very appreciated
I would go the one field approach. You could have three columns, Name, Surname, and field_values. In the field_values column, store a PHP serialized string of an array representing what would otherwise be your columns. For example, running:
array(
['col1'] => 'val',
['col2'] => 'val1',
['col3'] => 'val2',
['col4'] => 'val3'
)
through serialize() would give you:
a:4:{s:4:"col1";s:3:"val";s:4:"col2";s:4:"val1";s:4:"col3";s:4:"val2";s:4:"col4";s:4:"val3";}
and you can take this value and run it back through unserialize() to restore your array and use it however you need to. Loading/saving data within this array is no more difficult than changing values in the array before serializing it and then saving it to the field_values column.
With this method you can have as many or few 'columns' as you need with no need for a ton of columns or tables.
In this case I would personally create a new table for each user, with new row inserted for ever new custom field. You must have a master table containing table names of each user table to access the data within later.
I am currently planning out how a table will look in MYSQL database. I want to do something like the below, where plant1 and plant2 would be the columns, and then each of those plants would have characteristics assigned to them as you see below.
Is it possible to display info this way in MYSQL?
Array (
[plant1] => Array (
[image_url] => http://www.example.com/image1.png
[botanical_name] => Foo
[common_name] => Bar
),
[plant2] => Array (
[image_url] => http://www.example.com/image2.png
[botanical_name] => Foo
[common_name] => Bar
)
Well, i don't suggest that, but you can insert php array to that field and then parse it in php when you are getting data from database. So the content of that field would be like that:
$plant1 = array('plant1' => array('image_url' => 'http://www.example.com/image1.png', 'botanical_name' => 'Foo', 'common_name' => 'Bar'));
$plant2 = array('plant2' => array('image_url' => 'http://www.example.com/image2.png', 'botanical_name' => 'Foo', 'common_name' => 'Bar'));
You can insert $plant1 $plant2 to your mysql fields and then print it like this to get wanted result:
print_r(array_merge($mysql_plant1, $mysql_plant2));
Function array_merge connects arrays together.
You can do it storing as a serialized value (http://www.php.net/manual/en/function.serialize.php) but it's not a good idea.
For that you will have to create another table to store the caracteristics of each plant like:
**plants**
id_plant
name
**plants_ccharacteristics**
id_plant_characteristic
fk_plant
name
value
In that way you can store it properly.
As an extra point, that structure you want to store looks quite good for use NoSQL databases like MongoDB.
Your table design is flawed. What you should have is Plant being a row, with each item in the array being a column in the plants table.
If you need Plants to be a column in another table, then assign the first column of the plants table to be a unique, auto-incrementing key and then put that key in the column of the other table. Eg:
**Garden_Plants**
gp_key
gp_garden_id
gp_plant_id <-- p_id from Plants_Table
**Plants_Table**
p_id
p_botanical_name
p_common_name
p_image_url
you would have a table called plants, this would have a related table called plantDetails that has a referencing ID from the plant in question.
this would give 1 plant, with multiple references
This doesn't seem optimised for querying the database, however if you have a specific reason for doing it this way please let us know..
A more optimised solution:
Have a table called Plants, with fields ID, image_url, botanical_name, common_name.
Store all plants in that table. ID is a unique Identifier for that plant, probably set with autonumber so cannot be duplicated
If you need to store some kind of relationship between 2 plants, have a table called plant_relationships with fields for something like plant_ID_1 and plant_ID_2
You can then query your full list of plants directly, or query the relationships table to find plants related to other plants
If you want multiple values in one mysql field, i would suggest to put your information in one string before storing it in the database. Each substring need to be separated by a character that will not be used in the substrings.
$value1 = aaa
$value2 = bbb
$value3 = ccc
$valueAll = aaa:bbb:ccc
When you get the data out of the DB, you will need to split the string with the : or the other character selected.