I am developing a classroom website.
There is a form to insert student profile/data into the database table student.
This site has 5 class groups, IDs as id= 1, 2, 3, 4, 5.
Inserting data to database table succeeds.
But I have a question: Each student must be under classroom 1 and 2, so when we insert data I need the database to automatically create two database results for each times, both results all field are same data except classgroup_id, i mean one result must classgroup_id=1 and second result must be classgroup_id=2, i need mysql automatically generated this for when add each student... any idea.?
this is my table structure
student_id (int) AI
name
email
classgroup_id (default value=1)
user_id
this is my php code for insert data to table
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "'");
thanks... i have only a medium level php knowledge
ClassGroups are in table or just static numbers?
If they are just static numbers, then i think simpliest way is to do another insert with duplicated data. For example for both rows should be:
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "'");
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "', classgroup_id =2");
If they are in some table, then you can do insert with one insert(code will be shorter) but with different insert syntax then yours. For example your ClassGroup table is just ClassGroups:
$this->db->query("INSERT INTO " . DB_PREFIX . "student (user_id, name, email, ClassGroup_id)
select " . (int)$this->user->getId() . ", '" . $this->db->escape($data['name']) . "', '" . $this->db->escape($data['email']) . "',ClassGroup_id from ClassGroups where ClassGroup_id=1 or ClassGroup_id=2");
But i think it should be best if you do for each data(student, ClassGroup) different table and do relation table for them, it will not duplicate data and table student will be faster if you gather data from it by primary AI key and not by varchar type column name.
You don't need PHP to do this... Pure SQL pseudosolution:
INSERT INTO student (student_id name, email) SELECT name, email from student where classgroup_id = ?
If you construct a fiddle and leave a comment as to where to find said fiddle, I'd be happy to tweak the query for your specific needs.
In order to avoid duplicate entries for students, you can make another table in which you link the students to their classes.
For example:
Students
student_id (primary key)
name
email
user_id (if still needed...)
Classgroups
classgroup_id (primary key)
classgroup_name
StudentsPerClassgroup
student_id (foreign key)
classgroup_id (foreign key)
You have to keep the record in temporary table first and then do the operations .. try it
//get last insertId
$last_insert_id = $this->db->insert_id();
$new_id = $last_insert_id +1;
$query = "CREATE TEMPORARY TABLE tmp SELECT * FROM yourtable WHERE your_primary_key = $last_insert_id;
UPDATE tmp SET your_primary_key= $new_id,classgroup_id = 2 WHERE your_primary_key = $last_insert_id;
INSERT INTO yourTable SELECT * FROM tmp WHERE your_primary_key = new_id";
$this->db->query($query);
Hope you get some idea
Related
i have a form where you can select category and will return products that are in this category
$query = $this->db->query("SELECT id, name FROM " . DB_PREFIX . "shared_products_product WHERE category = '" . (int)$id . "' AND status != 2");
Result
Array
(
[0] => Test 1
[1] => Test 2
[2] => Test 3
)
Than you can select only Test 1 and Test 2 to insert in different table
$this->db->query("INSERT INTO " . DB_PREFIX . "shared_products_view SET product_id = '" . (int)$product_id . "', shared_product_id = '" . (int)$shared_product_id . "', category_id = '" . (int)$cat_id . "'");
When i run 1st query how will i get result that still not inserted into shared_products_view for current category_id ?
you need to join table and check if value is already existing
Like this
$query = $this->db->query("SELECT `spp`.id, `spp`.name
FROM " . DB_PREFIX . "shared_products_product `spp`
LEFT JOIN " . DB_PREFIX . "shared_products_view `spv` ON `spp`.`id`=`spv`.shared_product_id
WHERE category = '" . (int)$id . "' AND status != 2 AND `spv`.shared_product_id IS NULL");
When you run your second query, the INSERT, the row will be added, unless you have an error. One thing that comes to mind is you seem to insert integers as strings.
It is better to use PDO and bindValue() and explicitly state it is an integer.
If I understand you right, you want to know if the INSERT succeeded. (Is that correct?)
In that case check the result of your command $this->db->query("INSERT ...").
You didn't mention what database handle $this->db is, but I expect it will return false on failure.
I highly recommend you study this hands-on guide first before proceeding:
https://phpdelusions.net/pdo
I have a requirement to update a record if it exists else insert it. I already tried previous related answers but those are not sufficient
I have a table name with data_meta
meta_id | token | meta_key | meta_value
1 1 terms_conditions terms conditions content
2 1 is_config_enable 1
3 2 terms_conditions terms conditions content
I have to update based on token & meta_key.. For same token meta_key doesn't repeat..
My Insert Query
"INSERT INTO data_meta (token, meta_key, meta_value)
VALUES (" . $token . ", '" . $key . "', '" . $value . "')";
My Update Query
"UPDATE data_meta SET meta_value = '" . $value . "' WHERE meta_key = '" . $key . "' AND token=" . $token ;
MySQL provides the REPLACE INTO statement just for this.
REPLACE INTO data_meta (token, meta_key, meta_value) VALUES ( x, y, z );
For this to work , the combination of (token, meta_key) should be either primary key, or you need to create a unique index for the combination of (token, meta_key)
Clearly your meta_id is your auto-increase index.
You forgot to use it in your update query. That query won't work without it, the update needs a WHERE condition.
Once you grasped this, the solution is obvious. So how does it work?
If you don't know the meta_id you insert, if you do know it you can update. It's as simple as that.
create uniqe index on (token, meta_key) If not exists:
create unique index data_meta_tm on data_meta(token, meta_key);
Query:
"INSERT INTO data_meta (token, meta_key, meta_value)
VALUES (" . $token . ", '" . $key . "', '" . $value . "')
ON DUPLICATE KEY UPDATE meta_value = VALUES(meta_value)";
I have the following query:
REPLACE INTO `oxarticles`
SET
OXID = '10-1010',
oxartnum = '10-1010',
oxtitle = 'Dummy',
oxprice = '10.000000',
oxstock = '100',
importstatus = 1"
This works so far as expected, but the fields I do not specifiy, are just overwritten with ' ' / empty string. From what I read, should this syntax work identically like the UPDATE-command.
Am I missing something? How can I prevent that fields are replaced with '' ?
Edit 1
Just to clarify, I can't just use UPDATE. I am setting a flag (importstatus) to 0 before every run and during the import to 1. After the import finishes, I delete all articles, which are still on status 0.
// Just for the compeletion, here is the PHP-snippet:
while (!feof($this->handle))
{
$row = fgetcsv($this->handle, 0, ";");
$sSql = "REPLACE INTO oxarticles SET "
. " OXID = '" . $row[0] . "', "
. " oxartnum = '" . $row[0] . "', "
. " oxtitle = '" . $row[1] . "', "
. " oxprice = '" . str_replace(",", ".", $row[4]) . "', "
. " oxstock = '" . str_replace(",", ".", $row[5]) . "', "
. " importstatus = 1";
// $sSql = "UPDATE oxarticles SET oxtitle ='" . $row[1] . "', oxprice='" . $row[4] . "', oxstock='" . $row[5] . "' WHERE oxartnum ='".$row[0]."'";
$this->db->execute($sSql);
}
From the mysql documentation:
REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted. See
Section 13.2.5, “INSERT Syntax”.
In other words, the row is being deleted and then inserted, hence your old values aren't staying intact. Perhaps you could select the original row first, and feed those values back in where appropriate.
You query will replace old data into new data if you do not provide data for a field it will set to null . If you do not want to loose your data just want to update field use on duplicate key update.
If did't found any match it will insert new row
If found it will replace data if provide
INSERT INTO table (id,a,b,c,d,e,f,g) VALUES (1,2,3,4,5,6,7,8) ON
DUPLICATE KEY
UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;
How to insert the same id in different tables at a time in one table. it is a primary key and autoincrement and in another table. It is a foreign key at a time. I have to insert in both the tables using OpenCrat.
$this->db->query("INSERT INTO "
. DB_PREFIX . "xyz
SET
boutiques_id = '" . (int)$this->customer->getId() . "',
boutique_customer_id = '" . $this->db->escape($data['boutique_customer_id']) . "',
ordered_date = '" . $this->db->escape($data['ordered_date']) . "',
'");
$this->db->query("INSERT INTO "
. DB_PREFIX . "abc
SET
boutiques_id = '" . (int)$this->customer->getId() . "',
firstname = '" . $this->db->escape($data['firstname']) . "',
lastname = '" .$this->db->escape($data['lastname']). "',
}
in abc table it is a primary key and autoincrement whereas in second table it is foreign key.
After an insert query use this $this->db->getLastId(); to get last inserted id of that table, by this u can add this to another table.
The ghetto way assuming there is a unique constraint on boutique_customer_id and ordered_date would be:
INSERT INTO abc (boutiques_id, firstname, lastname)
SELECT boutiques_id, 'John', 'Smith'
FROM xyz
WHERE boutique_customer_id = 123
AND ordered_date = 2015-05-01
Or else you would need to use a transaction/programmatically get and set that foreign key value. Either way I wouldn't try to set the primary key when initially inserting. Finally unrelated to your question, try looking at using an ORM.
I have two values from URL. This is those,
$_GET['a'] // this variable has a email address
$_GET['b'] // this variable has a code to activate my account.
I am trying to create UPDATE query using these two values, but problem is these two values belong to two different tables. email has in contact table and active column has in user table.
This is my code so far:
$q = "UPDATE tutors SET active = NULL
WHERE (active='" . mysqli_real_escape_string($dbc, $_GET['z']) . "')
LIMIT 1";
This code is working for me. but I need to check both values in WHERE clause. Can anybody help me to build this query?
UPDATE :
$q = "UPDATE tutors t, contact c SET t.active = NULL
WHERE t.active = '" . mysqli_real_escape_string($dbc, $_GET['z']) . "'
AND c.email = '" . mysqli_real_escape_string($dbc, $_GET['y']) . "'
AND t.contact_id = c.contact_id
LIMIT 1";
Thank you.
At a guess: something like this would work if your tutors and contacts are linked via a contact_id in the tutors table.
<?php
$q = "UPDATE tutors T, contacts C SET T.active = NULL
WHERE T.active = '" . mysqli_real_escape_string($dbc, $_GET['z']) . "'
AND C.email = '" . mysqli_real_escape_string($dbc, $_GET['a']) . "'
AND T.contact_id = C.contact_id"
but... I would need more information about your database schema to make this a more precise answer.