how to insert data from primary key column to foregin key - php

i am inserting data from a form i want when i will insert data so the first column primary id which is using in second column as a foreign key should be increased
i have tried this code but not working
first table code
$this->db->query("insert into af_ads (ad_title,ad_pic,ad_description)
values ('$title','$filepath','$description')");
second table code
$this->db->query("insert into af_category (cat_type,ad_id_fk)
values ('$category','ad_id')");
NOTE: i want to insert ad_id into ad_id_fk

Try this:
// Your first query
$this->db->query("insert into af_ads(ad_id, ad_title, ad_pic, ad_description)
values ('', '$title', '$filepath', '$description')");
$ad_id = $this->db->insert_id(); // This returns the id that is automatically assigned to that record
// Use the id as foreign key in your second insert query
$this->db->query("insert into af_category (cat_type,ad_id_fk)
values ('$category', $ad_id)");

MySQL provides the LAST_INSERT_ID function as way to retrieve the value generated for an AUTO_INCREMENT column from the immediately preceding INSERT statement.
A lot of client libraries make this conveniently avaiable (e.g. PDO lastInsertId function.)
(I'm not familiar with CodeIgniter or ActiveRecord, so I can't speak to how that's made available.
Your code looks like it's using the PDO interface... but I'm not sure about that.
# either we need to check return from functions for errors
# or we can have PDO do the checks and throw an exception
$this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
# attempt insert which will generate AUTO_INCREMENT value
$this->db->query("INSERT (ad_id, ... ) VALUES (NULL, ...)");
# if previous insert successfully inserted a row (or rows)
$ad_id = $this->db->lastInsertId();
You really need to check whether the previous insert was successful or not. If you aren't going to code that check yourself, then PDO does provide a mechanism that performs this checking automatically, and will throw an exception if a MySQL error occurs.
I've avoided copying your original code, which looks like it's vulnerable to SQL Injection. If you're using PDO, you can make effective use of prepared statements with bind placeholders, rather than including values in the SQL text.

Related

Alternatives for insert ignore into for SQL server

i just switched over from a Mysql server to SQL server. But i just found out that INSERT INGORE INTO doesn't work with sql server.
Original code:
INSERT IGNORE INTO DATA_EXACT_INVENTORY_LOCATIONS (ID, Code, Opslaglocatie, Omschrijving, OpVoorraad)
VALUES ('$inventorylocationID','$inventorylocationsItemCode','$inventoryStorageLocationsCode','$inventorylocationsItemDescription','$inventorylocationsCurrenctStock')
I found out that i can use on duplicate key update, but the problem is that i have sql query's with upto 50 variables. So to use on duplicate key update would be alot of work. So what i was wondering is there a better alternative for INSERT IGNORE INTO that's is just plug and play so i don't have to write all variables again.
You can use not exists:
INSERT DATA_EXACT_INVENTORY_LOCATIONS (ID, Code, Opslaglocatie, Omschrijving, OpVoorraad)
SELECT ID, Code, Opslaglocatie, Omschrijving, OpVoorraad
FROM (VALUES ('$inventorylocationID', '$inventorylocationsItemCode', '$inventoryStorageLocationsCode', '$inventorylocationsItemDescription', '$inventorylocationsCurrenctStock')
) V(ID, Code, Opslaglocatie, Omschrijving, OpVoorraad)
WHERE NOT EXISTS (SELECT 1
FROM DATA_EXACT_INVENTORY_LOCATIONS deil
WHERE deil.id = v.id -- or whatever column gets the duplicate key
);
Alternatively, you could rewrite the code to use MERGE. The SELECT should work in both databases.
Let me also add that you should learn to use parameters. Munging query strings with constant values exposes your code to SQL injection attacks and to hard-to-debug syntax errors.

Syntax Error while inserting students into postgres database via php using nextval

I created a database with my .sql file with this:
CREATE SEQUENCE ec_account_id
start 1
increment 1;
create table ec_account
(id serial PRIMARY KEY,
name VARCHAR(40) not null,
password VARCHAR(80) not null,
email VARCHAR(30) not null,
phone VARCHAR(10) not null);
insert into ec_account values (nextval('ec_account_id'),'admin','68dc71d4b0724561008d7665a37d9f8bba008f95836c0caab9656d9f1983d314','123456#gmail.com','123456789');
insert into ec_account values (nextval('ec_account_id'),'dsds','cfb68d2dba58568ff9e223235ff1b77b3cb42c371403832a434112aabc','johnnsySilva#gmail.com','123456789');
And i could watch it(the table) via terminal. Check the passwords on the html. Everything was going along fine. But now i want to add new persons to the database via an html form and i want the id to increment automatically, however im not being able to insert (via php) the instances on the database cause when i run this code i get this error:
$sql = "INSERT into ec_account values ('nextval('ec_account_id')','$nome','$hashedPass','$email','$telemovel') ";
ERROR: ERROR: syntax error at or near "ec_account_id" LINE 1: INSERT
into ec_account values ('nextval('ec_account_id')','f...
^
Im almost sure it has something to do with the next val but i dont know how to solve it. Can somebody clarify me? I don't want the responsability of having to memorize how many people are already enrolled in the ec_account table, and i thought this was the way to automatically increment the primary key whenever i insert a new row.
Seems like you made a fairly simple mistake:
$sql = "INSERT into ec_account values ('nextval('ec_account_id')','$nome','$hashedPass','$email','$telemovel') ";
Notice your extraneous single quote before nextval. Remove that and the closing one you added and things should be fine.
$sql = "INSERT into ec_account values (nextval('ec_account_id'),'$nome','$hashedPass','$email','$telemovel') ";
Just to clarify, SQL needs quotes around string values. You do not need to randomly add quotes around every variable you are passing.
Another clarification about Postgresql, is that when you define a column as type "serial" Postgresql creates a sequence for you with the name tablename_columname_seq. So you redundantly created a sequence when you could have used nextval('ec_account_id_seq') and do not need to create the sequence ec_account_id.
When you author an insert statement you should avoid using the shorthand method and explicitly list the columns. This avoids issues later should you need to do an insert that doesn't include all columns, or if you add a column to the table which will break your existing insert statements.
Fixed:
$sql = "INSERT into ec_account ('id', 'name', 'password', 'email', 'phone')
values (nextval('ec_account_id'),'$nome','$hashedPass','$email','$telemovel')";
A final word about SQL injections, escaping and parameters:
This technique of using PHP strings to interpolate values is prone to numerous problems and creates vulnerabilities in your system.
I don't know if you are using the pg api or PDO, but in either case, you should be using parameters to send in your values.
Here's a link to the pg_query_params page that explains this.
I'd recommend using PDO personally.

Update SQL row if exists, create if does not exist (in PHP)

I am trying to update a value for a user without knowing if the user exists or not.
Basically: If the user does not exist, create it, and update the value. If it does exist, update the value.
Am I using ON DUPLICATE properly? Can I use WHERE while using ON DUPLICATE?
$sql = "INSERT INTO Users ('$column_name[$i]') VALUES ('$value[$i]') ON DUPLICATE KEY UPDATE '$column_name[$i]'='$value[$i]' WHERE LoginName = '$login_name'";
The error I am getting with this line is:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''record_id') VALUES ('5287469') ON DUPLICATE KEY UPDATE 'record_id' at line 1
Any suggestions on how I should form my query?
The WHERE clause cannot be used with an INSERT ... VALUES statement.
It doesn't matter that there's an ON DUPLICATE KEY clause or not.
MySQL Reference Manual reveals (in a cryptic way) that there is no WHERE clause in an INSERT ... VALUES statement:
https://dev.mysql.com/doc/refman/5.7/en/insert.html
(An INSERT ... SELECT statement can include a WHERE clause, in the SELECT part of the statement, like a normal SELECT statement.)
Don't use single quotes around identifiers (e.g. column names).
If those need to be escaped, use single backtick characters.
Including potentially unsafe values in SQL text throws wide open a whole slew of nasty vulnerabilities, categorized as SQL Injection.
https://www.owasp.org/index.php/SQL_Injection
It could be the values being included in the SQL text have been properly sanitized, or whitelisted. But we're not seeing that in the code, so alarm bells are ringing.
Normative pattern (of just the SQL) would be something like this:
INSERT INTO Users
( `primary_or_unique_key_column`
, `some_column_name`
) VALUES
( 'safe_unique_key_value'
, 'safe_column_value'
)
ON DUPLICATE KEY
UPDATE `some_column_name` = VALUES(`some_column_name`)
If LoginName is the PRIMARY or UNIQUE KEY in the table
INSERT INTO Users
( `loginname`
, `record_id`
) VALUES
( 'safe_loginname_value'
, 'safe_record_id_value'
)
ON DUPLICATE KEY
UPDATE `record_id` = VALUES(`record_id`)
Note that usage of backticks around the column names, and single quotes around literal string values.
Also note the usage of the VALUES function, to reference the value that would have been inserted into the column, if the INSERT had been successful. (Avoids us having to provide the same value twice.
Using prepared statements with bind placeholders, we would need to properly validate the column name that's being incorporated into the SQL text (to avoid SQL Injection vulnerabilities... but the values can be passed in via placeholders.
The SQL text would look like this:
INSERT INTO Users
( `loginname`
, `record_id`
) VALUES
( ?
, ?
)
ON DUPLICATE KEY
UPDATE `record_id` = VALUES(`record_id`)
And code (assuming PDO) would be of the form:
$sth=$dbh->prepare($sql_text);
# check return from prepare
$sth->bindValue(1, $loginname_val, PDO::PARAM_STR);
$sth->bindValue(2, $record_id_val, PDO::PARAM_INT);
$sth->execute();
# check return from execute

SQL, how to get the automated ID from the previous INSERT?

I am using PHP and SQL and trying to insert user data into two tables upon registration. First in the user_table and second into the character_table. I'm using an automatically generating user_id to link the tables and need to get the value of the user_id from the first INSERT (into user_table) then add it to a column in the character_table.
I tried a few methods and here is where I ended ($username, $email, $password and $character are defined above);
$sql = "INSERT INTO
user_table (id, username, email, password)
VALUES ('NULL', '".$username."', '".$email."', '".$password."')
INSERT INTO
character_table (name, id)
VALUES ('".$character."', 'LAST_INSERT_ID()')";"
I want "id" from user_table to match with "id" inserted into character_table.
When I run the above, nothing seems to be happening. Previous attempts I always ended with id = 0. What is the correct way I can get the ID from the first INSERT?
Run your statements seperately. You run your insertion into your user_table, then grab the id then run your insertion into your character_table
You can grab the id using mysql_insert_id after running the insert. Note that on the php webpage detailing the mysql_insert_id function that it is deprecated as is all mysql* functions. Which leads to...
For the love of everything holy don't concatenate your variables directly to your INSERT statement. Switch to mysqli* functions or PDO if you haven't already and use prepared statements (parameterizing the query). If you build an application using mysql it means you are not parameterizing your queries which means you are at a huge risk for a sql injection attack.
If/when you switch over to mysqli or PDO functions you will find an equivalent mysqli_insert_id() (or PDO::lastInsertID()) function

how to use mysql update query and mysql insert query together?

this the condition: there is a form in html and php haivng around 120 fields its for a website i am making this form on submitting goes to a php page where i first retrive all the values using $_REQUEST[]and then using insert query insert all of them in their specific coloums in the same table in my mysql database. Now i will have to do all the process again for updating these values. Becuase syntax for insert query and update query are quite different .
I dont want to write another 100 lines of code . Is there any way to use the code i wrote inside my insert query to use to update the data.?
Actually in MySQL there is an alternative syntax for insert that is very similar to the syntax for update. You can write
insert customer set customerid=12345, firstname='Fred', lastname='Jones
etc.
Personally I prefer this syntax because it's easy to see what value is going into each field. This is especially true on records with long lists of fields.
On the minus side, it's not standard SQL, so if you ever decide to port your app to a different database engine, all your inserts would have to be rewritten.
Another option I've occasionally used is to write a little function to create your insert and update statements. Then the syntax of your function can be the same, no matter how different the generated code is.
Another alternative, and depending on requirements and keys, you could use:
replace into tbl (<cols>) values (<vals>)
which will insert if not exist, or replace based on keys (insert/update in one query)
or if you are only inserting and don't want to insert twice, you could use:
insert ignore into tbl (<cols>) values (<vals>)
where if the record is already inserted based on keys, it is gracefully ignored
for more info http://dev.mysql.com/doc/refman/5.0/en/replace.html
There is a quite similar syntax for INSERT and UPDATE:
INSERT INTO <table> SET
column1 = value1,
column2 = value2,
...
;
UPDATE <table> SET
column1 = value1,
column2 = value2,
...
WHERE <condition>
;
INSERT INTO yourtable (field1, field2, field3, ...)
VALUES ($field1, $field2, $field3, ...)
ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), etc...
Details on this construct here.

Categories