(Php)Retrieve primary key of previous table and insert into current table - php

Im new to php scripting.. I want to know if there is any mistake in my php script that i want to fetch income_id (primary key in income table) from income table and insert it into expenses table(as foreign key)...I able to add all data into expenses table except the income_id..
<?php
//Importing our db connection script
require_once('dbConnect.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$id = $_POST['id'];
$income_id = $_POST['income_id'];
$category = $_POST['category'];
$amount = $_POST['amount'];
$date = date('Y-m-d');
$sql = "SELECT income_id from `income` where id='".$id."'";
$result = mysqli_query($con, $sql);
$rows = mysqli_fetch_array($result);
//Creating an sql query
$sql = "INSERT INTO expenses (income_id,category,amount,date) VALUES ('$rows[income_id]','$category','$amount','$date')";
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Added Successfully';
}else{
echo 'Could Not Add';
}
//Closing the database
mysqli_close($con);
}

I would suggest joining both queries:
INSERT INTO expenses (income_id, category, amount, date)
VALUES ((SELECT income_id FROM `income` WHERE id='$id'), '$category', '$amount', '$date')

Related

Insert INTO with 3 tables

$sql3 = "INSERT INTO users_addresses (ua_user_id,ua_address_id) VALUES ('','')";
I am new in php and my hint is to link 2 tables id's in in another one called users_addresses.When a user is registered in my database i want the user_id and address_id to clone in users_addresses(ua_user_id,ua_address_id)
My tables
$sql = "INSERT INTO users (user_fname,user_mname,user_lname,user_login,user_email,user_phone)
VALUES ('{$_SESSION['userinfo']['fname']}', '{$_SESSION['userinfo']['mname']}', '{$_SESSION['userinfo']['lname']}', '{$_SESSION['userinfo']['login']}', '{$_SESSION['userinfo']['email']}', '{$_SESSION['userinfo']['phone']}')";
$sql1 = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ('{$_SESSION['addressinfo']['adr1']}', '{$_SESSION['addressinfo']['adr2']}', '{$_SESSION['addressinfo']['zip']}', '{$_SESSION['addressinfo']['city']}', '{$_SESSION['addressinfo']['provinciq']}', '{$_SESSION['addressinfo']['durjava']}')";
$sql2 = "INSERT INTO notes (note_text)
VALUES ('{$_SESSION['noteinfo']['note']}')";
These are my others SQL codes for adding session's data in DB.
Just need get user_id from first sql. If you are using mysqli function, do this
// run your first sql: insert user
mysqli_query($con, $sql);
$user_id = mysqli_insert_id($con); // or mysqli::$insert_id
Next, you have $user_id variable with user id.
$sql1 = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ($'{$_SESSION['addressinfo']['adr1']}', '{$_SESSION['addressinfo']['adr2']}', '{$_SESSION['addressinfo']['zip']}', '{$_SESSION['addressinfo']['city']}', '{$_SESSION['addressinfo']['provinciq']}', '{$_SESSION['addressinfo']['durjava']}')";
mysqli_query($con, $sql);
$address_id = mysqli_insert_id($con); // or mysqli::$insert_id
$sql3 = "INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES ($user_id, $address_id)";
mysqli_query($con, $sql);
Use mysqli_insert_id() to get the unique ID of the insert table, this example uses Procedural style:
<?php
include 'connection.php';
......
$InsertSQL = "INSERT INTO users (user_fname,user_mname,user_lname,user_login,user_email,user_phone)
VALUES ('{$_SESSION['userinfo']['fname']}',
'{$_SESSION['userinfo']['mname']}',
'{$_SESSION['userinfo']['lname']}',
'{$_SESSION['userinfo']['login']}',
'{$_SESSION['userinfo']['email']}',
'{$_SESSION['userinfo']['phone']}')";
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
$UserID = mysqli_insert_id($conn); // <-- get the UserID
$InsertSQL = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ('{$_SESSION['addressinfo']['adr1']}',
'{$_SESSION['addressinfo']['adr2']}',
'{$_SESSION['addressinfo']['zip']}',
'{$_SESSION['addressinfo']['city']}',
'{$_SESSION['addressinfo']['provinciq']}',
'{$_SESSION['addressinfo']['durjava']}')";
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
$AddressID = mysqli_insert_id($conn); // <-- get the AddressID
$InsertSQL = "INSERT INTO user_addresses (ua_user_id,ua_address_id)
VALUES ($UserID,$AddressID)"; // <-- INSERT INTO user_address
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
?>
You should also look into SQL Injection vulnerability, check out prepared statements.
Hope that helps.

How do I get the "user_id" for a customer places an order?

I have been struggling with this for a while now. Is there any way for me to get the "user_id" form my "users" table into my "orders" table when a customer places an order?
When using the second SQL statement, after the "INSERT INTO" statement, the system still says that the order has been successful. However, when I check my database the order has not even been inserted.
Without the use of the second SQL statement the order will be inserted correctly, with every field except the "user_id" being placed in the table.
I have also tried "INSERT INTO table2 (column1, column2, column3, ...) SELECT column1, column2, column3, ... FROM table1 WHERE condition;" Statement and that also does not work.
Would it work if only one SQL command was written? If so I am not sure how to do this.
Any help would be greatly appreciated.
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$type = mysqli_real_escape_string($conn, $_POST['type']);
$square_ft = mysqli_real_escape_string($conn, $_POST['square_ft']);
$materials = mysqli_real_escape_string($conn, $_POST['materials']);
$time= mysqli_real_escape_string($conn, $_POST['time']);
$date= mysqli_real_escape_string($conn, $_POST['date']);
$price= mysqli_real_escape_string($conn, $_POST['price']);
if (empty($price) || empty($time) || empty($date) || empty($type) || empty($square_ft) || empty($materials)) {
header("Location: ../placeorder.php?order=empty");
exit();
} else {
//Insert orders into database
$sql = "INSERT INTO orders (price, time, date, type, square_ft, materials,) VALUES('$price', '$time', '$date', '$type', '$square_ft','$materials');";
$sql = "INSERT INTO orders (user_id) FROM users;";
mysqli_query($conn, $sql);
header("Location: ../orderform.php?order=success");
exit();
}
}
?>
<?php
include_once 'footer.php';
?>
To get key from Users, you need to perform SELECT over users field, then to insert users key into orders. It would be something like this:
$sql1 = "SELECT user_id FROM users_table WHERE username='someusername'";
$userid = mysqli_fetch_assoc(mysqli_query($conn, $sql1));
$sql2 = "INSERT INTO orders (price, time, date, type, square_ft, materials, user_id) VALUES('$price', '$time', '$date', '$type', '$square_ft','$materials', '$userid');";
mysqli_query($conn, $sql1);

I want to insert two values into a same table of sql, the first value is from another table and other value is argv[2]?

I want to insert two values into the same table of SQL. The first value comes from another table and the other value is argv[2].
This is the code that I am using but it does not work.
for($i=0;$i<=feof($getdata);$i++){
if (filter_var($data[$i][1], FILTER_VALIDATE_EMAIL)){
//echo $data[$i][1];
$email=$data[$i][1];
$type=$argv[2];
$name=$data[$i][0];
$sql ="INSERT INTO promo_user (name,email) VALUES ('$name','$email')";
mysqli_query($conn,$sql);
$uid = mysqli_insert_id($conn);
$sql ="INSERT INTO promo_type set uid =$uid";
mysqli_query($conn,$sql);
$sql = "INSERT INTO promo_type (type) values ('$type')";
mysqli_query($conn,$sql);
}
}
mysqli_close($conn);

add mysql row if userID do not exist in table

i'm sending a post request to this code:
$name = (string)$_POST['name'];
$id = (int)$_POST['id'];
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
Which works fine and it adds a row to the table. How do i check wether the userID all ready exist in one of the following rows?
Do it like this
$query = "SELECT COUNT(*) FROM Users WHERE userID = '$id'";
$result = mysqli_query($link,$query);
if ( mysqli_fetch_assoc($result) ) {
$message = "Already exists";
} else {
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
}
Try this
$name = (string)$_POST['name'];
$id = (int)$_POST['id'];
$res = mysqli_query($link, "SELECT * FROM Users WHERE userID = '$id' LIMIT 1 ");
if($row = mysqli_fetch_assoc($res))
{
echo "this user id is already exists";
}
else
{
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
echo "record inserted successfully ";
}
REMEMBER : always use LIMIT 1 when you trying to get exactly one result.
IF you have properly set 'id' as primary key or unique key in your table, you can use the modifier IGNORE in your query you don't get an error when you try to isert a duplicate.
Doing this will result in the row only being inserted if the value of the primary key wasn't already in the table.
$query = "INSERT IGNORE INTO Users (name, userID) VALUES ('$name', '$id')";
IF you haven't set a primary key in your table you will have to do a SELECT query to find out if a row with that id is already in your table.
Make the UserID an Unique Key.
If it already exists, your code will throw an error and the row will not be insterted.
alter table Users
add unique index Unique_user (userID (8000))
Before inserting the values to the table check whether the following user id exists in the table or not
You can do it in this way
$name = $_POST['name'];
$id = $_POST['id'];
$sql = "SELECT * FROM Users WHERE userID = '$id'";
$res= mysqli_query($sql);
$num = mysqli_num_rows($res);
if($num == 0)
{
$query2 = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result2 = mysqli_query($query2);
echo "record inserted successfully ";
}
else
{
echo "Record Failed !!";
}

How to insert same data into two tables in mysql

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

Categories