Inserts into MySQL table going onto separate rows - php

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

Related

Updating one table with a value from another table in pecee-pixie

I am using the pecee-pixie library.
I am trying to update a column from one table based on values from another table however when i ran my query i simply updated the values with a text table2.values rather with the actual values.
This is my query:
$table1 = $query_builder->table('table1');
$table1
->leftJoin("table2", "table1.id", "=", "table2.join_id")
->whereNotNull("table2.values")
->update(['table1.values' => 'table2.values']);
I would mind using raw queries but i'd prefer if i didnt have to write the whole query raw. Anybody has any ideas?

SQL Database approach - I need your suggestion

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.

Storing multiple values in one MYSQL field

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.

array type of question

I'm trying to figure out a way to make a small "table" style system in php for about 10 data rows. Because it requires constant editing, I want to replace my mysql system for something in php directly.
The data is 10 rows of:
id
first name
last name
I give the php file the id and want to pull out the first name and last name.
I tried using a associative array, but that turned into a coding mess as my syntax was all over the place.
How can I set this one up properly so i can edit the data easily in a single place and get first and last name of a row by its $id?
edit - example:
id fname lname
1 john ter
2 mark laken
3 peter lars
4 vlad morch
Basically, how do I set that info above up in php such that I can add new rows without too much trouble and the code will still work, and such that it is possible to output the fname and lname from a $_GET of an id value...
Hope that makes sense!
I'm not understanding why you wouldn't want to store constantly changing data in the database, but here is how I would hardcode it:
$data = array(
'id01' => array(
'firstName' => 'Eric',
'lastName' => 'Smith',
),
'id02' => array(
'firstName' => 'John',
'lastName' => 'Turner',
),
...
);
If you were returning this data in an ajax call I'd do it along these line
echo json_encode($data[$id]);
Of course you should also test if the value in $id is in your data array.
I'm not totally sure I understand what you're looking for, but if you want to be able to edit something inline and save it on form input blur, you will have to look beyond PHP and into an AJAX solution. You will likely still want to back this with a database as PHP scripts don't have a continuous runtime, so you can't read all the data into memory and change it directly in memory through user interaction. So what you'll do is read all the data from the DB into a form, then using a little ajax, you will be able to save the form data back to the database everytime a value is changed.

php checkbox update, insert, delete mysql records

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.

Categories