Insert all in mysql [duplicate] - mysql

Assuming that I have two tables, names and phones,
and I want to insert data from some input to the tables, in one query. How can it be done?

You can't. However, you CAN use a transaction and have both of them be contained within one transaction.
START TRANSACTION;
INSERT INTO table1 VALUES ('1','2','3');
INSERT INTO table2 VALUES ('bob','smith');
COMMIT;
http://dev.mysql.com/doc/refman/5.1/en/commit.html

MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...
INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)

Old question, but in case someone finds it useful... In Posgresql, MariaDB and probably MySQL 8+ you might achieve the same thing without transactions using WITH statement.
WITH names_inserted AS (
INSERT INTO names ('John Doe') RETURNING *
), phones_inserted AS (
INSERT INTO phones (id_name, phone) (
SELECT names_inserted.id, '123-123-123' as phone
) RETURNING *
) SELECT * FROM names_inserted
LEFT JOIN phones_inserted
ON
phones_inserted.id_name=names_inserted.id
This technique doesn't have much advantages in comparison with transactions in this case, but as an option... or if your system doesn't support transactions for some reason...
P.S. I know this is a Postgresql example, but it looks like MariaDB have complete support of this kind of queries. And in MySQL I suppose you may just use LAST_INSERT_ID() instead of RETURNING * and some minor adjustments.

I had the same problem. I solve it with a for loop.
Example:
If I want to write in 2 identical tables, using a loop
for x = 0 to 1
if x = 0 then TableToWrite = "Table1"
if x = 1 then TableToWrite = "Table2"
Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT
either
ArrTable = ("Table1", "Table2")
for xArrTable = 0 to Ubound(ArrTable)
Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT
If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.

my way is simple...handle one query at time,
procedural programming
works just perfect
//insert data
$insertQuery = "INSERT INTO drivers (fname, sname) VALUES ('$fname','$sname')";
//save using msqli_query
$save = mysqli_query($conn, $insertQuery);
//check if saved successfully
if (isset($save)){
//save second mysqli_query
$insertQuery2 = "INSERT INTO users (username, email, password) VALUES ('$username', '$email','$password')";
$save2 = mysqli_query($conn, $insertQuery2);
//check if second save is successfully
if (isset($save2)){
//save third mysqli_query
$insertQuery3 = "INSERT INTO vehicles (v_reg, v_make, v_capacity) VALUES('$v_reg','$v_make','$v_capacity')";
$save3 = mysqli_query($conn, $insertQuery3);
//redirect if all insert queries are successful.
header("location:login.php");
}
}else{
echo "Oopsy! An Error Occured.";
}

Multiple SQL statements must be executed with the mysqli_multi_query() function.
Example (MySQLi Object-oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Related

Converting empty string into null

I have a form that POST value keeps coming as "" empty string into a unique SQL field.
It has to be unique as the field is optional but jet it can not have 2 same values. The unique value does allow null multiple values.
I don't even want to say what I tried to do, I'm trying to fix this for last few days.
Closest that I got is putting '$OIB'=IF('$OIB'='',NULL,'$OIB' into NSERT INTO statement, then i get null values into a database but for some reason when the number is entered into OIB form field it puts number 1 into a database...
$result = mysqli_query($conn, "SELECT OIB, NAZIV FROM STRANKEP WHERE OIB = '$OIB' OR NAZIV = '$NAZIV'");
if(mysqli_num_rows($result) == 0) {
// row not found, do stuff...
$sql = "INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES ('$NAZIV', CASE WHEN '$OIB' = '' THEN 'NULL', '$EMAIL', '$ADRESA', '$TELEFON')";
$query = mysqli_query($conn, $sql);
This solution gets me null but not the real $OIB when entered into form, it just puts number 1.
$result = mysqli_query($conn, "SELECT OIB, NAZIV FROM STRANKEP WHERE OIB = '$OIB' OR NAZIV = '$NAZIV'");
if(mysqli_num_rows($result) == 0) {
// row not found, do stuff...
$sql = "INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES ('$NAZIV', '$OIB'=IF('$OIB'='',NULL,'$OIB'), '$EMAIL', '$ADRESA', '$TELEFON')";
$query = mysqli_query($conn, $sql);
Thank you in advance for the help.
Try
CASE '$OIB' WHEN '' THEN NULL ELSE '$OIB' END
You can use also IF Clause
Like so
INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES
('$NAZIV', IF('$OIB' = '', NULL,'$OIB'), '$EMAIL', '$ADRESA', '$TELEFON');
But as mentioned in my comment use prepared statements like in PDO https://phpdelusions.net/pdo#prepared
I would recommend nullif(). It is a built-in standard function to do exactly this:
nullif(?, '')
Note: Do not munge queries with constant values. That makes the code subject to SQL injection attacks. And it can introduce very hard-to-debug errors. Use parameters!

Single INSERT query for multiple records using Prepared statement [duplicate]

This question already has answers here:
PDO Prepared Inserts multiple rows in single query
(21 answers)
Closed 7 years ago.
Here's a fairly basic PHP PDO snippet that accesses a MySQL table named "Users" and inserts rows of data to it using a prepared statement and multiple bindings:
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO Users (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
// insert another row
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
....
As can be seen, this involves an indefinite number of queries since every row-insert takes an execute() of its own. I am attempting to reduce the number of queries and my goal is to have a single loop create a single INSERT query for all the records being inserted. Is it possible? Without prepared statement it's very easy and I can make it work but I am lost with prepared.
It's enough to concatenate strings with coma (,) to act as one parameter.
$stmt->bindParam(':firstname', $firstname[0] . ',' . $firstname[1]);

Mysql - move and replace columns

We have two databases A and B and we want to move and replace some columns with all values from database A to database B
Database.SourceTable >>> move to >>> Database.TargetTable
A.User1 >>> >>> B.User2
The user table has many columns, but we only want to replace some columns: col1, col2 and col3.
How can i do this?
Thank you
EDIT: I forget to say, that i only want to replace the first 100 columns id's.
I mean each column has more than 100 id's and i want to replace first 100; not all.
As you're not able to move datas from a database to another one with a single connection, you can't do it with a single query, you need to do it manually, or with a third party language.
You'll need to :
get one connection per database
get a PRIMARY KEY on your table user
export datas from databaseA
inject these datas to databaseB
Example with PHP/PDO :
// Create 2 connections
try {
$dbA = new PDO('mysql:dbname=databaseA;host=localhost', 'root', '');
$dbB = new PDO('mysql:dbname=databaseB;host=localhost', 'root', '');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
// Get datas from databaseA
$result = $dbA->query("SELECT id, col1, col2, col3 FROM user");
// Prepare REPLACE query for databaseB
$query = "REPLACE INTO user (id, col1, col2, col3) VALUES";
$values = array();
foreach ($result as $row) {
array_push($values, '('.$row['id'].', "'.$row['col1'].'", "'.$row['col2'].'", "'.$row['col3'].'")');
}
$query .= implode(',', $values);
// Execute REPLACE query on databaseB
$stmt = $dbB->prepare($query);
$stmt->execute();
If table1 on db1 database has t1c1, t1c2,t1c3 columns and you want only t1c1, and t1c3 data be copied into table2 of database db2 with columns t2c1 and t2c2 then
insert into db2.table2( t2c1, t2c2 ) select t1c1, t1c3 from db1.table1
should work for you.
And make sure that you have required privileges set to access data from cross database tables or other objects. And you should also check issues with constraints, if any defined, on table2.

joomla database select and insert query

i am trying to insert another info to joomla (2.5.7) database after user is registered. The user chooses his usergroup and I want the insertion to happen only when the user is in a specific group. So I am trying to use this code to get the group data from the databse first to be used in the insert query. Now it is just a testing ground, later this retrieved value be used in if statement.
This is the code:
function onUserAfterSave($user, $isnew, $success, $msg)
{
if ($isnew && $success) {
$db = &JFactory::getDBO();
$query = "SELECT #__k2_users.group FROM #__k2_users WHERE userID = ".$user['id'];
$db->setQuery($query);
$group = $db->loadResult();
$db->setQuery( 'INSERT INTO #__user_profiles (ordering) VALUES ('.$group.')' );
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
return $this->onAfterStoreUser($user, $isnew, $success, $msg);
}
and this is the error I am getting upon the failed registration:
Column count doesn't match value count at row 1 SQL=INSERT INTO std13_user_profiles (ordering) VALUES ()
If I read it correctly, it means that the select statement is not returning anything but why? Thank you for your help.
UPDATE:
if ($isnew && $success) {
$db = &JFactory::getDBO();
$userId = JArrayHelper::getValue($user, 'id', 0, 'int');
$query = "SELECT #__k2_users.group FROM #__k2_users WHERE userID = ".$userId;
$db->setQuery($query);
$group = $db->loadResult();
$query2 = "INSERT INTO #__user_profiles (ordering) VALUES ('".$group."')";
$db->setQuery($query2);
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
with this code, I don't get any errors and the user is registered and the values are inserted. However the $group is always 0 and based on the value is only 1 or 3 in k2_users table, I am guessing that it returns nothing. I think it may be because the registered user is not stored in the databse yet and it doesn't have his ID yet to look for the group?
UPDATE2:
if ($isnew && $success) {
$count = JRequest::getVar('gender');
if($count == 3) {
$db = &JFactory::getDBO();
$alias = $user['name'];
$table = array(
' '=>'-', 'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj', 'Ž'=>'Z', 'ž'=>'z', 'C'=>'C', 'c'=>'c', 'C'=>'C', 'c'=>'c',
'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
'Õ'=>'O', 'Ö'=>'O', 'ě'=>'e', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
'ÿ'=>'y', 'R'=>'R', 'r'=>'r', " "=>'-', '"'=>'-'
);
$string = strtr($alias, $table);
$alias_low = strtolower($string);
$query = "INSERT INTO #__menu (menutype, title, alias, path, link, type, published, level, component_id, access) VALUES ('stavebnici','".$user['name']."','".$alias_low."','".$alias_low."',
'index.php?option=com_k2&view=itemlist&layout=user&id=".$user['id']."&task=user','component',1,1,10012,1)";
$db->setQuery($query);
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
}
OKAY! I got it working so now I can insert new menu every time a user is created, however th activation link is not created and the registration says that it failed. This is the error:
Duplicate entry '0-1-vojtech-plesner-' for key 'idx_client_id_parent_id_alias_language' SQL=INSERT INTO std13_menu (menutype, title, alias, path, link, type, published, level, component_id, access) VALUES ('stavebnici','Vojtěch Plešner','vojtech-plesner','vojtech-plesner', 'index.php?option=com_k2&view=itemlist&layout=user&id=2789&task=user','component',1,1,10012,1)
The client_id, parent_id and language have values of 1,1 and * abd they are in all the rows so why is it saying it is duplicate?
You need to update that query to 2.5 style.
http://www.theartofjoomla.com/home/9-developer/135-database-upgrades-in-joomla-16.html
is a good article.
You definitely seem to be missing
$query = $db->getQuery(true);
not to mention that you are using & for an object. That usage will generate strict errors.
You can do it with one query:
$query = "
INSERT INTO #__user_profiles (ordering)
SELECT #__k2_users.group
FROM #__k2_users
WHERE userID = " . user['id']
";
But doesn't #__user_profiles have other columns like the user id?
Also You can do it with one query:
$query = "
INSERT INTO #__user_profiles (ordering)
SELECT "YOURJOOMLADBPREFIX"_k2_users.group
FROM "YOURJOOMLADBPREFIX"_k2_users
WHERE userID = " . user['id']
";

How to append a mysql table to another table in a different database

I would like to grab a table from one database and append this data to a table in another database. However, they have similar numbers (including the id) which need to be updated before they can be copied over. Is there a function available that could do this automatically? Or do I need to write a script in between?
So far I've got:
#!/bin/sh
mysqldump -uuser1 -ppw1 database1 table1 > /home/user/public_html/database1.sql --skip-add-drop-table --skip-create-options
mysql -uuser2 -ppw2 database2 < /home/user/public_html/database1.sql
rm /home/user/public_html/database1.sql
You could select from one table and insert it into another. The results will be "appended" to the original data.
insert into new_table (id, name) select old_id, old_name from old_table;
To append a table from one database to a table from an other database
insert into new_database.new_table (id, name) select old_id, old_name from old_database.old_table;
Sounds like something that would be a lot safer to do via script, which seems simple enough - just grab the data from the first DB and perform batch inserts into the other, letting mysql handle the ids itself. This should take about 10-30 LOC in any descent scripting language, and gives you more control over the outcome.
I solved it by creating a php script that creates new connections for each new database. This script empties the main table first before it will append the data of the other tables. Having the first entry on NULL and having the $row[x] start on 1 makes sure it appends.. Don't know if it's the best solution, but it works.
<?php
$db_user = "database_all_usr";
$db_pw = "";
$db_database = "database_all_db";
mysql_connect("localhost", $db_user, $db_pw) or die(mysql_error());
mysql_select_db($db_database) or die(mysql_error());
$sql = "TRUNCATE TABLE table_all";
mysql_query($sql) or die(mysql_error());
copy_table("database1_db","database1_usr","",$db_database,$db_user,$db_pw);
copy_table("database2_db","database2_usr","",$db_database,$db_user,$db_pw);
function copy_table($db_current,$db_user_current,$db_pw_current,$db_host,$db_user_host,$db_pw_host){
mysql_connect("localhost", $db_user_current, $db_pw_current) or die(mysql_error());
mysql_select_db($db_current) or die(mysql_error());
$sql = "SELECT * FROM table";
$result = mysql_query($sql) or die(mysql_error());
mysql_connect("localhost", $db_user_host, $db_pw_host) or die(mysql_error());
mysql_select_db($db_host) or die(mysql_error());
while ($row = mysql_fetch_row($result)) {
$sql = "INSERT INTO table_all VALUES (NULL, '$row[1]', '$row[2]')"; //adapt to the amount of columns
mysql_query($sql) or die(mysql_error());
}
}
?>