How to handle column default value insert in SQLIte? - php

Below is the table structure. Insert query and Error message.
Table Structure
CREATE TABLE d0000ke_c_name (
c_name INTEGER PRIMARY KEY NOT NULL,
value VARCHAR(255) ,
sc_version INTEGER ,
sc_state INTEGER
);
Insert Query
$sql = "INSERT INTO d0000kv_c_name SELECT 3 AS 'c_name','manash' AS 'value' UNION SELECT 2,'ram' UNION SELECT 1,'rahim'";
$statement = $this->odb->prepare($sql);
if (!$statement) {
echo "\nPDO::errorInfo():\n";
print_r($this->odb->errorInfo());
}
$statement->execute();
Error message
PDO::errorInfo(): Array ( [0] => HY000 [1] => 1 [2] => table d0000kv_c_name has 4 columns but 2 values were supplied )

Your select SELECT 3 AS 'c_name','manash' AS 'value' UNION SELECT 2,'ram' UNION SELECT 1,'rahim' return 2 columns but your table d0000ke_c_name has 4 columns.
You have to declare the to be filled fields in your INSERT INTO:
$sql = "INSERT INTO d0000kv_c_name (c_name, value) SELECT 3 AS 'c_name','manash' AS 'value' UNION SELECT 2,'ram' UNION SELECT 1,'rahim'";
(In this case the fields sc_version and sc_state will get the default values.)
Or you should add the missing fields (e.g. "0, 0" for fields sc_version and sc_state) to your SELECT:
$sql = "INSERT INTO d0000kv_c_name SELECT 3 AS 'c_name','manash' AS 'value', 0, 0 UNION SELECT 2, 'ram', 0, 0 UNION SELECT 1,'rahim', 0, 0";

Related

PDO Error Code 1060 Duplicate column name for Inserting Record to table

I tried to Insert Record to table using PDO but its always return this error Error : Array ( [0] => 42S21 [1] => 1060 [2] => Duplicate column name '' )
and Sometimes inserting perfectly. I don't understand why its happened.
$data=array(
':business_title' =>$title ,
':business_cover' => $cover,
':business_logo' => $logo,
':business_location'=>$location,
':business_address' =>$address,
':business_contact' =>$phone ,
':business_email' =>$email ,
':business_url' =>$website ,
':business_category' =>$category ,
':business_subcategory' =>$subcategory ,
':business_keywords' =>$keywords ,
':business_full_desc' => $summary,
':business_amenities' => $amenities,
':business_socialurl' => $socialurl,
':business_token' => $token,
':user_id' => $userid
);
$query = "
INSERT INTO tablename
(business_title,business_cover,business_logo,business_location,business_address,business_contact,business_email,business_url,business_category,business_subcategory,business_keywords,business_full_desc,business_amenities, business_socialurl,business_token, user_id)
SELECT * FROM (SELECT :business_title,:business_cover,:business_logo,:business_location,:business_address,:business_contact,:business_email,:business_url,:business_category,:business_subcategory,:business_keywords,:business_full_desc,:business_amenities, :business_socialurl,:business_token, :user_id) AS tmp
WHERE NOT EXISTS (
SELECT user_id FROM tablename WHERE user_id = :user_id
) LIMIT 1
";
Your problem is occurring when you get duplicated values in the input data. When you SELECT a set of constant values, MySQL automatically generates column names which match the values. For example:
SELECT 'a', 'b', 'c'
yields the result:
a b c
---------
a b c
Now if you
SELECT 'a', 'b', 'b'
You get
a b b
---------
a b b
As a result, if you then attempt to
SELECT * FROM (SELECT 'a', 'b', 'b') AS tmp;
You will get a duplicate column error as there are two columns called b in the result set of the subquery.
You can work around this by giving the values column aliases, for example:
SELECT * FROM (SELECT 'a' AS a, 'b' AS b, 'b' AS c) AS tmp;
Output:
a b c
a b b
Demo on dbfiddle
Note that it's not clear that you need the complexity of the query that you have, you should be able to simply:
INSERT INTO tablename (business_title,business_cover,business_logo,business_location,business_address,business_contact,business_email,business_url,business_category,business_subcategory,business_keywords,business_full_desc,business_amenities, business_socialurl,business_token, user_id)
SELECT :business_title,:business_cover,:business_logo,:business_location,:business_address,:business_contact,:business_email,:business_url,:business_category,:business_subcategory,:business_keywords,:business_full_desc,:business_amenities, :business_socialurl,:business_token, :user_id
WHERE NOT EXISTS (
SELECT * FROM tablename WHERE user_id = :user_id
)
See for example this demo.

How to select two fields in to one filed

i have mysql table:
id | nameEng | NameRus
1 | Moscow | Москва
2 | London | Лондон
What i want is:
$result = array (
1 => array (id => 1, Name => "Москва"),
2 => array (id => 1, Name => "Moscow"),
3 => array (id => 2, Name => "London"),
4 => array (id => 2, Name => "Лондон")
)
Here is my query:
mysql_query("SELECT id, nameRus FROM citynames WHERE nameRus LIKE '%".$_GET['chars']."%'
UNION ALL
SELECT id, nameEng FROM citynames WHERE nameEng LIKE '%".$_GET['chars']."%' ORDER BY nameEng LIMIT 0, 10"
Query working but i want to optimize this query
$l = "like '%". $_GET['chars'] ."%'";
$sql = "(select `id` as `id`, `nameEng` as `name` from `citynames `) union (select `id` as `id`, `NameRus` as `name` from `citynames `) where `name` $l order by `id`;";

Insert multiple records in table if IDs do not exist in table

I want to add multiple records in a single table for multiple employees if the employees ID's do not already exist in the table. I have the employee IDs in array.
Array ( [0] => Array ( [EmployeeID] => 1 ) [1] => Array ( [EmployeeID] => 2 ) )
Now I have a table where I want to check that if record exist for employees then don't insert if record for certain employee don't exist then do the insertion.
e-g I have table.
INSERT INTO timesheet (employee_id,date_created) Values (1,2014-12-20),(2,2014-12-20) where employee_id NOT IN (1,2)
I know the above query I wrote is not right but that's why I want to ask how to insert in to table only if the records do not exist for that certain ID.
I'm using codeigniter, if you also know in codeigniter way that would be great. But simple mysql query help can also work for me.
Try to use NOT EXIST clause like this:
INSERT INTO timesheet (employee_id,date_created)
select 1,'2014-12-20'
from dual
WHERE NOT EXISTS (
SELECT *
FROM timesheet
WHERE employee_id in (1)
);
For multiple rows, you have to add dummy rows as following (or just execute previous statement in loop)
INSERT INTO timesheet (employee_id,date_created)
select * from (
select 1 AS ID,'2014-12-20'
union all
select 2 AS ID, '2014-12-20'
union all
select 3 AS ID, '2014-12-20'
) t
WHERE NOT EXISTS (
SELECT *
FROM timesheet
WHERE employee_id = t.ID
);
Demo Fiddle
Thanks to Spock for correction! :)
Start by making sure employee_id is a primary key and/or uniquely indexed. Then, you can use ON DUPLICATE KEY UPDATE
See this as a reference: MySQL - insert if doesn't exist yet
$data=Array ( Array ( 'EmployeeID' => 1 ),Array ( 'EmployeeID' => 2 ) );
echo '<pre>';
print_r($data);
foreach ($data as $key => $value) {
echo $str="INSERT INTO timesheet (employee_id,date_created) Values (1,2014-12-20),(2,2014-12-20) where employee_id NOT IN ($key)";
echo '<br>';
}

How to get row count as column

So I have a query like this
SELECT DISTINCT colB FROM tbl WHERE colA = "foo" LIMIT 0, 20
which gets me an array with max. 20 records where colA matches "foo", but without duplicate records. Each array entry contains an associative array that contains the value of colB, like
0 => array(
'colB' => 'some_value',
),
1 => array(
'colB' => 'other_value',
)
Can I also get the COUNT() for colB value? I mean this:
SELECT COUNT() as cbCount FROM tbl WHERE colA = "foo" AND colB = "some_value"
SELECT COUNT() as cbCount FROM tbl WHERE colA = "foo" AND colB = "other_value"
But included in the first query as another array field, like:
0 => array(
'colB' => 'some_value',
'cbCount' => 5,
),
1 => array(
'colB' => 'other_value',
'cbCount' => 2,
)
You need to use Group By with Count -
SELECT
colB, count(colB) as cbCount
FROM
tbl
WHERE
colA = 'foo'
GROUP BY
colB
LIMIT
0, 20
This query will fetch the first 20 rows, group them according to the distinct values of colB and give their count.
all you need to do is to use GROUP BY clause
SELECT colB,
COUNT(colB) AS cbCount
FROM tableName
WHERE colA = 'Foo'
GROUP BY colB

Calling SQL foreign key data with PHP

I need to get a better grasp on the process of manipulating and utilizing the SQL tables I need to make so I can continue figuring out exactly how I should make them and structure them to work.
If I have a table for shirts and another table for sizes and I use a foreign key on the shirts table to link to the sizes table to represent multiple options for that column. Do I only need to call on the shirts table in the PHP coding? If so how do I tell the PHP to gather whatever options are available for each row on the sizes table?
If in the table it has
vneck sizes,
scoop neck sizes
and I have it set where the vnecks only have s,m,l,1x and the scoop necks have xs,s,m,l,1x,2x,3x. How can I code the PHP to recognize the difference I have logically set in each row for that column?
It sounds like you actually need to have at least three tables, one for shirts, one for sizes , and one to relate shirts to sizes. There are any number of way you can use PHP to query the data, but most likely you would want to simply query using a JOIN to get data from all tables at the same time.
So perhaps something like this:
shirts table:
shirt_id (auto-incrementing primary key)
...other shirt-related fields
sizes table:
size_id (auto-incrementing primary key)
size_value (i.e. S, M, L)
...other size-related fields
shirt_sizes table:
shirt_id (foreign key to shirts table)
size_id (foreign key to sizes table)
(you have compound primary key across these two fields)
An you would query it like
SELECT * (or whatever fields you need)
FROM shirts
INNER JOIN shirt_sizes ON shirts.shirt_id = shirt_sizes.shirt_id
INNER JOIN size ON shirt_sizes.size_id = sizes.size_id
With the following table structure:
CREATE TABLE `shirt` (
`id` INTEGER NOT NULL,
`name` VARCHAR(32),
PRIMARY KEY( `id` )
);
CREATE TABLE `size` (
`id` INTEGER NOT NULL,
`name` VARCHAR(4),
PRIMARY KEY( `id` )
);
CREATE TABLE `shirt_size` (
`shirtId` INTEGER NOT NULL,
`sizeId` INTEGER NOT NULL,
PRIMARY KEY( `shirtId`, `sizeId` ),
FOREIGN KEY( `shirtId` ) REFERENCES `shirt`( `id` ),
FOREIGN KEY( `sizeId` ) REFERENCES `size`( `id` )
);
And this data:
INSERT INTO
`shirt` ( `id`, `name` )
VALUES
( 1, "vneck" ),
( 2, "scoop neck" );
INSERT INTO
`size` ( `id`, `name` )
VALUES
( 1, "xs" ), ( 2, "s" ), ( 3, "m" ),
( 4, "l" ), ( 5, "1x" ), ( 6, "2x" ), ( 7, "3x" );
INSERT INTO
`shirt_size` ( `shirtId`, `sizeId` )
VALUES
( 1, 2 ), ( 1, 3 ), ( 1, 4 ), ( 1, 5 ),
( 2, 1 ), ( 2, 2 ), ( 2, 3 ), ( 2, 4 ), ( 2, 5 ), ( 2, 6 ), ( 2, 7 );
In MySQL you could do:
SELECT
`shirt`.`id`,
`shirt`.`name`,
GROUP_CONCAT( `size`.`name` ) as `sizes`
FROM
`shirt`
JOIN
`shirt_size`
ON `shirt_size`.`shirtId` = `shirt`.`id`
JOIN
`size`
ON `size`.`id` = `shirt_size`.`sizeId`
GROUP BY `shirt`.`id`;
Which would result in something like:
+----+------------+-------------------+
| id | name | sizes |
+----+------------+-------------------+
| 1 | vneck | s,m,l,1x |
+----+------------+-------------------+
| 2 | snoop neck | xs,s,m,l,1x,2x,3x |
+----+------------+-------------------+
Not sure if other RDBMS's have aggregate functions similar to MySQL's GROUP_CONCAT(). If not, then use something like:
SELECT
`shirt`.`id`,
`shirt`.`name` as `shirtName`,
`size`.`name` as `sizeName`
FROM
`shirt`
JOIN
`shirt_size`
ON `shirt_size`.`shirtId` = `shirt`.`id`
JOIN
`size`
ON `size`.`id` = `shirt_size`.`sizeId`;
Which will give you multiple rows for every size, with each shirt.

Categories