Updating one column in multiple rows - php

I'm trying to update values in a table that looks like this:
+----+-------------+
| Id | Value |
+----+-------------+
| 1 | title |
+----+-------------+
| 2 | description |
+----+-------------+
| 3 | email |
+----+-------------+
| 4 | keywords |
+----+-------------+
I would like to update the value if the PK already exists, otherwise insert a new row.
submit.php:
include('../../include/config.php');
if($_POST['settings']){
$title=$_POST['title'];
$description=$_POST['description'];
$email=$_POST['email'];
$keywords=$_POST['keywords'];
$test=$db->query("UPDATE `settings` SET `value` = '$title' WHERE `id` =1, SET `value` = '$description' WHERE `id` =2,SET `value` = '$email' WHERE `id` =3, SET `value` = '$keywords' WHERE `id` =4;");
if($test){
echo "good";
}else{
echo "bad";
}
}
UPDATE:
To whoever reading this question now, don't use this structure to store your website settings. and I don't recommend using the query either because it is vulnerable to SQL injection

Consider this example...
SELECT * FROM user;
+---------+------+
| user_id | name |
+---------+------+
| 1 | X |
| 2 | B |
| 3 | C |
+---------+------+
UPDATE user
SET name = CASE user_id WHEN 1 THEN 'A'
WHEN 2 THEN 'J'
WHEN 3 THEN 'K' END;
SELECT * FROM user;
+---------+------+
| user_id | name |
+---------+------+
| 1 | A |
| 2 | J |
| 3 | K |
+---------+------+

This query can in fact be done with a single statement in Mysql as long as you have a unique index or primary key on your Id field.
INSERT INTO `settings` (`id`,`value`) VALUES (1,?),(2,?),(3,?),(4,?)
ON DUPLICATE KEY UPDATE `value`=VALUES(`value`);
See the documentation of INSERT ... ON DUPLICATE KEY at https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Related

MySQL issue on INSERT ... SELECT ON DUPLICATE KEY UPDATE and LAST_INSERT_ID()

In MySQL, I have INSERT ... SELECT ON DUPLICATE KEY UPDATE query as below:
$sql = "INSERT INTO user ( name
, mobile
, email
, sex
, username
, password
)
SELECT u.name
, u.mobile
, u.email
, u.sex
, u.username
, u.password
FROM import_user u
WHERE u.name <> '' AND u.mobile <> ''
ON DUPLICATE KEY UPDATE
user_id = LAST_INSERT_ID(user_id),
name = VALUES (name),
mobile = VALUES (mobile),
email = VALUES (email),
sex = VALUES (sex)";
UPDATE:
This is the result from above query.
select user_id, role_id, name,sex, mobile from user;
+---------+---------------------------+--------+-------------+
| user_id | name | sex | mobile |
+---------+---------------------------+--------+-------------+
| 131 | Name 1 | Male | 435345345 |
| 132 | Name 2 | Male | 43543534 |
| 133 | Name 3 | Male | 45645644 |
| 134 | Name 4 | Male | 5345 |
| 135 | Name 5 | Male | 5465475 |
| 136 | Name 6 | Male | 56456546 |
+---------+---------------------------+--------+-------------+
Now I want to create an array of the user_id of either the insert or the update the records.
So, my expecting array should be
$uid = [131,132,133,134,135,136]
I tried it something like this, but it doesn't work for me. That mean I can get only one id.
$stmt = $pdo->prepare($sql);
$stmt->execute();
$uids[] = $pdo->lastInsertId();
So, May I know Is there a way to create an array from the effected user ID of the above query running?
DEMO:
CREATE TABLE test (id INT AUTO_INCREMENT PRIMARY KEY,
category INT,
value INT,
UNIQUE (category, value) );
CREATE TRIGGER tr_ai
AFTER INSERT ON test
FOR EACH ROW
SET #ids_array := CONCAT_WS(',', #ids_array, NEW.id);
CREATE TRIGGER tr_au
AFTER UPDATE ON test
FOR EACH ROW
SET #ids_array := CONCAT_WS(',', #ids_array, NEW.id);
SET #ids_array := NULL;
INSERT INTO test (category, value)
VALUES (1,11), (2,22);
SELECT * FROM test;
SELECT #ids_array;
id | category | value
-: | -------: | ----:
1 | 1 | 11
2 | 2 | 22
| #ids_array |
| :--------- |
| 1,2 |
SET #ids_array := NULL;
INSERT INTO test (category, value)
VALUES (1,111), (2,22)
ON DUPLICATE KEY
UPDATE value = NULL;
SELECT * FROM test;
SELECT #ids_array;
id | category | value
-: | -------: | ----:
1 | 1 | 11
3 | 1 | 111
2 | 2 | null
| #ids_array |
| :--------- |
| 3,2 |
-- do not reset #ids_array
INSERT INTO test (id, category, value)
VALUES (1,4,44), (22,2,22)
ON DUPLICATE KEY
UPDATE value = NULL;
SELECT * FROM test;
SELECT #ids_array;
id | category | value
-: | -------: | ----:
1 | 1 | null
3 | 1 | 111
2 | 2 | null
22 | 2 | 22
| #ids_array |
| :--------- |
| 3,2,1,22 |
db<>fiddle here

How to display name instead of id if records are in one table?

I am using CodeIgniter. I have an employee table and records are
id |firstname | lastname | mobileno | created_by
2 |mnb | nbgfv | 1452145625 | 1
3 |jhg | uhgf | 1452365478 | 2
4 |poi | ijuy | 1458745632 | 2
5 |tgf | tgfd | 1458745254 | 2
6 |wer | qwes | 1523654512 | 2
Now My issue is in the column created_by. When I am displaying the record of any id value then I am getting the output like
id |firstname | lastname | mobileno | created_by
3 |jhg | uhgf | 1452365478 | 2
But my expected output
id |firstname | lastname | mobileno | created_by
3 |jhg | uhgf | 1452365478 | mnb nbgfv
I have to display the name of created_by
I tried only this query.
$get_single_emp_record = array('id' => 3);
$this->db->where($get_single_emp_record);
$query = $this->db->get('tbl_employee');
$result = $query->row();
if($result)
{
return $result;
}
else
{
return 0;
}
I have a hint (maybe this can give solution in your problem).
Try query like this :
SELECT
t1.id , t1.firstname , t1.lastname ,t1.mobileno,
CONCAT(t2.firstname ," ",t2.lastname ) AS createby
FROM tbl_employee AS t1
JOIN tbl_employee AS t2 ON t2.id = t1.created_by
WHERE t1.id = '3'
With above query you no need create temporary table or other additional tables.
I Tested it. >>>
http://sqlfiddle.com/#!9/e693cf/2/0
Thanks
you will have to create another table maybe tbl_creator which will have the id, creator_name then in your query you will perform a Join operation

How to compare data with another table's data before deleting the record in MySQL

I have this db called Enrolment where all the students will be added with batch and course. stud_id, course_id, and batch_id are referring to the other table with the fk.
enrolment
+----------+---------+-----------+----------+
| enrol_id | stud_id | course_id | batch_id |
+----------+---------+-----------+----------+
| 1 | 1 | 2 | 1 |
| 2 | 5 | 3 | 2 |
| 3 | 4 | 5 | 3 |
+----------+---------+-----------+----------+
Before I delete the student record in the student table, i want to compare the stud_id in the students table with the stud_id in the enrollment table. If it matches, do not delete the student. Or some kind of message to say this record is linked with the enrollment table, or something.
If it matches i want to run this $sql = "DELETE FROM students WHERE student_id = $id ";
students
+---------+------------+-----------+
| stud_id | first_name | last_name |
+---------+------------+-----------+
| 1 | John | Doe |
| 2 | Susy | Roberts |
| 3 | John | redneck |
+---------+------------+-----------+
Please help!!
It can be achieved using NOT IN
DELETE FROM students
WHERE student_id NOT IN (SELECT stud_id
FROM enrolment) AND student_id = $id
It can be achieved using NOT EXISTS
DELETE FROM students
WHERE NOT EXISTS(SELECT NULL
FROM enrolment
WHERE stud_id = $id) AND student_id = $id
you want to run a query like
$sql = SELECT COUNT(1) FROM enrolment WHERE stu_id = $id
Then check the contents for the number returned if > 0 then error.

php get records from mysql only when dosent have duplicated value

mysql like that
=======================
| id | name |
| 1 | jhon |
| 2 | sarah |
| 3 | suzan |
| 4 | jhon |
| 5 | ahmed |
=======================
my expected result is
sarah
suszan
ahmed
want to remove jhon or any value name are duplicated
i tried to use
SELECT * FROM table WHERE id={$id} GROUP BY name
but it's only displaying the duplicated values
Use HAVING
SELECT `name` FROM `table` GROUP BY `name` HAVING COUNT(`name`) = 1
To get unique values, you can use below :
// This will return unique values
SELECT DISTINCT `name` FROM `table`;

PHP MySQL consolidate column where other column has duplicates

I have a MySQL table that has three columns, the first is a unique key (INT(11) AUTO_INCREMENT), the next is an indexed value (VARCHAR(255)) and the third is a description (TEXT). There are duplicate values in the second column, but each row has a different description. I want to remove all rows where the second column is duplicated but append each description of the same indexed value to the first instance the value, and breaking string with a semicolon and space.
For example, my table looks like this:
cid | word | description
------------------------------
1 | cat | an animal with wiskers
2 | cat | a house pet
3 | dog | a member of the canine family
4 | cat | a cool person
I want to change the table to look like this:
cid | word | description
------------------------------
1 | cat | an animal with wiskers; a house pet; a cool person
3 | dog | a member of the canine family
I'm not adverse to using a PHP script to do this, but would prefer MySQL. The table has over 170,000 rows and would take PHP a long time to loop over it.
SQL:
select `cid`,`word`,group_concat(`description` SEPARATOR '; ') as `description` from `test_table` group by `word`;
Ok.. you can copy all the data into another table, and rename it then..
insert into `test_new` (`cid`,`word`,`desc`) (select `cid`,`word`,group_concat(`desc` SEPARATOR '; ') as `description` from `test_table` group by `word`);
mysql> describe `test_new`;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| word | char(10) | YES | | NULL | |
| desc | text | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> select * from `test_new`;
+------+------+---------------------+
| id | word | desc |
+------+------+---------------------+
| 1 | cat | desc1; desc2; desc4 |
| 3 | dog | desc3 |
+------+------+---------------------+
2 rows in set (0.00 sec)
As was mentioned before, you can create a new table and copy the info, you can also do it in two steps, but only if thereĀ“s no problem with modifying the old table:
UPDATE tableOld AS N1, tableOld AS N2
SET N1.description = concat(concat(N1.description,"; "),N2.decription))
WHERE N2.word = N1.word
insert into tableNew (cid,name,description)select * from tableOld group by word

Categories