Running an SQL query multiple times - php

I need to run this query 100 times to input data into my MySQL database. ID auto increments. Not concerned about incrementing the table Name column. Just need to fill the database. What is the best way to go about this without having to copy/paste 100 times?
"INSERT INTO `tables`(id, name, assigned_seating, open_seating, position) VALUES ('', 'Table 1', 0, 1, '')";

All you need is an existing table with at least 100 rows. I will use information_schema.columns as example:
INSERT INTO `tables`(id, name, assigned_seating, open_seating, position)
SELECT null, 'Table 1', 0, 1, ''
FROM information_schema.columns
LIMIT 100;
Demo: http://rextester.com/DMSC23853

If anyone sees this in the future, this is the best answer
public function addbatch()
{
for ($i = 1; $i <= 100; $i++)
{
$tableName = "Table " . $i;
$q = "INSERT INTO `tables`(id, name, cap, assigned_seating, open_seating, position) VALUES ('', '".$tableName."', 10, 0, 1, '')";
$this->db->query($q);
}
}
call function once. Make sure to delete when done though!

You can do a Batch insert:
insert into Table
(column1, column2)
VALUES
('value 1', 'value2') ,
('value3', 'value4')
You can do as many rows as you want as long as you separate them by comas.

$vals='';
for ($i = 0; $i < 100; $i++) {
$vals.="('Table 1', 0, 1, ''),";
}
$vals=rtrim($vals,',');
mysqli_query($dbh, 'INSERT INTO `tables`(name, assigned_seating, open_seating, position) VALUES ' . $vals);
assumed id was auto incremented so just leave it out of the query

try this:
DELIMITER $$
DROP PROCEDURE IF EXISTS `multipleInsert` $$
CREATE PROCEDURE `multipleInsert`(in n int)
BEGIN
DECLARE cont int default 0;
WHILE cont < n DO
INSERT INTO `tables`(id, name, assigned_seating, open_seating, position) VALUES ('', 'Table 1', 0, 1, '');
set cont = cont + 1;
end while;
END $$
DELIMITER ;
Call Procedure:
call multipleInsert(100);

Related

MySQL: Insert new record using MAX value of a column in the same table

I need to INSERT a new record, using the MAX value of the position column plus one, in the newly inserted row. So if the MAX value is 14, the next inserted row's position column value should be 15.
This is my current code, which is working but it needs 2 separate queries:
# get position order
$sql = 'SELECT MAX(position) FROM store_item_photo WHERE id_item = 3';
$stmt = cnn()->prepare($sql);
$stmt->execute();
$position = $stmt->fetchColumn();
$position++;
# photo: new record
$sql = 'INSERT INTO store_item_photo (id_item, position) VALUES (3, :position)';
$stmt = cnn()->prepare($sql);
$stmt->bindValue(':position', $position, PDO::PARAM_INT);
$stmt->execute();
I wanted to know if there is some way to achieve the same result with just one query:
# photo: new record (one query)
$sql = 'INSERT INTO store_item_photo (id_item, position) VALUES (3, (SELECT MAX(position) FROM store_item_photo WHERE id_item = 3) + 1)';
$stmt = cnn()->prepare($sql);
$stmt->execute();
That test is throwing an error. Is it possible to achieve this with a similar approach?
I built the schema in sqlfiddle: http://sqlfiddle.com/#!9/228058/1
If you want to use a subquery in an Insert you don't have to use VALUES
Try this query:
INSERT INTO store_item_photo (id_item, position)
SELECT
3 AS id_item,
MAX(position) + 1
FROM store_item_photo
WHERE id_item = 3;
Try this query :
$sql = 'INSERT INTO store_item_photo (id_item, position) VALUES (3, ((SELECT MAX(position) FROM store_item_photo WHERE id_item = 3) + 1))';
$stmt = cnn()->query($sql);

Retrieve output variable from MySQL stored procedure using CakePHP

I'm attempting to call a stored procedure using CakePHP.
Currently the returned values are comprised of the first recordset from the first SQL select statement in the stored procedure.
Even though the output variable is set in the stored procedure (ie. select #project_id into project_id), it doesn't show in the var_dump of the query result.
Stored Procedure:
CREATE DEFINER = 'admin'#'%'
PROCEDURE thebuggenie.cmdb_project_team_init(
IN project_name VARCHAR(200),
IN project_key VARCHAR(200),
IN project_homepage VARCHAR(200),
IN team_name VARCHAR(200),
OUT project_id INT(10))
BEGIN
-- start transaction
start transaction;
-- init variables
set #project_id = 0;
set #team_id = 0;
set #assoc_count = 0;
set #scope_id = 1;
-- select team and set variable
select #team_id := id
from tbg3_teams
where name = team_name;
-- if team_id = 0, insert team and set variable
if #team_id is NULL or #team_id = '' or #team_id = 0 then
-- insert new project
insert into tbg3_teams(ondemand, name, scope) values(0, team_name, #scope_id);
-- set team_id variable
set #team_id = LAST_INSERT_ID();
end if;
-- select project and set variable
select #project_id := id
from tbg3_projects
where name = project_name;
-- if project_id = 0, insert project and set variable
if #project_id is NULL or #project_id = '' or #project_id = 0 then
-- insert project
insert into tbg3_projects (name, locked, use_scrum, `key`, homepage, deleted, owner_team, scope, workflow_scheme_id, issuetype_scheme_id) values(project_name, 0, 1, project_key, project_homepage, 0, #team_id, #scope_id, 1, 1);
-- set project_id variable
set #project_id = LAST_INSERT_ID();
end if;
select #assoc_count := count(*)
from tbg3_projectassignedteams
where uid = #team_id
and project_id = #project_id;
if(#assoc_count = 0 and #project_id > 0 and #team_id > 0) then
insert into tbg3_projectassignedteams (project_id, role_id, uid, scope) values(#project_id, 35, #team_id, #scope_id);
end if;
-- setup default views
INSERT INTO tbg3_dashboard_views (name, view, pid, tid, target_type, scope) VALUES (101, 0, 0, #project_id, 2, 1);
INSERT INTO tbg3_dashboard_views (name, view, pid, tid, target_type, scope) VALUES (102, 0, 0, #project_id, 2, 1);
INSERT INTO tbg3_dashboard_views (name, view, pid, tid, target_type, scope) VALUES (110, 0, 0, #project_id, 2, 1);
INSERT INTO tbg3_dashboard_views (name, view, pid, tid, target_type, scope) VALUES (105, 0, 0, #project_id, 2, 1);
INSERT INTO tbg3_dashboard_views (name, view, pid, tid, target_type, scope) VALUES (106, 0, 0, #project_id, 2, 1);
INSERT INTO tbg3_dashboard_views (name, view, pid, tid, target_type, scope) VALUES (111, 0, 0, #project_id, 2, 1);
commit;
-- return values
select #project_id INTO project_id;
END
PHP Code:
$sql = "call thebuggenie.cmdb_project_team_init(";
$sql .= '\''.$results[0]['Asset']['project_name'].'\'';
$sql .= ',\''.$results[0]['Asset']['project_name'].'\'';
$sql .= ',\'\'';
$sql .= ',\''.$results[0]['Repository']['team_name'].'\'';
$sql .= ',#project_id';
$sql .= ');';
$sql .= 'select #project_id as project_id';
var_dump($sql);
$results = $this->Asset->query($sql);
print_r($results);
PHP Code outputs:
string 'call thebuggenie.cmdb_project_team_init('CMDB','CMDB','','team-app-platforms',#project_id);select #project_id as project_id;'
Array ( [0] => Array ( [0] => Array ( [#team_id := id] => 6 ) ) )
Note: I haven't finalized error trapping yet.
I ended up using this:
$sql = "call thebuggenie.cmdb_project_team_init(";
$sql .= '\''.$results[0]['Asset']['project_name'].'\'';
$sql .= ',\''.$results[0]['Asset']['project_name'].'\'';
$sql .= ',\'\'';
$sql .= ',\''.$results[0]['Repository']['team_name'].'\'';
$sql .= ',#project_id';
$sql .= '); select #project_id as project_id';
var_dump($sql);
$mysqli = new mysqli("DB_HOST", "DB_USER", "DB_PWD", "DATABASE");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$out = array();
if($mysqli->multi_query($sql))
{
do
{
if($result=$mysqli->store_result())
{
while($row=$result->fetch_row())
{
array_push($out, $row);
}
$result->free();
}
}while($mysqli->more_results() && $mysqli->next_result());
}
$mysqli->close();
$out[3][0] contained the value I was looking for.

insert single set of data multiple times mysql

I have to insert single set of data multiple times , say n rows.
INSERT INTO MyTable VALUES ("John", 123, "US");
Can I insert all n rows in a single SQL statement?
here n is dynamic value n is user input , how to make insert query n times , any idea.
$sql = "INSERT INTO `mytable` VALUES(`field1`,`field2`,`field3`) VALUES ";
$count = 5;
for($i=0;$i<$coutn;$i++)
{
$sql .= " ('john','123','us' )";
}
is this correct way..
Yep, this can be done easily, it should look something like this:
INSERT INTO MyTable VALUES ("John", 123, "US"), ("Carl", 123, "EU"), ("Jim", 123, "FR");
However, it is good programming practice to specify the columns of your table in the query, for example:
INSERT INTO MyTable (Column1, Column2, Column3)
VALUES ("John", 123, "US"), ("Carl", 123, "EU"), ("Jim", 123, "FR");
EDIT : You can build your query like this (in for cycle), the $total is your user input:
$sql = "INSERT INTO MyTable (Column1, Column2, Column3) VALUES";
//Build SQL INSERT query
for ($i = 1; $i <= $total; $i++) {
$sql .= " ($value1, $value2, $value3), ";
}
//Trim the last comma (,)
$sql = rtrim($sql,",");
//Now, the $sql var contains the complex query.
$result = mysql_query($sql);
As you can see we do not execute the INSERT statement in the loop, but rather we build the SQL query text and then we will execute it in one pass.

How to select the last inserted ID on concatenated values

I'm trying to get the last inserted id of multiple inserted rows.
record_id is auto increment
$sql = "INSERT INTO records (record_id, user_id, status, x) values ";
$varray = array();
$rid = $row['record_id'];
$uid = $row['user_name'];
$status = $row['status'];
$x = $row['x'];
$varray[] = "('$rid', '$uid', '$status', '$x')";
$sql .= implode(',', $varray);
mysql_query($sql);
$sql2 = "INSERT INTO status_logs (id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES";
$varray2[] = "(' ', mysql_insert_id(), '$status', '$uid', '$x')";
$sql2 .= implode(',', $varray2);
mysql_query($sql2);
This is the result:
INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', mysql_insert_id(), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active'), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active')
There is no value for mysql_insert_id().
You're mixing php function mysql_insert_id() and SQL INSERT statement syntax.
Either use MySQL function LAST_INSERT_ID() in VALUES clause of INSERT statement
INSERT INTO records (user_id, notes, x) VALUES('1237615', 'this is a note', 'active');
INSERT INTO status_logs (record_id, status_id, date, timestamp, notes, user_id, x)
VALUES(LAST_INSERT_ID(), '1', ...);
^^^^^^^^^^^^^^^^^
or retrieve the last inserted id by making a separate call to mysql_insert_id() right after first mysql_query(). And then use that value when you as a parameter to your second query.
$sql = "INSERT INTO records (user_id, ...)
VALUES(...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
$last_id = mysql_insert_id();
// ^^^^^^^^^^^^^^^^^^
$sql2 = "INSERT INTO status_logs (record_id, ...)
VALUES $last_id, ...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
Note:
You don't need to specify auto_incremented column in column list. Just omit it.
Use at least some sort of error handling in your code
On a side note: Instead of interpolating query strings and leaving it wide open to sql-injections consider to use prepared statements with either mysqli_* or PDO.
Unless I mis-reading your code, you're calling the PHP function mysql_insert_id from within the SQL?
What you need to do is grab that into a PHP variable first, then use the variable in the SQL. Something like this:
// Run the first query
mysql_query($sql);
// Grab the newly created record_id
$recordid= mysql_insert_id();
Then in the second INSERTs just use:
$varray2[] = "(' ', $recordid, '$status', '$uid', '$x')";

Insert query does't insert data to mysql database table

i have a recipe table and ingredient table the primary key of both tables are auto increament and primary key of recipe is foreign key in ingredient. i post data from html to php.Note that my ingredient textboxes are generated dynamically and successfully post the data to php script. posted data is correct when i insert this data to table my query working fine but data is not added to mysql table. my code and output is
$sql = "insert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', '$name','$overview','$category','$time','$TARGET_PATH')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
$rec_id = mysql_insert_id();
and for ingredient
$ingredient = $_POST['ingredient'];
$amount = $_POST['amount'];
$integer = 0;
while (count($ingredient)>$integer) {
if (($ingredient[$integer] <> "") && ($amount[$integer] <> "")){
$sql = "INSERT INTO `cafe`.`ingredients` (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";
mysql_query($sql);
echo $sql."";
}
else{
echo "ingredient number ".($integer+1)." is missing values and cannot be inserted.";
}
$integer = ($integer + 1);
}
when i echo the queries the out put is nsert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', 'demo recipe','no overview','meal','10/12/10 : 13:02:33','http://www.localhost/cafe/pics/demo.gif')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient one', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient two', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient three', '3gm', '29')
but when i see the mysql table or retriew data from ingredient there is no data in ingredient.
You have an extra , after rec_id.
Remove it, so it looks like
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id) VALUES ('', 'ingredient one', '3gm', '29')
And you will be OK
There seems to be a syntax error in your code:
if (($ingredient[$integer] "") && ($amount[$integer] ""))
^^ ^^
Looks like you are missing a comparison operator.
You might want to verify if you are using a BEGIN call and not committing after INSERT. You can refer to http://www.devarticles.com/c/a/MySQL/Using-Transactions-with-MySQL-4.0-and-PHP/
in that scenario.
When insert doesnt throw exceptions and doesnt insert data there are I think a couple of options
1) you use transaction somewhere and rollback it
2) your select query is bad and data is there, but you just dont select it
remove cafe from the query
$sql = "INSERT INTO ingredients (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";

Categories