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.
Related
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
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??
My case now is every username can select the items in spinner one time only. Mean if the spinner has 5 item, the user can choose all of them but all of them just can one time only. Below are my select data php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['username'];
$name = $_POST['name'];
//Creating an sql query
$sql = "INSERT INTO Selection (username, name) VALUES
('$username','$name')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Select Successfully';
}else{
echo 'Sorry, You Already Select it Before';
}
//Closing the database
mysqli_close($con);
}
The name in this php means the item in spinner. I am no idea how to set every username can select all the item in spinner one time only. I am using localhost phpmyadmin.
You can specify unique constraint for username and name columns.
Alter the Selection table using this code:
ALTER TABLE `Selection` ADD UNIQUE `unique_index`(`username`, `name`);
Now if you try to insert any username and name pair that is already inserted, will fail.
Why are you not testing if the entry is already on database before you do insert? May be this (Untested) code might help:
if($_SERVER['REQUEST_METHOD']=='POST')
{
//Getting values
$username = $_POST['username'];
$name = $_POST['name'];
//Importing our db connection script
require_once('dbConnect.php');
//Creating an sql query
$check_sql = "SELECT * FROM Selection WHERE username='$username' AND name='$name' LIMIT 1";
$check_res = $mysqli->query($con,$check_sql);
if($check_res && mysqli_num_rows($check_res) >0)
{
echo 'Sorry, You Already Select it Before';
}
else
{
$sql = "INSERT INTO Selection (username, name) VALUES ('$username','$name')";
if(mysqli_query($con,$sql))
{
echo 'Select Successfully';
}
else
{
echo "Select failed for some other reason";
}
}
//Closing the database
mysqli_close($con);
}
I think for checking the user to spin it only once only you need to add a flag in your database structure such as
u_id | flag |
--------------
1 | 1
--------------
So that when retrieving or fetching or you can say while checking you just have to make sure that this particular u_id has already spin it once so further it can't be allowed.
So before inserting check the username or user_id of particular.
$sql = "SELECT u_id from user_spins table where u_id = 1 AND flag = 1";
//if yes then don't allow to proceed
//if no then insert into User_spins table
$sql = "INSERT INTO User_spins (u_id, name,flag) VALUES
('$username','$name',1)";
//Importing our db connection script
require_once('dbConnect.php');
I am creating a sign up form using HTML5/CSS3/PHP/MySql that will have following columns:
Firstname, Lastname, Email, Password ( to be filled on Web form-1)
Username, country, Age, SecurityQues, SecurityAns, Mobile (to be filled on web-form 2).
there is only one table named user_record for all the fields and it has a user_id that is auto generated and auto increment when the web form 1 is executed, and it is also the primary key for the table.
I am using insert query for web form 1 and update query for web form 2. but the second form's data cannot be submitted until it has UserId generated in the web form 1.
I tried to retrieve it using lastInsertId(); but it is not working as it returns the id only when the insertion is done on the same page so it works on form 1 but not on form 2.
there is only one table being used on two different web pages. on one insertion is being done and user_id is being generated.
On the another update query will be performed to update the remaining fields of the row created in the first form. for that form 2 needs primary key which is not available.
Can any one help me and tell me how to retrieve last UserId on the form 2 so that the data can be filled on the same row that user just created on form 1.
following is the code snippet for both form 1 and form 2.
Form 1 PHP Snippet:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "myDB";
$conn = new PDO("mysql:host=$servername;dbname=$db", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['sign_up-btn'])){
session_start();
$first_name = ($_POST['first_name']);
$last_name = ($_POST['last_name']);
$email_id = ($_POST['email_id']);
$password = ($_POST['password']);
$password2 = ($_POST['password2']);
if($password == $password2){
$password = md5($password);
$sql = "INSERT INTO user_record(first_name, last_name, email, password) VALUES('$first_name', '$last_name', '$email_id', '$password')";
$conn->exec($sql);
$_SESSION['message'] = "You are almost done";
$_SESSION['first_name'] = $first_name;
header("location: pro.php");
}else{
$_SESSION['message'] = "Password do not match";
}
}
$conn = null;
?>
PHP Script of form 2 is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "myDB";
$conn = new PDO("mysql:host=$servername;dbname=$db", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['sub_btn'])){
session_start();
$user_name = ($_POST['user_name']);
$sel_cont = ($_POST['sel_cont']);
$age = ($_POST['age']);
$sec_que = ($_POST['sec_que']);
$sec_ans = ($_POST['sec_ans']);
$mob_num = ($_POST['mob_num']);
$con_code = ($_POST['con_code']);
$id = $conn->lastInsertId();
$sql = "UPDATE user_record SET user_name = '$user_name', country = '$sel_cont',
age = '$age', security_ques = '$sec_que', security_ans = '$sec_ans',
mobile_num = '$mob_num', c_code = '$con_code' WHERE user_id = '$id' ";
$conn->exec($sql);
$_SESSION['message'] = "Welcome";
$_SESSION['user_name'] = $user_name;
header("location: home.php");
}
$conn = null;
?>
Plz tell me how to update the same row with the data of second form.
Obviously, the second form can't be submited if does not exists first record inserted.
I supose that second forms is already on the client browser.
You must to use session capabilities, on first form you must to set the lastInsertId() on a session variable.
Later, on form2 submit, the php can retrive the session variable before the UPDATE. If the session variable containing the lastInsertID is not set, means that the client has not submited first form.
As the #XPerez mentioned I needed to use session variables. so on the first web form I added following line before header statement:
$_SESSION['user_id'] = $conn->lastInsertId();
and on the second form I added following statement before Update statement
$id = $_SESSION['user_id'];
and it did the trick. Session variables can used on different web pages through out the single session. On the first page when session started I stored the id of the insertion statement into a session variable and then use it on the second page.
Hello guys I have a problem with a script
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'site';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die(mysql_error());
}
mysql_select_db($dbname, $con);
$sql = "REPLACE INTO stiri (id, titlu, continut, link, categorie, data) VALUES ('','$titlu','$text','$link','Liga 1','$data')";
mysql_query($sql);
mysql_close($con);
This part is in a php foreach part and every time I run the script I get duplicate entry, how can I prevent this?
I could use UNIQUE Constraint but I want the link to be unique which is longer than 125 chars..
I'm guessing id is a primary key field in your table? You're trying to insert an empty string ('') into it. If that's an INT field, mysql will convert '' into 0. After the first such insert, you'll run into the duplicate key problem.
Change id to be an auto_increment field, and insert a null value, e.g.
REPLACE INTO stiri (id, ...) VALUES (null, ....)
so mysql can generate an ID for you automatically.