Storing multiple inputs in database in single query - php

<form method="post" action="formProcessing.php">
<input type="text" name="uses[]">
<input type="text" name="uses[]">
<input type="text" name="uses[]">
</form>
I have two database tables one called info other uses. info table contain column name inf_num, Is there a way where i can get the last row inf_num and insert the above inputs in uses in one query. For instance if i was to do it manually i would check the last row myself so if it's 10 i would do the below:
INSERT INTO uses (id, uses) VALUES (10, 'useZero'), (10, 'useOne'), (10, 'useTwo');
How would i go about doing it dynamically with php using the above form:

you can create trigger on uses table to set last inserted id of info table.
CREATE TRIGGER uses_before_insert_trigger BEFORE INSERT ON `uses` FOR EACH ROW
BEGIN
SET NEW.id = (select id from info order by id desc LIMIT 1);
END
After, create trigger you can execute insert query directly.
INSERT INTO uses (uses) VALUES ('10'),('20'),('26');

INSERT INTO user( id, uses )
SELECT MAX(id), 'userOne' FROM info
UNION ALL
SELECT MAX(id), 'userTwo' FROM info;

Try To Make A Query Like This
<?php
//Your input is array of your input.
$yourInput = array(10,20,26);
$query = "INSERT INTO uses (id, uses) VALUES ";
foreach($yourInput as $value ){
$query .= "(10, '$value')".",";
}
echo $query;
//Output
INSERT INTO uses (id, uses) VALUES (10, '10'),(10, '20'),(10, '26')
Tested Here
Than Execute this Query
But Remember Youe code is not secure. it is possible to do a sql injection so kindly read this note. and make it more secure.

We can make it possible via query as well.
INSERT INTO uses( id, uses ) VALUES ((SELECT MAX(inf_num) from info),
'useOne', (SELECT MAX(inf_num) from info), 'useTwo', (SELECT MAX(inf_num) from
info), 'useThree')

Related

Running an insert script from multiple values

I'm trying to run a pretty simple script that does the following: Takes the id of a content module and assigns it to multiple locations
So say I click the link on a content module with ID of 123, I want to assign it to all multiple locations. In SQL I would just say :
INSERT INTO table (cont_id,loc_id)
VALUES (123, select(id from location_table where active = 1))
I'm currently using this:
$pageID = $_GET['pageID'];
$assignPage = "
INSERT INTO locationContent(page_id, display_id)
VALUES ( '$pageID', select(id from locations where active = 1))
ON DUPLICATE KEY UPDATE active = 1
";
$performAssign = $mysqlConn->query($assignPage);
The issue I'm wondering about though, is do I need to put this into a foreach or while loop? If I were to just run as is, I feel like that would only work for one record
You seem to be looking for MySQL INSERT ... SELECT syntax.
From the documentation:
With INSERT ... SELECT, you can quickly insert many rows into a table from the result of a SELECT statement, which can select from one or many tables.
Query:
INSERT INTO locationContent (page_id, display_id)
SELECT ?, id FROM locations WHERE active = 1
ON DUPLICATE KEY UPDATE active = 1
The ? stands for parameter $pageID (you do want to use parameterized queries and prepared statement to protect your code against SQL injection).
You can't mix the INSERT INTO .. VALUES and INSERT INTO ... SELECT syntax, however SELECT constant, var FROM .. is possible like:
$assignPage = $mysqlConn->prepare("
INSERT INTO locationContent(page_id, display_id)
SELECT :page as page_id, id FROM locations WHERE active = 1
ON DUPLICATE KEY UPDATE active = 1
";
$performAssign = $assignPage->execute(array('page' =>$pageID));

insert records from one table to another

Hi I am trying to add records from one table to another, once i have added a 'user' record, the table that is being selected contains rows of available security options, and the table that is being inserted to is the child table for the user, detailing security options.
I cam across this code in an earlier post, which i am sure works nicely, however i am trying to modify it so that the values from statement, includes two parts, one from the select query and one which is the key from the master record.#
This is the original code I found from this site:
INSERT INTO def (catid, title, page, publish)
SELECT catid, title, 'page','yes' from `abc`
And this is what I am trying to do with it:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('".$keys["UserPk"]."', SELECT ModulePk from Global_Modules)";
CustomQuery($sql);
And this is the error I am getting:
INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('4', SELECT
ModulePk from Global_Modules)
See screenshot for further detail
Obviously I am not concating the from statement properly, but would appreciate any help?
You can insert the $keys["UserPk"] variable as if it were a constant in the SQL:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Do note that $keys["UserPk"] must be escaped before adding it into the query. In PDO, it would look like this:
$keys["UserPk"] = $pdo->quote($keys["UserPk"]);
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Could be a problem related to the double quotes sequence
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
values ('". $keys['UserPk']. "', SELECT ModulePk from Global_Modules)";
but you could use also a select insert
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
SELECT '" . $keys['UserPk']. "' , ModulePk from Global_Modules)";
Adding only new and unique records from one table to another. Limiting is a good idea to prevent it from timeout. It can be run several times until all the records copied.
First, select the latest record ID from the table to be copied:
SET #lastcopied =
(SELECT
IF(MAX(a.exp_inotech_id)>0, MAX(a.exp_inotech_id), 0) AS lastcopied
FROM
kll_export_to a
WHERE exp_tezgah = 'A2015-0056');
Then, select and add the records to the destination table:
INSERT INTO kll_export_to
(SELECT * FROM
kll_export_from f
GROUP BY f.exp_inotech_id
HAVING COUNT(f.exp_inotech_id) = 1 AND exp_tezgah = 'A2015-0056' AND f.exp_inotech_id > #lastcopied
ORDER BY exp_inotech_id
LIMIT 1000);

determine if mysql values are in same row

How would this be done? I would like to search the database row by row. I might even print out the entire list of the database row by row. But I would also like to show record 1400 for example and determine the info on that row - such as name, gender and country.
Is it possible to use the rownum function to get this done? Or would I need to use a where in the query? But even so how would I determine the row number? Thanks.
Make one column as ID, make it PK and auto_increment. Then your query shell be something like this for #1400 row:
$pdo
->prepare(
"SELECT `name`, `gender`, `country`
FROM `foo_table` WHERE `id` = :id"
)
->execute([':id' => 1400]);
You can use user defined variables to get your rownumber in MySQL
set #nr = 0;
Now you can use this variable (same connection!) in your query
SELECT
#nr := (#nr + 1) rownumber,
*
FROM
table
see: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
do your select and add
LIMIT n,1
this will skip to n-th element(1400) and show just one result

Insert id from from one table and insert it into another one. Mysql + PHP [duplicate]

This question already has answers here:
How to get the last field in a Mysql database with PHP?
(5 answers)
Closed 9 years ago.
I am working on a register user form and I have two tables in mysql. What I want to do is when a new user has registered, take the id (which primary key) of that user and insert it into another table. What is the best way to do that?
Thanks in advance.
You need to use mysql_insert_id for this purpose. Here is an example:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
First insert the user details into users table and get inserted user id using mysql_insert_id. and use that user id to insert into another table.
AS ON GETTING IT ON PHP
GET LAST INSERT ID HERE
BUT IF YOU INTEND TO GET IT USING MYSQL QUERY
use stored procedure to store last insert id to a variable then generete your second query
INSERT INTO T1 (col1,col2) VALUES (val1,val2);
SET #last_id_in_T1 = LAST_INSERT_ID();
INSERT INTO T2 (col1,col2) VALUES (#last_id_in_T1,val2);
or direct insert after your first insert
INSERT INTO T1 (col1,col2) VALUES (val1,val2);
INSERT INTO T2 (col1,col2) VALUES (LAST_INSERT_ID(),val2);
Use any of transaction query for writing:
Following is in CI pattern:
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('AN SQL QUERY...');
if(!$this->db->trans_complete()){
$this->db->trans_rollback();
}
$query1= "INSERT INTO employee ( username, email,...)
VALUES ('".$_POST["username"]."', ...)";
if($result1 = mysql_query($query1))
{
$emp_id = mysql_insert_id(); // last created id by above query
$query2= "INSERT INTO dept ( emp_id, dept_name, ...)
VALUES ('".$emp_id."', '".$_POST["dept_name"]."',...)";
if($result2 = mysql_query($query2))
{
//success msg
}
}
Another neat way to do it at do it at Database level itself is to used Stored Procedure
Look at this solution to see an example of how to do it. You will have to check how Stored procedures work in your specific database to get the specific syntax. This makes it error free even if someone refactors or moves around the code and more efficient.
Using trigger the Mysql on database-level. For example, I have two tables:
user(id int primary key, nombre varchar(50));
replication(id_r int primary key, nombre_r varchar(50));
Using the trigger:
create trigger user_r after insert on user
for each row
insert into replication(id_r, nombre_r)
select u.id, u.nombre
from user u
where u.id=NEW.id and u.nombre=NEW.nombre;

Access last row added to table - PHP

I have a simple sql query adding a new row to a database and need it to return the a field back to Javascript. The field does Auto_increment but stupildy I called it 'itemId' so mysql_insert_id doesnt work and I don't think I have time to go and amend all the php files that use 'itemId'
Here's my code if it helps:
$addMainItem = "INSERT INTO newsItems (itemId, title, date, tags, location, latitude, longitude, visibleFrontpage, introText, fullDome, liveEvent, customServing, visitorAttraction, retail, digitalCinema, visiblePublic, thumbPath, links, smallDesc) VALUES ('','$title','$date','$tags','$loco','$lat','$long','$visiFront','$intro','$dome ','$live','$custom','$attrac','$retail','$cinema','$public','$thumbPath','$links','$smallDesc')";
$result = mysql_query($addMainItem) or die('error '.mysql_error());
if($result) echo (mysql_insert_id());
I've never heard that naming a column itemId breaking mysql_isert_id().
But you can just select the last inserted record if auto_increment is working.
SELECT * FROM newsItems ORDER BY itemId DESC LIMIT 1
You can put the select statement into a transaction with the insert statement if you're using innoDB and you're worried about a race condition.
mysql_query("SELECT LAST_INSERT_ID()");
Isn't it what are you looking for?

Categories