insert single set of data multiple times mysql - php

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.

Related

PHP - date(time) insert into DB

I'm using a time method:
$time= date('h:i:s');
What I want is to put this time into database in mySQL,
I used:
$query = mysqli_query($conn, "INSERT INTO tab ('ltime') VALUES ($time)"); but it's not working
Where tab is a table and a ltime is a Column with time Type.
What am I doing wrong?
Regards
Your query will goes like this.
$query = mysqli_query($conn, "INSERT INTO tab (ltime) VALUES ('$time')");
Your query should be like this
$query = mysqli_query($conn, "INSERT INTO tab (ltime) VALUES ($time)");
Columns and tables should have backticks and not single quotes
INSERT INTO `tab` (`ltime`) VALUES ($time)
$query = mysqli_query($conn, "INSERT INTO tab (ltime) VALUES ($time)");
Don't use '' when assigning the column name
The first way specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)VALUES (value1, value2, value3, ...);
If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query
INSERT INTO table_name VALUES (value1, value2, value3, ...);
In your case:
$query = mysqli_query($conn, "INSERT INTO tab (ltime) VALUES ($time)");
there is no need to single quote with column name:
Reference: https://www.w3schools.com/sql/sql_insert.asp

Running an SQL query multiple times

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);

Loop an MySQL query in PHP with DBH

everbody.
I have a array I want to store in my database. Each element in each row. So I created a loop with a query using DBH. As normal queries (with no loop) go though with no problem, the query in the loop does not work. How should I correct my code?
for($i=0;$i<$count($array);$i++)
{
$stmt = $dbh->prepare("INSERT INTO table (column1, column2) VALUES (:value1, :value2)");
$stmt->bindValue(':value1', $value1[$i]);
$stmt->bindValue(':value2', $value2[$i]);
$stmt->execute();
}
Even this variant doesnt work
for($i=0;$i<$count($array);$i++)
{
$stmt[$i] = $dbh->prepare("INSERT INTO table (column1, column2) VALUES (:value1, :value2)");
$stmt[$i]->bindValue(':value1', $value1[$i]);
$stmt[$i]->bindValue(':value2', $value2[$i]);
$stmt[$i]->execute();
}
I have fixed the problem by building the query in one loop and executing it outside the loop
$query = "";
for($i=0;$i<$count;$i++)
{
$query .= "INSERT INTO `table` (`column1`, `column2`) VALUES ('".$velue1[$i]."', '".$value2[$i]."'); ";
}
rtrim($query, "; ");
$stmt = $dbh->prepare($query);
$stmt->execute();

Insert items in a table using a for loop

I've deleted an old, badly worded question and am reposting to not waste anyone's time.
I'm trying to query stuff from two tables, rooms and items. Then in a nested loop, create an entry in a 3rd table using info from the first two.
'For each room, insert ALL the standard items'
<?php
mysql_connect("******", "****", "******") or die(mysql_error());
mysql_select_db("MaintenanceTracking") or die(mysql_error());// Check connection
//collect standard items names
$stditemdata = 'SELECT * FROM `StandardItems`';
$itemresult = mysql_query($stditemdata) or die("Couldn't execute query. ". mysql_error());
$itemarray = mysql_fetch_array( $itemresult ));
//collect room info
$roomdata = 'SELECT * FROM `Rooms`';
$roomresult = mysql_query($roomdata) or die("Couldn't execute query. ". mysql_error());
//repeat for each room
while($room = mysql_fetch_array( $roomresult ))
{
//repeat for each item
for ($i = 0; $i <= count($itemarray); $i++)
{
mysqlquery("INSERT into Items
(ItemNumber, Name, LocationCode)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
}
}
?>
I'm pretty new to php and must appologize that the syntax sometimes gets me stumped...I notoriously miss the semi-colon at the ends of rows, for example.
A million thanks in advance to anyone and everyone who can help me out.
kindest regards
mysqlquery("INSERT into Items
(ItemNumber, Name, LocationCode)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
It should be
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
You use mysqlquery instead of mysql_query
To avoid duplication of mysql-reserved names (f.e. date, table etc) use this syntax
`column_name` or `table_name`
UPDATE
oh.. i miss! look, you try to write some strings into DB here
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
All strings in queries must be concluded in quotes single ' or double ", so your query should looks like
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, \"$itemarray['Name']\", \"$room['LocationCode']\")");
(i use \ symbol before " to escape quote), but i suggest you to use syntaxys like this:
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, '".$itemarray['Name']."', '".$room['LocationCode']."')");

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