I have the folowing array called $words
Array
(
[0] => Array
(
[token] => dwA
[pos] => *DII.7,8*
)
[1] => Array
(
[token] => nTr
[pos] => *DI.5,9*
)
[2] => Array
(
[token] => dwA
[pos] => *DI.2,8*
)
[3] => Array
(
[token] => nTr
[pos] => *DI.2,8*
))
I want to insert it with the following :
foreach ($words as $value)
{
$word = $value['token'];
$attestation = $value['pos'];
$insert="INSERT INTO Examples (Word, Attestation) VALUES ('$word', '$attestation')
mysql_query($insert) OR die(mysql_error());
}
The table 'Examples' has a key called ID with auto increasement;
the field word is 'unique'
what I want is that in the field 'Attestation' the values are added each time the 'word' is the same
so the result should be the following:
Id word Attestation
1 dwA *DII.7,8*, *DI.2,8*
2 nTr *DI.5,9*, *DI.2,8*
so I tried to add a 'on duplicate key' phrase
foreach ($words as $value)
{
$word = $value['token'];
$attestation = $value['pos'];
$insert="INSERT INTO Words2 (Word, Attestation) VALUES ('$word', '$attestation')
on duplicate key update Attestation =
";
mysql_query($insert) OR die(mysql_error());
}
but I can't figure out what I have to add after Attestation = so that the differents attestations are added one after the other, like for example : DI.5,9, DI.2,8
Or is the 'on duplicate key' not the correct way to do this?
Try this;
INSERT INTO Words2 (Word, Attestation) VALUES ('$word', '$attestation')
on duplicate key update Attestation = CONCAT(Attestation, ', ', '$attestation')
Although, it may a bit difficult to break those values apart later on. You may want to consider another table, so you can set up a one-to-many relationship.
Related
This question already has answers here:
fetch data primary key value as the index for the associative array
(2 answers)
Closed 4 years ago.
I have a table with items with a name and id. Here's some create table code:
CREATE TABLE items (
id INT,
name TEXT
);
INSERT INTO items VALUES
(1, "Flute"),
(2, "Guitar"),
(4, "Saxophone"),
(7, "Tuba"),
(5, "Xylophone"),
(14, "Triangle");
I want to perform a query on this grabbing all items:
$stmt = $db->prepare("
SELECT id, name FROM items
ORDER BY id ASC
");
$stmt->execute();
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
This creates an array that looks something like the below:
Array (
[0] => Array ([id] => 1, [name] => "Flute"),
[1] => Array ([id] => 2, [name] => "Guitar"),
...
[5] => Array ([id] => 14, [name] => "Triangle")
)
I want to access this array by key id. Something like:
echo $array["1"]; // "Flute"
echo $array["14"]; // "Triangle"
echo $array["7"]; // "Tuba"
Not necessarily exactly like the above, but in a way that I can print name from the array by using key id. Is something like this possible? To format the array created earlier.
You will need to create a new array and iterate over the old.
Something like:
$newArray = array();
foreach ($array as $item)
$newArray[$item['id']] = $item['name']
Is there a more efficient way of deleting multiple entities by id
$data = $this->request->data ['missing_lexicon_id'];
foreach ( $data as $id ) {
$missingLexicon = $this->MissingLexicons->get ( $id );
$this->MissingLexicons->delete ( $missingLexicon )
}
This should work
$this->MissingLexicons->deleteAll(['MissingLexicons.column IN' => $keys]);
Where $keys is an array with the ids to be deleted.
Most efficient way to delete multiple entities using deleteALL().
$this->MissingLexicons->deleteAll(['id IN' => $multiItemsArray]);
OR
$this->MissingLexicons->deleteAll(['id' => $multiItemsArray[]]);
MissingLexicons = Your Model name.
$multiItemsArray = Your deleted entities id
Read More Here
I have this query for a search form:
// General Query
$conditions = array(
'editore LIKE' => "%$e%",
'titolo LIKE' => "%$t%"
);
Now, if the user chooses fill some field (eg author, year, etc), I have:
if (isset($menu)&&$menu!='')
$conditions[]=array('classe LIKE' => "%$menu%");
Or:
if ($anno&&$anno2)
$conditions[] = array('anno BETWEEN ? AND ?' => array($anno,$anno2));
If the user chooses some tags for the book, I have:
$query_t = $CdBibliotem->query("SELECT codiceBiblio FROM cd_bibliotem WHERE codiceTematica IN (".implode(',', $fields).")");
$query_t = Set::classicExtract($query_t,'{n}.cd_bibliotem.codiceBiblio');
$tot=implode(',', $query_t);
$conditions[]=array('codiceBiblio IN (?)'=> "$tot");
This should work, but instead I don't know why, it gives me only the first record.
This is an example of debug a final query, where the user selects only 1 tag, and leaves the others fields empty:
Array (
[editore LIKE] => %%
[titolo LIKE] => %%
[0] => Array
(
[autori LIKE] => %%
)
[1] => Array
(
[codiceBiblio IN (?)] => 118729,118656,118645,118554,118534,118533,118532,118531,118530,118529,118528,118527,118526,118121,117632,117515,117040,116562,115851,115787,114613,114612,113545,113385,113142
) )
In this case, it gives me all the details of the first book (with id=118729), while it should gives me the details of all that books.
I have the following insert query:
$salarystuff = array('salary' => $salary, 'from_date' => $salary_from_date, 'to_date' => $salary_to_date);
$this->db->insert('salaries', $salarystuff);
The salary table has columns: emp_no| salary| from_date| to_date (I'm using the database available from dev.mysql.com.
But it gives me an error 1452 saying foreign key constraint. How do I reference to the key value in the other table to be able to insert into this table?
This is the error message:
Cannot add or update a child row: a foreign key constraint fails
(employees.salaries, CONSTRAINT salaries_ibfk_1 FOREIGN KEY
(emp_no) REFERENCES employees (emp_no) ON DELETE CASCADE)
INSERT INTO salaries (salary, from_date, to_date) VALUES
('1000000', '2012-12-27', '2013-01-16')
Thank you
edit: I'm trying the following
First I create the record in the employees table using this function:
function add_emp($firstname,$lastname,$gender,$date_of_birth,$jobtitle,$dept,$hiredate)
{
$data = array( 'first_name' => $firstname,
'last_name' => $lastname,
'gender' => $gender,
'birth_date' => $date_of_birth,
'hire_date' => $hiredate);
$this->db->trans_start();
$this->db->insert('employees', $data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
$msg = "Adding the new employee failed.";
return $msg;
}
else
{
$msg = "Successfully Added Employee.";
return $msg;
}
}
and then in another function I add the salary:
function add_salary($firstname,$lastname,$gender,$date_of_birth,$jobtitle,$dept,$hiredate,$salary, $salary_from_date,$salary_to_date)
{
$this->db->select('emp_no');
$this->db->from('employees');
$this->db->where('first_name', $firstname);
$this->db->where('last_name', $lastname);
$this->db->where('gender', $gender);
$this->db->where('hire_date', $hiredate);
$this->db->where('birth_date', $date_of_birth);
$this->db->limit(1);
$selected_employee = $this->db->get();
$salarystuff = array('emp_no' => $selected_employee, 'salary' => $salary, 'from_date' => $salary_from_date, 'to_date' => $salary_to_date);
$this->db->insert('salaries', $salarystuff);
}
both of which are in the model. Then in the controller I call both functions:
$employee_insert = $this->user->add_emp($firstname,$lastname,$gender,$date_of_birth,
$jobtitle,$dept, $hiredate);
$salarythings = $this->user->add_salary($firstname,$lastname,$gender,$date_of_birth,$jobtitle,$dept,$hiredate,$salary, $salary_from_date,$salary_to_date);
But I get an error because there is no value in the emp_no field...I think it might be the line:
$selected_employee = $this->db->get();
$salarystuff = array('emp_no' => $selected_employee,
My error message is:
Object of class CI_DB_mysql_result could not be converted to string
The problem is you are trying to insert into the salaries table, but you aren't specifying what employee the salary record is for. You would need to provide a value for the emp_no column that is in the employees table.
ETA:
Glad you posted more code - what you should do is modify your add_emp function so that it returns the id of the employee that was created (I'm assuming here that emp_no is and auto-increment column in your database). Like so:
function add_emp($firstname,$lastname,$gender,$date_of_birth,$jobtitle,$dept,$hiredate)
{
$data = array( 'first_name' => $firstname,
'last_name' => $lastname,
'gender' => $gender,
'birth_date' => $date_of_birth,
'hire_date' => $hiredate);
$this->db->trans_start();
$this->db->insert('employees', $data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
//$msg = "Adding the new employee failed.";
//return $msg;
return -1; // indicates failure
}
else
{
//$msg = "Successfully Added Employee.";
//return $msg;
return $this->db->insert_id();
}
}
Note that the code that calls add_emp will need to change a bit to look at the return value as an integer instead of a message now, but now you have the id of the employee and you can use that in your add_salary function instead of having to pass in all that other data, like so:
function add_salary($emp_no,$salary, $salary_from_date,$salary_to_date)
{
$salarystuff = array('emp_no' => $emp_no, 'salary' => $salary, 'from_date' => $salary_from_date, 'to_date' => $salary_to_date);
$this->db->insert('salaries', $salarystuff);
}
So the code to add an employee and their salary would be something like this:
$emp_no = add_emp([Your parameters]);
if ( $emp_no > 0 ) {
add_salary($emp_no, [other parameters]);
} else {
// Show some error message that the employee creation failed.
}
EDIT AGAIN:
If you ignore my advice above, the simple answer to why you are getting an error is because $selected_employee is a result set and not an actual employee number. You would need to change that code like so:
$selected_employee = $this->db->get();
$result = $selected_employee->result();
$emp_no = $result[0]->emp_no;
$salarystuff = array('emp_no' => $emp_no, 'salary' => $salary, 'from_date' => $salary_from_date, 'to_date' => $salary_to_date);
$this->db->insert('salaries', $salarystuff);
i'm thinking about this for days now and don't come to grasps (since i'm relativley new to MVC and CI). I'm not even sure whether this is an issue with MVC, MySQL or arrays.
Situation: 2 MySQL tables
Table data: id, title, list
Table values: id, name
Querying the data table results in an array like the following (excerpt):
[4] => Array
(
[id] => 3
[title] => Foo
[list] => 1,2,3,4,6,14
)
[5] => Array
(
[id] => 4
[title] => Bar
[list] => 2,6,9,12
)
The field list contains comma separated values that correspond to some IDs of the values table like
[3] => Array
(
[id] => 12
[name] => 'value12'
)
What I try to do for each row is:
take the list-values & explode it into an array
check with the result set from the values-table (via in_array() method)
return the name values of the IDs if
include it somehow into the main result set (e.g. as a 2-dimensional array):
[5] => Array (
[id] => 4
[title] => Bar
[list] => Array (
[0] => value6
[1] => value12
...
)
)
My naive approach so far was to
run a query on each of the 2 tables
compare the 2 result sets via in_array
My main problem (while trying to strictly separate model, controller and view): How can I include the name field from the values-table in the "main loop" of the data table result set?
if($q->num_rows() > 0)
{
$data[] = $q->result_array();
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
If I use the following (cumbersome) approach i naturally get a new item each time:
foreach ($q->result_array() as $row)
{
$data[]['id'] = $row['id'];
$data[]['title'] = $row['title'];
$data[]['list'] = $row['year'];
}
Since this is a MySQL database I see no way to do the explode and the comparison in SQL (with LIKE or something else).
Any hint, even a simple link to an info bit, is highly appreciated.
Thanks a trillion!
fab
There is a many-to-many relationship between lists and list values. The conventional way to model this in a relational database is to create a joining table. So I'd structure your schema like this.
lists : list_id, title
values : value_id, name
list_values : list_id, value_id
list_values is the joining table. It links lists with values.
To build a list you could have the following functions in your model
function build_list($list_id)
{
$list = $this->get_list($list_id);
$list->values = $this->get_list_values($list_id);
return $list;
}
function get_list($list_id)
{
$sql = 'select * from lists where list_id=?';
return $this->db->query($sql, array($list_id))->row();
}
function get_list_values($list_id)
{
$sql = 'select v.value_id, v.name
from list_values lv
join values v on v.value_id=lv.value_id
where lv.list_id=?';
return $this->db->query($sql, array($list_id))->result();
}