i want to insert a database table into another one which has more columns. I need all records of it. What i tried is following which is not working and does not give me an error message:
$sql = mysqli_query($con, "SELECT * FROM table1");
while ($row = mysqli_fetch_array($sql)) {
$sql1 = mysqli_query($con, "INSERT INTO table2
(uid,
pid,
tstamp,
crdate)
VALUES ('',
'".$row['value1']."',
'".$row['value2']."',
'".$row['value3']."'");}
you can directly do it like this, that's much faster and better than fetching the data and iterating over it.
insert into table2(uid,pid,tstamp,crdate)
select value1,value2,value3,value4 from table1
you forget close " :
mysqli_query($con, "INSERT INTO table2
(uid,
pid,
tstamp,
crdate)
VALUES ('',
'".$row['value1']."',
'".$row['value2']."',
'".$row['value3']."');");
also you can do this in query by select into to reduce consuming time:
INSERT INTO table2 (uid,pid,tstamp,crdate)
SELECT '',val1,val2,val3 FROM table1;
Related
This question already has answers here:
Retrieve id of each INSERT statement in multi query
(5 answers)
Closed 3 years ago.
I've been working with this project, now am stuck where i have to insert the id of the first query of which it identifies the relations of that table to others, i want the id of the first query to be saved as a variable and then be inserted into the following queries
I've tried to set value to be used but its not working, as i want all these to work in one multi-query, down here are some code of the queries
$query = "INSERT INTO guests (
user_id,
first_name,
last_name,
nationality,
status,
sign_up)
VALUES (
'$user_id',
'$first_name',
'$last_name',
'$nationality',
'$status',
NOW());";
$query = "SELECT #last_id := LAST_INSERT_ID();"
$query .= "INSERT INTO bookings (
user_id,
guest_id,
coming_from,
going_to,
date_in,
date_out,
sign_up)
VALUES (
'$user_id',
#last_id,
'$coming_from',
'$going_to',
'$date_in',
'$date_out',
NOW());";
$query .= "INSERT INTO preference (
guest_id,
prefer,
alergy,
sign_up)
VALUES (
#last_id,
'$prefer',
'$alergy',
NOW());";
$query .= "INSERT INTO rooms (
user_id,
guest_id,
room_number,
room_type,
room_price,
sign_up)
VALUES (
'$user_id',
#last_id,
'$room_number',
'$room_type',
'$room_price',
NOW())";
if(mysqli_multi_query($conn, $query))
{
echo "Guest Received successfully!";
} else {
echo "Failed! Data input error!";
}
}
i expected it to fetch the first query guest id and insert it into #last_id column, Kindly any ideas?
On occasion, I've had to use this:
SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
or
SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_name = your_tablename' AND table_schema = DATABASE( ) ;
Perhaps that will work for you
References:
https://dev.mysql.com/doc/refman/8.0/en/show-table-status.html
https://php.net/manual/en/mysqli.insert-id.php
I need to update and insert around 1 Million data in mysql data base, when I am using the following code It takes more time. please suggest how can i update and insert the data fastly?
include('db.php');
include('functions.php');
$functions=new functions();
set_time_limit(0);
$column="rank"."_".date("Y-m-d");
$count=$functions->get_row("SELECT COUNT(id) as ct FROM alexa_filename WHERE status=1");
if($count->ct==100){
$alexas=$functions->get_result("SELECT DISTINCT (`sitename`),`$column` FROM `top-2m` WHERE `status`=0 LIMIT 100" );
if(!empty($alexas)){
foreach($alexas as $alexa){
$site_name=$alexa->sitename;
echo $site_name;
$rank=$alexa->$column;
$table=$functions->find_table_name($site_name);
$count=$functions->get_row("SELECT COUNT(site_name) as ct FROM `$table` WHERE site_name='$site_name'");
if($count->ct==0){
$functions->set_query("INSERT INTO `$table`( `site_name`, `other_id`, `response`, `category`, `updated`, `site_update`, `wot_update`, `social_update`, `google_update`, `server_update`, `alexa_update`, `backlinks_update`, `antivirus_update`, `key`, `desc`, `google_backlink`, `images_url`, `images`, `tag`, `view_count`, `title`, `api_update_time`, `table_name`, `user_added_similar`, `auto_similar`, `comments`, `status`) VALUES ('$site_name',0,0,0,0,0,0,0,0,0,$rank,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)");
$functions->set_query("UPDATE `top-2m` SET `status`=1 WHERE sitename ='$site_name'");
}else{
$functions->set_query("UPDATE `$table` SET `alexa_update`=$rank WHERE site_name='$site_name'");
$functions->set_query("UPDATE `top-2m` SET `status`=2 WHERE sitename ='$site_name'");
}
}
}else{
mail("aaa#aaa.com","Alexa_Cron_Update_Status","aaaRank Is Succes fully Updated");
}
}
You can insert/update multiple rows using INSERT ... ON DUPLICATE KEY
UPDATE.
Reindex your database.
Use Prepared Mysql Statements.
Also If you are using Linux/ubuntu try to use terminal instead of browser. It will make a lot difference.
Concatenate your INSERT and UPDATE Query to $qry and apply
$functions->set_query($qry);
once your looping done. This will take less time.
Edited:
Example:
$qry = "Insert into table values('', '', '','', '')";
$qry .= "insert into table2 values('', '', '','', '')";
$qry .= "insert into table3 values('', '', '','', '')";
$qry .= "update table3 set field = 'something' ";
and out of condition or loop.
$functions->set_query($qry);
what im trying to figure out is how do i find something in my MySQL database and then replacing another row. Example
mysqli_query($con,"INSERT INTO persons (FirstName, LastName, Age)
VALUES ('$_POST[custom]', '$_POST[receiver_email]','$_POST[mc_gross]')");
$result = mysqli_query($con,"SELECT * FROM Persons
WHERE FirstName='bjarne'");
mysqli_query($con,"INSERT INTO persons (LastName)
VALUES ('$_POST[item_name]')");
Here i would like it to find where FirstName is "bjarne" and then replace his LastName with '$_POST[item_name]' in this case.
Try this:
$result = mysqli_query($con,"UPDATE `Persons` SET `LastName`='".$_POST['item_name']."'
WHERE `FirstName`='bjarne'");
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']."')");
Is this possible if I want to insert some data into two tables simultaneously?
But at table2 I'm just insert selected item, not like table1 which insert all data.
This the separate query:
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
Can I insert COUNT(model) at table2?
I have found some script, could I use this?
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$result = mysql_query($sql,$conn);
if(isset($model))
{
$model = mysql_insert_id($conn);
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
$result = mysql_query($sql,$conn);
}
mysql_free_result($result);
The simple answer is no - there is no way to insert data into two tables in one command. Pretty sure your second chuck of script is not what you are looking for.
Generally problems like this are solved by ONE of these methods depending on your exact need:
Creating a view to represent the second table
Creating a trigger to do the insert into table2
Using transactions to ensure that either both inserts are successful or both are rolled back.
Create a stored procedure that does both inserts.
Hope this helps
//if you want to insert the same as first table
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (one,two, three) VVALUES('$one','$two','$three')";
$result = #mysql_query($qry2);
//or if you want to insert certain parts of table one
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (two) VALUES('$two')";
$result = #mysql_query($qry2);
//i know it looks too good to be right, but it works and you can keep adding query's just change the
"$qry"-number and number in #mysql_query($qry"")
its cant be done in one statment,
if the tables is create by innodb engine , you can use transaction to sure that the data insert to 2 tables
<?php
if(isset($_POST['register'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$website = $_POST['website'];
if($username == NULL OR $password == NULL OR $email == NULL OR $website == NULL) {
$final_report2.= "ALERT - Please complete all fields!";
} else {
$create_chat_user = mysql_query("INSERT INTO `chat_members` (`id` , `name` , `pass`) VALUES('' , '$username' , '$password')");
$create_member = mysql_query("INSERT INTO `members` (`id`,`username`, `password`, `email`, `website`) VALUES ('','$username','$password','$email','$website')");
$final_report2.="<meta http-equiv='Refresh' content='0; URL=login.php'>";
}
}
?>
you can use something like this. it works.
In general, here's how you post data from one form into two tables:
<?php
$dbhost="server_name";
$dbuser="database_user_name";
$dbpass="database_password";
$dbname="database_name";
$con=mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to the database:' . mysql_error());
$mysql_select_db($dbname, $con);
$sql="INSERT INTO table1 (table1id, columnA, columnB)
VALUES (' ', '$_POST[columnA value]','$_POST[columnB value]')";
mysql_query($sql);
$lastid=mysql_insert_id();
$sql2=INSERT INTO table2 (table1id, table2id, columnA, columnB)
VALUES ($lastid, ' ', '$_POST[columnA value]','$_POST[columnB value]')";
//tableid1 & tableid2 are auto-incrementing primary keys
mysql_query($sql2);
mysql_close($con);
?>
//this example shows how to insert data from a form into multiples tables, I have not shown any security measures