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.
Related
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
This question already has an answer here:
MySQL SELECT LAST_INSERT_ID() for compound key. Is it possible?
(1 answer)
Closed 6 years ago.
I have this table:
CREATE TABLE `test` (
`Id1` int(11) unsigned NOT NULL,
`Id2` int(11) unsigned NOT NULL,
`Id3` int(11) unsigned NOT NULL,
`Id4` int(11) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(255) NOT NULL,
PRIMARY KEY (`Id1`,`Id2`,`Id3`,`Id4`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;
INSERT INTO `test` (`Id1`, `Id2`, `Id3`, `Name`) VALUES (1, 1, 1, 'test')
INSERT INTO `test` (`Id1`, `Id2`, `Id3`, `Name`) VALUES (1, 1, 1, 'test2')
INSERT INTO `test` (`Id1`, `Id2`, `Id3`, `Name`) VALUES (1, 2, 1, 'test')
INSERT INTO `test` (`Id1`, `Id2`, `Id3`, `Name`) VALUES (1, 2, 1, 'test2')
After creating the table the date looks like this:
Id1 Id2 Id3 Id4 Name
1 1 1 1 test
1 1 1 2 test2
1 2 1 1 test
1 2 1 2 test2
Id4 is incrementing as is expected but I have problem to get inserted Id4 using PHP mysqli. This is the code I am using:
$db = new mysqli('host', 'user', 'pass', 'db');
$db->query("INSERT INTO `test` (`Id1`, `Id2`, `Id3`, `Name`) VALUES (1, 1, 1, 'test')");
var_dump($db->insert_id);
I get result
int(0)
Result should be int(1) but I get zero for no reason. Any ideas?
Essentially, your code should work... it worked when tested... in other words check to see if there is something else going on... as it stands, your code is ok.... and should work fine... However as an alternative work-around, you may want to wrap MySql LAST_INSERT_ID() Function in your own Function and then call the Function when you need to get the Last Insert ID...
<?php
// WILL RETURN THE ID OF THE AUTO-INCREMENTED FIELD ONLY
function getLastInsertID($db, $tbl='test'){
$result = null;
$sql = $db->prepare("SELECT LAST_INSERT_ID() FROM `". $tbl ."`");
$sql->execute();
$sql->bind_result($result);
$sql->fetch();
return $result;
}
var_dump(getLastInsertID($db));
Perhaps it does the Trick for you....
REF: http://dev.mysql.com/doc/refman/5.7/en/getting-unique-id.html
LAST_INSERT_ID() returns the value only for a column declared AUTO_INCREMENT. There's no function to return the value in a compound primary key that wasn't generated by the system. You ought to know that value already, since you just gave it in an INSERT statement. The tricky case would be when a trigger or something overrides the value.
More details:
Check this stackoverflow link
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);
I am studying relational databases on my own and after reading some articles I am having trouble implementing them.
Due to my lack of experience with relational databases I believe that my error can be in any of the following 3 (if not in all 3) steps:
Table Creaton
Value Insertion
Query call
I should point out that there aren't any syntax errors or something like that.
We are talking about an error in my understanding so I will approach the problem in detail.
The tables:
For the abstraction I have chosen to have people and the drinks which they like (1 person can like many drinks, one drink can be liked by many people.
Here is the code for the table People (It has 2 names, and a primary key):
CREATE TABLE `People`
(
`PeopleID` INT NOT NULL AUTO_INCREMENT,
`FirstName` VARCHAR(25),
`LastName` VARCHAR(25) NOT NULL,
PRIMARY KEY (`PeopleID`)
)
Here is the table Drinks (Name of drink, some number in menu or something like that for example and the primary key)
CREATE TABLE `Drinks`
(
`DrinksID` INT NOT NULL AUTO_INCREMENT,
`Code` VARCHAR(10) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL,
`Name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`DrinksID`)
)
And lastly the table PeopleDrinks:
CREATE TABLE `PeopleDrinks`
(
`DrinksID` INT NOT NULL default 1,
`PeopleID` INT NOT NULL default 1,
PRIMARY KEY (`DrinksID`,`PeopleID`)
)
Note: from here I saw the example given for the third table and pretty much copied it.
Value insertion:
People input:
INSERT INTO People (FirstName, LastName) VALUES ('John', 'Smith')
INSERT INTO People (FirstName, LastName) VALUES ('Sam', 'Johnson')
INSERT INTO People (FirstName, LastName) VALUES ('Michael', 'Morgan')
Drinks input:
INSERT INTO Drinks (Code, Name)VALUES ('#543', 'Beer')
INSERT INTO Drinks (Code, Name) VALUES ('#132', 'Vodka')
INSERT INTO Drinks (Code, Name) VALUES ('#123', 'Wine')
PeopleDrinks input:
Note: The id of the drinks are 4, 5 and 6. Not 1, 2, 3.
INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (1, 4)
INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (2, 5)
INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (3, 6)
Above we give as favorite one drink to every person. Below we will make one person like all the drinks:
INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (1, 5)
INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (1, 6)
And finally the query call:
//Consider $link an established, working connection to the database
$result = mysqli_query($link, "SELECT
`People`.*
FROM
`People`
JOIN
`PeopleDrinks` ON `People`.`PeopleID` = `PeopleDrinks`.`PeopleID`
WHERE
`PeopleDrinks`.`DrinksID` = 5");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br/>";
}
The above code, should print the name of anyone who likes the drink with id 5. I don't get an error, but I don't get any output.
You said the id of the drinks are 4,5,6
In the INsert you have used
INSERT INTO PeopleDrinks (DrinksID, PeopleID)VALUES (1, 4)
INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (2, 5)
INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (3, 6)
The drink ids(first number) are 1,2,3 instead of 4,5,6 or something like that. I think your order is wrong.
Your many to many table needs foreigns key :
CREATE TABLE `PeopleDrinks` (
`DrinksID` INT NOT NULL,
`PeopleID` INT NOT NULL,
PRIMARY KEY (`DrinksID`,`PeopleID`),
FOREIGN KEY (`DrinksID`) REFERENCES `Drinks`(`DrinksID`),
FOREIGN KEY (`PeopleID`) REFERENCES `People`(`PeopleID`)
)
Remove the default values of DrinksID and PeopleID, this make no sense.
Then when you do your insert, you will be sure that the data you are trying to insert are right.
I think that your insert are false. When you say that your IDs are what they are, you are wrong. This is particulary true if your are doing a lot of inserts and deletes. Autoincrement will keep going forever, and you can't be sure. With Foreign Keys, the RDBMS will tell you if there is something wrong with your relations.
Anyway, your query looks great, so no problem for that.
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.