How can I merge two tables into one table ?
For example, let say I have table named person with first_name and last_name,gender then I have another table called person_d and this has first_name, last_name, telephone and email.
The new table should contain first_name, last_name, telephone and email,gender
but i want to do that in an automatic way without even know what the fields name are just by using a conditions
Is that possible with sql or i have to do it using php?
I thought that I can create php script and get fields name into two arrays then compare for doubles and add them to new array and delete them after that we will have arrays with no doubles
this is my code
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mydb";
//mysql and db connection
$db = new mysqli($servername, $username, $password, $dbname);
if ($db->connect_error) { //error check
die("Connection failed: " . $con->connect_error);
} else {
}
$query1 = $db->query("SELECT * FROM tablename1");
$query2 = $db->query("SELECT * FROM tablename2");
$table1 = array();
$table2 = array();
$newtable = array();
while ($property = mysqli_fetch_field($query)) { //fetch table field name
array_push($table1,$property->name);
}
while ($property = mysqli_fetch_field($query)) { //fetch table field name
array_push($table2,$property->name);
}
foreach($table1 as $field1) {
foreach($table2 as $field2) {
if ($field1==$field2)
{
array_push($newtable,$field1);
unset($table1[$field1]);
unset($table1[$field2]);
}
}
}
and after that i create new table with fields from arrays side by side
Is this the best way or there is another way to do that ?
no need for PHP in here. This can be done in SQL only.
INSERT INTO new_table (first_name, last_name, telephone, email)
SELECT first_name, lastname, telephone, email
FROM person_d;
And afterwards
INSERT INTO new_table (first_name, last_name)
SELECT first_name, lastname
FROM person
ON DUPLICATE KEY IGNORE;
This requires you make the combination of first and last name UNIQUE
You could of course change the names of the columns.
And I suppose this is an exercise to do only once
Related
I'm creating a signup form and am onto the confirmation email part. I want to find all values associated with one other value in a database.
Ex. I get the "key" that is in the URL, then want to find all the values associated with it. In my database there are 4 columns: STR (the key), USERNAME, PASSWORD, and EMAIL. If I get STR I want to get the username, password, and email that are in the same row as the key and then insert it into another table in the same database.
verify.php:
<?php
$username = $_GET['username'];
$password = $_GET['password'];
$email = $_GET['email'];
$servername = "localhost";
$user = 'usernamelol';
$pass = 'passwordlol';
$dbname = 'vibemcform';
$str = $_GET['str'];
$conn = new mysqli($servername, $user, $pass, $dbname);
/* The variable query gets the "key" from the dont database. I want to compare that value with the other values associated with it. Ex. the variables in the same row as the key. */
$query = mysqli_query($conn, "SELECT * FROM `dont` WHERE STR='".$key."'");
/* Below is my attempt. Feel free to change whatever you want. */
$sql = "SELECT USERNAME, PASSWORD, EMAIL FROM dont";
$result = $conn->query($sql);
if (!$query) {
die('Error: ' . mysqli_error($con));
}
if (mysqli_num_rows($query) > 0) {
if ($result -> num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$sqltwo = "INSERT INTO data (USERNAME, PASSWORD, EMAIL) VALUES ($row["USERNAME"], $row["PASSWORD"], $row["EMAIL"])";
}
}
}
echo 'Successfully verified your email!'; exit;
?>
Why not simpy use the insert ... select syntax?
insert into data(username, password, email)
select username, password, email from dont where str = :key
You can run this query right ahead, and then check how many rows were affected:
If no row was affected, then it means that the select did not bring a row back: so the :key was not found in the database
If a row was affected, then the key was found and the executed row was inserted
Note that you should use parametrized queries so your code is safe from SQL injection (and more efficient as well); recommended reading How can I prevent SQL injection in PHP??
Let's say I have 2 tables in the database, first table is userregistration and 2nd table is userdetails. In table userregistration, the primary key that I use is called id and it is auto increment.
So let's say I have insert one user and the id of the user is 1, and then I want to insert the details of the said user, how do I make sure the id is also the same as in the userregistration table?
Already read about last_insert_id, but I can't understand how to use it.
Here is an example:
$server_name = ""; //Your server name
$user_name = ""; //Database Username
$password = ""; //Database Password
$database_name = ""; //Database Name
// Create a connection
$connnection = new mysqli($server_name, $user_name, $password, $database_name);
//Insert into First Table
$sql = "INSERT INTO user_registration (firstname, lastname)
VALUES ('Firstname', 'Lastname')";
if ($connection->query($sql) == TRUE) {
$last_inserted_id = $connection->insert_id;
//Insert into Second Table
$sql_two = "INSERT INTO user_registration (user_id, phone_no, address)
VALUES ($last_inserted_id, 1234567, 'Address')";
$connection->query($sql_two);
}
You must create a Foreign key reference in the second table. In this user_id is the Foreign Key.
I have two tables in my database namely reservations and guests. The rows are as follow:
Reservation:
Reservation id
Property Id
Checkin date
Checkout date
Price
Guest
Guest id
Reservation id
Guest name
Guest address
Using a form that contains the reservation details and the guest details at the same time.
How can I run the insert query so that the auto generated reservation id(auto-increment in database) can also be inserted into the guest table at the same time?
This is what I have so far. I changed my code using last_insert_id()
INSERT INTO reservations
SET Checkin date= '24/05/2018', checkout date = '29/05/2018';
INSERT INTO guests
SET reservation id = LAST_INSERT_ID(),
guest name = guest name
First insert to reservation table
<?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);
}
$sqlR = "INSERT INTO Reservation(firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
$rStatus = $conn->query($sqlR);
$res_id = $conn->insert_id;
$sql = "INSERT INTO MyGuests (firstname, lastname, email,res_id)
VALUES ('John', 'Doe', 'john#example.com',$res_id)";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Firstly you can insert the data into the Reservation table, based on the last inserted id, you can use the value for the column Reservation id for the table Guest. Also, please maintain foreign key constraints, so as on update and delete operations of Reservation, simultaneous operations are performed on the Guest table.
To get the last inserted id,
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ...";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id; //gives the last inserted id
}
Run the insert query first with the insert_id function and then use that insert_id to run the second insert query
I am trying to build a page that displays the data that has been searched for within a html table. I have the search field and button set up on the page and a small table showing all data currently. I need it to actively change the data displayed in the table depending on the words in the search field.
EDIT:
How can I dynamically change the data within the table depending on the text in the search field?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT clientname, clientsurname, address1, postcode, dob FROM clients";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Name</th><th>Surname</th><th>Address</th><th>Postcode</th><th>Date of Birth</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["clientname"]."</td><td>".$row["clientsurname"]."</td><td>".$row["address1"]."</td><td>".$row["postcode"]."</td><td>".$row["dob"]."</td></tr>";
}
echo "</table>";
} else {
echo "There are 0 clients in the system matching your search criteria";
}
$conn->close();
?>
What #eselskas said + If you want to search by the given value from your search bar, you need to change the query.
$sql = "SELECT clientname, clientsurname, address1, postcode, dob FROM `clients` WHERE `your_field` LIKE '%$_POST[search_var]%'";
or better:
if($_POST['change_var'] != ""){
$sql = "SELECT clientname, clientsurname, address1, postcode, dob FROM `clients` WHERE `your_field` LIKE '%$_POST[search_var]%'";
}else{
$sql = "SELECT clientname, clientsurname, address1, postcode, dob FROM `clients`";
}
The best solution would be to create an ajax request to the back-end, searching the database and returning a json response which would be appended into your html.
This however would require your code to be re-factored and split the front-end and back-end logic.
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();
?>