PHP: use id to another column - php

Ok, so i have a normal query that inserts to the database.
mysql_query("INSERT INTO users_pm_in (uID, msg) VALUES ('$uID', '$msg')");
Now this table has also a column called "id" with auto_increment & primary key.
When it inserts it auto makes number for the column in the row. Now I want this number, and put it in column dialog, in the same row. So the inserted row have the same number/id in "id" and "dialog". How can i do that?

Not sure if this can be done in one query (or why you even want to do this), but you can use this:
mysql_query("INSERT INTO users_pm_in (uID, msg) VALUES ('$uID', '$msg')");
mysql_query("UPDATE users_pm_in SET dialog = id WHERE id = '".mysql_insert_id()."');
Be sure to escape the variables properly also.

I think it would be easier to remove the autoincrement and add the id+dialog value yourself.

Check out mysql_insert_id()

You can do this, altough it's not very efficient...
Supose you have this table:
CREATE TABLE `test` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`a` INT(10) NULL DEFAULT '0',
`b` INT(10) NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
ENGINE=MyISAM
ROW_FORMAT=DEFAULT
You can perform the following query:
INSERT INTO test (a, b) SElECT IFNULL((MAX(id) +1),1), 200 FROM test;
Notice that "200" is some random value that will be inserted on "b" column.

Related

Auto increment column after inserting same value

Is it possible to auto increment column after inserting the same value and also check the duplicate value of maximum of 2 like this:
INSERT INTO info (name, date, sched) VALUES ('$name', '$date', '$sched')
// I want to auto increment for count column after inserting same date and sched
INSERT INTO appointment (date, sched) VALUES ('$date', '$sched')
Here is my table:
Somebody can help me to achieve that or suggest a better way for appointment scheduling? Thanks!
Firstly, table design like this:
create table appointment (
id int(11) unsigned not null auto_increment,
date date not null '2018-01-01',
sched varchar(20) not null defalut '',
count int(11) not null default 0,
primary key (id)
unique key `date_sched` (`date`, `sched`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Then, sql like this:
insert into appointment(date, sched, count) values ($date, $sched, $count)
on duplicate key update count = count + 1

MariaDB INSERT INTO... SELECT... ON DUPLICATE KEY UPDATE affecting 0 rows

I've created the following table in MariaDB
Table creation
CREATE TABLE `email_templates_pending` (
`template_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`template_name` varchar(100) NOT NULL,
`template_data` text,
`modify_type` varchar(16) NOT NULL,
`modify_by` varchar(50) NOT NULL,
`modify_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`template_id`),
UNIQUE KEY `template_name` (`template_name`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
And inserted a row in that table with the template_id = 1. I wanted to update the row using the following INSERT INTO...SELECT...ON DUPLICATE KEY UPDATE statement below
SQL Statement
INSERT INTO email_templates_pending
(template_id, template_name, template_data, modify_by, modify_type)
SELECT template_id, template_name, template_data, 'test#test.com', 'Deleted'
FROM email_templates WHERE template_id= '1'
ON DUPLICATE KEY UPDATE modify_type='Deleted'
However, when I run the statement it returns successful but with 0 rows affected. I have another similar table with different column names that works as intended. I've ensured that the template_id is the primary key, so I'm not sure what else the issue could be?
You have 1 row in email_templates_pending, but no rows in email_templates.
That may be the reason why 0 row affected. No row is in the source table.
INSERT INTO email_templates_pending ...
SELECT ... FROM email_templates
If you just want to update for id = 1, you can use this:
INSERT INTO email_templates_pending (template_id, template_name, template_data, modify_by, modify_type)
SELECT template_id, template_name, template_data, 'test#test.com', 'Deleted' FROM email_templates_pending
ON DUPLICATE KEY UPDATE modify_type='Deleted';
If you just need to do UPDATE, may be a direct UPDATE statement can also be used.
UPDATE email_templates_pending SET modify_type='Deleted' WHERE template_id= '1';
If id#1 existed and was already marked as "Deleted", you would correctly get "0 rows affected".
To prove that this is not the case, let's see the output from
SELECT template_id, template_name, template_data, modify_by, modify_type
FROM email_templates WHERE template_id= '1' ;

INSERT if not exists UPDATE if exists does not work

I am trying to have the solution of the very well known INSERT IF NOT EXISTS UPDATE IF EXISTS.
But mine is not working. I don't know why, Can anyone figure it out?
Here is what I have tried yet:
$qprep = ("INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('$imei','$lathex1','$lonhex1') ON DUPLICATE KEY UPDATE
latitude='$lathex1',longitude='$lonhex1';");
I want to update the row if the same "imei" is in there, or Insert if its not.
I have my ROW as the primary key and from phpmyadmin, I have made the imei "unique".
What am I doing wrong?
My SQL DUMP:
CREATE TABLE IF NOT EXISTS `gpsdata` (
`ROW` int(11) NOT NULL AUTO_INCREMENT,
`IMEI` varchar(255) NOT NULL,
`Latitude` varchar(255) NOT NULL,
`Longitude` varchar(255) NOT NULL,
PRIMARY KEY (`ROW`),
UNIQUE KEY `IMEI` (`IMEI`,`Latitude`,`Longitude`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
--
-- Dumping data for table `gpsdata`
--
INSERT INTO `gpsdata` (`ROW`, `IMEI`, `Latitude`, `Longitude`) VALUES
(24, '#2:359672050035420:2:*', '90.370803333333', '0'),
(30, '#2:359672050035420:2:*', '90.370803333333', '23.7584'),
(27, '#2:359672050035420:2:*', '90.370803333333', '23.75854'),
(35, '1:135790246811221:1:*', '1.0961283333333', '1.759595'),
(32, '1:135790246811221:1:*', '1.759595', '1.0961283333333');
As seen here, you need to replace the actual values in the update statement with either A| references to the alreay existing values (e.g. longitude=longitude) or B| references to the new values (e.g. longitude=VALUES(longitude), but not longitude='$lonhex1').
Your query should be rewritten:
$qprep = ("INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('$imei','$lathex1','$lonhex1') ON DUPLICATE KEY UPDATE
latitude=VALUES(latitude),longitude=VALUES(longitude)");
If you have statement based replication running on this server then there would be a problem, see the warning below:
Unsafe statement written TO the BINARY LOG USING statement FORMAT
since BINLOG_FORMAT = STATEMENT. INSERT... ON DUPLICATE KEY UPDATE
ON a TABLE WITH more THAN ONE UNIQUE KEY IS unsafe
You have to pass the column name and its value on which you have used the primary key or unique key on which you want the Duplicate Key Update.
If it gets the id(in your case ROW, latitude and longitude column on which primary and unique key is defined ) in the database, it updates it, else it inserts a new row.
$qprep = ("INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('$imei','$lathex1','$lonhex1') ON DUPLICATE KEY UPDATE
latitude=VALUES(latitude),longitude=VALUES(longitude)");
Example:
INSERT INTO gpsdata (`row`,`imei`,`latitude`,`longitude`)
VALUES ('24','1','TEST','TEST') ON DUPLICATE KEY UPDATE
`IMEI`='2', `Latitude`='2',`Longitude`='2';
or
INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('1','TEST','TEST') ON DUPLICATE KEY UPDATE
`IMEI`='2', `Latitude`=VALUES(`Latitude`),`Longitude`=VALUES(`Longitude);

MySQLi does not return error code

In my MySQL database I have a table "table1" with unique constraint set on column "name" - I want to prevent duplicate names.
If there's already name 'John' in table this code:
$db=new mysqli(...);
$sql="INSERT INTO table1 SET id=10,name='John'";
if(!$db->query($sql))
{
if($db->errno==1062)
{
throw new InsertNonUniqueException(...);
}
else
{
throw new InsertException(...);
}
}
should throw InsertNonUniqueException() (my own exception). Instead, it throws InsertException().
Execution of query returns false and execution enters the if() loop. Also $db->row_affected is -1 but problem is that $db->errno is always O (it should be 1062)!!! So I can't detect that my insert error was caused by violating unique key constraint on name column!
I don't know why mysqli does not return 1062 code when unique key constraint violation occurs!
I can't leave a comment, thus going to ask you here.
Please provide the result of SHOW CREATE TABLE table1;
I can't reproduce your problem using your code and next table:
CREATE TABLE `table1` (
`name` varchar(11) COLLATE utf8_unicode_ci NOT NULL,
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Am I the only one around here that thinks you have an error in your SQL syntax?.. There is no room for SET in INSERT INTO, because you can only use SET in UPDATE statements (assuming you habe MySQL in version 5.5 or below).
INSERT INTO syntax is like the following (as described in the docs):
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
OR
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
Try it like this:
<?php
$sql="INSERT INTO table1 (id, name) VALUES ('10', 'John')";
...
step 1
make sure that the table has a unique key
SHOW CREATE TABLE table1
expected result
CREATE TABLE `table1` (
`id` INT(11) default NULL,
`name` varchar(11) COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
if there is UNIQUE KEY name (name) we have a unique key
step 2
try to change your code
$db = new mysqli(...);
// first insert
if( !$db->query("INSERT INTO table1 (id, name) VALUES (10, 'John')") ) {
throw new Exception($db->error);
}
// second insert (for me raise: Duplicate entry 'John' for key 'name')
if( !$db->query("INSERT INTO table1 (id, name) VALUES (11, 'John')") ) {
throw new Exception($db->error);
}
Please, try these two steps
Side note: if you have name and id as duplicates, only the first duplicate encountered will be returned in the message.
The only issue i have with your code is that:
having setup your table and columns.
I setup a unique index on the table. I did .. stuff on a two column table that ensure it works.
You missed the 'new'
keyword when you 'throw exceptions'.
this is the only error with your posted code that i could find.
i.e: throw new Exception('Division by zero.'); // example taken from PHP manual.

mysql insert problem

ive got a really weird problem. i have no clue why its not working. i create an user and get the id and insert a row based on that id in another table. the row gets inserted with that id but the other values however for that row are not inserted!
$user_id = mysqli_insert_id($this->connection);
$query = "INSERT INTO selections
(user_id, language_id, country_id, region_id, city_id, gender_id, age_id, category_id)
VALUES ($user_id, 1, 1, 0, 0, 0, 20, 0)";
so the user_id gets inserted, but not the other values (they are all 0 in the table). i have really checked the columns and deleted all foreign keys to debug this problem. but i have no clue at all.
the columns are all INT. the weird part is sometime when i replace $user_id with a literal number it works, sometimes it doesnt. but the row is always created. and i have checked that $user_id is an integer.
i know this is a hard problem and that it can be caused of a lot of things, but i have tried to solve this tiny issue for 3 hours now. so would be great if someone just gave me something i could do to debug this problem.
UPDATE: even when i have set default values and just insert the first column (user_id) it doesnt work. every other field is 0. So weird!
| selections | CREATE TABLE `selections` (
`user_id` int(11) NOT NULL,
`language_id` int(11) NOT NULL DEFAULT '1',
`country_id` int(11) NOT NULL DEFAULT '1',
`region_id` int(11) NOT NULL DEFAULT '0',
`city_id` int(11) NOT NULL DEFAULT '0',
`gender_id` int(11) NOT NULL DEFAULT '0',
`age_id` int(11) NOT NULL DEFAULT '0',
`category_id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
$query = "INSERT INTO selections
(user_id)
VALUES ('$user_id')";
the user_id shows 178 and other fields are 0:(
UPDATE:
It worked in the sql command line. but not in php. but mysqli generated no error and the row was indeed inserted but why are the other fields 0?
ANSWER: My fault. i had a jquery script that changed it back to 0 0 0 0 0 0 0. There's a lot of AJAX on my page so it was tricky to find it...sorry my bad!
When you run into situations like this, print the query to screen before it is executed:
$query = "INSERT INTO ...";
echo $query
Try:
$query = "INSERT INTO selections
(user_id, language_id, country_id, region_id, city_id, gender_id, age_id, category_id)
VALUES
({$user_id}, 1, 1, 0, 0, 0, 20, 0)";
You need to wrap PHP variables in {} when referencing them in SQL string statements.
Use Your DEFAULT Constraints
If you have defaults then you don't need to set the values in your INSERT statement:
INSERT INTO selections
(user_id)
VALUES
({$user_id})
Referencial Integrity
You're getting the last inserted id and using it in a subsequent insert into another table, but you don't have a foreign key defined on the user_id column to ensure that the value going into that column actually exists in the other table. If you provide the name of the table & column you are getting for your last insert id, I'll provide the ALTER TABLE statement.
$query = "INSERT INTO selections
(user_id, language_id, country_id, region_id, city_id, gender_id, age_id, category_id)
VALUES ('$user_id', 1, 1, 0, 0, 0, 20, 0)";
Single quotes around $user_id might do it.

Categories