How do I insert values while inserting values from other table - php

I just learned how to insert into a table from another. Now I do not know how to add a value that is not from the other table inside.
$input_comment = $_POST["comments"];
$sql3 = "INSERT INTO QuotationService (referid, username, date, shiptype, city, country, poe, volume, volume2, service, included, price, comment)
SELECT referid, username, date, shiptype, city, country, poe, volume, volume2, service, included, price
FROM ServiceHolds
WHERE username='$login_session' AND id=(SELECT MAX(id) FROM ServiceHolds)";
mysqli_query($conn, $sql3);
Where should I insert $input_comment

You can simply include the value as a constant in your SELECT. Note that you should use a prepared query to protect you from SQL injection:
$input_comment = $_POST["comments"];
$sql3 = "INSERT INTO QuotationService (referid, username, date, shiptype, city, country, poe, volume, volume2, service, included, price, comment)
SELECT referid, username, date, shiptype, city, country, poe, volume, volume2, service, included, price, ?
FROM ServiceHolds
WHERE username=?
AND id=(SELECT MAX(id) FROM ServiceHolds)
";
$stmt = $conn->prepare($sql3);
$stmt->bind_param('ss', $input_comment, $login_session);
$stmt->execute();

Try with adding comment field while doing a select query
$input_comment = $_POST["comments"];
$sql3 = "INSERT INTO QuotationService
(referid, username, date, shiptype, city, country, poe, volume, volume2, service, included, price, comment)
SELECT referid, username, date, shiptype, city, country, poe, volume, volume2, service, included, price, $input_comment as comment FROM ServiceHolds WHERE username='$login_session' AND id=(SELECT MAX(id) FROM ServiceHolds)";
mysqli_query($conn, $sql3);

Related

How can I add a field outside a SELECT INTO statement into new table?

Given the statement
$SQL = "INSERT INTO members (lname, fname, vid, hphone, cphone, email, village )
SELECT fname, lname, vid, hphone, cphone, email, village
FROM waitlist WHERE waitlist.vid = :vid";
Which works just fine; however, I also need to add a date into the expiration field of then members table. The expiration date is calculated before the above statement.
Thanks
Add it as a literal value in the SELECT list.
$SQL = "INSERT INTO members (lname, fname, vid, hphone, cphone, email, village, expiration_date )
SELECT fname, lname, vid, hphone, cphone, email, village, :expiration_date
FROM waitlist WHERE waitlist.vid = :vid";

PHP-MySQL INSERT Operation isn't Working

I'm developing a web platform. I'm using PHP and MySQL. I want to insert data to db. My code below.
<?php
session_start();
require_once('../../system/database.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ownerid = (int)$_SESSION['id'];
$record_time = date('H:i:s');
$record_date = date('Y-m-d');
// form_data
$name = strip_tags($_POST['name']);
$surname = strip_tags($_POST['surname']);
$phone1 = strip_tags($_POST['phone1']);
$birthday = strip_tags(trim($_POST['birthday']));
$gender = strip_tags(trim($_POST['gender']));
$company = strip_tags(trim($_POST['company']));
$address1 = strip_tags(trim($_POST['address1']));
$address2 = strip_tags(trim($_POST['address2']));
$phone2 = strip_tags(trim($_POST['phone2']));
$mail1 = strip_tags(trim($_POST['mail1']));
$mail2 = strip_tags(trim($_POST['mail2']));
$about = strip_tags(trim($_POST['about']));
$type_of = strip_tags(trim($_POST['type_of']));
$visible = strip_tags(trim($_POST['visible']));
$query = "INSERT INTO contact (ownerid, name, surname, birthday, gender, address1, address2, phone1, phone2, mail1, mail2, about, type_of, visible, time, date) VALUES('$ownerid', '$name', '$surname', '$birthday', '$gender', '$address1', '$address2', '$phone1', '$phone2', '$mail1', '$mail2', '$mail1', '$mail2', '$about', '$type_of', '$visible', '$record_time', '$record_date')";
$result = mysqli_query($connection, $query);
mysqli_error($connection);
} else {
header('Location: ../new_contact.php');
}
But my MySQL code does not work and write any error message!
wrong number of column in values clause (you repeat two time mail1 and mail2 ) try
$query = "INSERT INTO contact
(ownerid, name, surname, birthday, gender, address1, address2, phone1,
phone2, mail1, mail2, about, type_of, visible, time, date)
VALUES('$ownerid', '$name', '$surname', '$birthday', '$gender', '$address1', '$address2', '$phone1',
'$phone2', '$mail1', '$mail2', '$about', '$type_of', '$visible', '$record_time', '$record_date')";
Edit insert variables to be like this
$query = "INSERT INTO contact (ownerid, name, surname, birthday, gender, address1, address2, phone1, phone2, mail1, mail2, about, type_of, visible, time, date) VALUES(".$ownerid.", '".$name."', '".$surname."', '".$birthday."', '".$gender."', '".$address1."', '".$address2."', '".$phone1."', '".$phone2."', '".$mail1."', '".$mail2."', '".$about."', '".$type_of."', '".$visible."', '".$record_time."', '".$record_date."')";
You need to concate PHP variable properly and also need correct query format. Try this
$query = "INSERT INTO `contact` (ownerid, name, surname, birthday, gender, address1, address2, phone1, phone2, mail1, mail2, about, type_of, visible, time, date) VALUES('".$ownerid."','".$name."', '".$surname."', '".$birthday."','".$gender."', '".$address1."', '".$address2."', '".$phone1."','".$phone2."', '".$mail1."','".$mail2."', '".$about."', '".$type_of."', '".$visible."', '".$record_time."', '".$record_date."')";
If you have access to PHPMyAdmin, place the query in the SQL section and test it. Sometimes it can give you clues as where to look for issues.
As ScaisEdge says, you have 16 entries as keys, but 18 entries as values into your insert. It can be helpful to use coding software when using PHP that highlights like words (notepad++ is free and does this) Eclipse is another. Also, place your query into PHPMyAdmin "SQL" and test your query to see if it gives you any results or throws an error. It will point where in the string to start looking for your error.

Grab Record ID before during submit and save to another table

I have two tables:
Invoices & Invoices Parts
The reason i'm using two tables is because i dont want to save the invoice parts array into one record on the Invoices table and i dont want to save it into multiple records on the Invoices table.
When i submit the data into both tables, how can i link both tables together with the ID if i dont have the ID yet?
$result = mysqli_query($mysqli, "INSERT INTO invoices(labelwarning, status, todaysdate, todaystime, todaysdatetime, avatar, firstname, lastname, mwaid, nextgenid, manager, manageremail, dispatcher, dispatcheremail, techemail, tag, serialnumber, currentequipment, company, address, city, state, zip, contactperson, contactnumber , currentdate, timearrived, timecompleted, login_id) VALUES('$labelwarning', '$status', '$todaysdate', '$todaystime', '$todaysdatetime', '$avatar', '$firstname', '$lastname', '$mwaid', '$nextgenid', '$manager', '$manageremail', '$dispatcher', '$dispatcheremail', '$techemail', '$tag', '$serialnumber', '$currentequipment', '$company', '$address', '$city', '$state', '$zip', '$contactperson', '$contactnumber ', '$currentdate', '$timearrived', '$loginId')");
$result2 = mysqli_query($mysqli, "INSERT INTO invoiceparts(partnumber, partdescription, partprice, partquantity, partdb, login_id) VALUES '$partnumberstring', '$partdescriptionstring', '$partpricestring', '$partquantitystring', '$partdbstring', '$loginId')");
If you need to link the "login_id" and the login_id is generated with AUTO_INCREMENT then you can do it by
for Mysqli connection, mysqli_insert_id($mysqli);
for PDO connection, $mysqli->lastInsertId();
If the login_id is not an AUTO_INCREMENT field then you can do it by
SELECT login_id FROM invoices ORDER BY login_id DESC LIMIT 1;
It'll return the last inserted row from there we can fetch the login_id

update two tables with one query in mysql PHPMyadmin?

I have two tables, user_info and Friend_info. I want to do that when user update his record in user_info then it should also b update in friend_info where friend_id=user_id. I have tried this
UPDATE user_info (name, user_email, Gender, DOB, contact, address) WHERE user_id='$user_id',
friends_info(name, user_email, Gender, DOB, contact, address) WHERE friend_id='$user_id'
values('$name', '$user_email', '$Gender', '$DOB', '$contact', '$address');
But its not working . Any other solution please. It'll be appreciated.
I know this question is too late to ask now a days but its my problem because i am confused after doing so many search and no query is working in my case.
Your question is not clear. So are you testing something like you want query in phpmyadmin. if not then you might need to do in as a transaction. but if its a test or such try this:
UPDATE user_info (name, user_email, Gender, DOB, contact, address)
values('$name', '$user_email', '$Gender', '$DOB', '$contact', '$address')
WHERE user_id='$user_id';
UPDATE friends_info(name, user_email, Gender, DOB, contact, address)
values('$name', '$user_email', '$Gender', '$DOB', '$contact', '$address')
WHERE friend_id='$user_id';
So this is two query which then they are gonna execute together. But now in PHP
check these:
https://stackoverflow.com/a/802474/2226796
http://se2.php.net/manual/en/mysqli.multi-query.php
PHP + MySQL transactions examples
You can join the two tables in your statement using user_id as the joining key.
UPDATE user_info ui
INNER JOIN friends_info fi
ON ui.user_id = fi.user_id
SET ui.name = $name,
SET ui.user_email = $email,
SET ui.Gender = $Gender,
SET ui.DOB = $DOB,
SET ui.contact = $contact,
SET ui.address = $address,
-- set friends_info
SET fi.name = $name,
SET fi.user_email = $email,
SET fi.Gender = $Gender,
SET fi.DOB = $DOB,
SET fi.contact = $contact,
SET fi.address = $address
WHERE ui.user_id = $user_id;

mysql/php wrong logic with sql statement

I'm doing a project which has an ability of a user to approve or revoke application (like scholarship). But I can't seem to find out why it's not doing what I wanted to do. Please do check my code below:
$try = mysql_query("UPDATE new_applicants SET ApplicantStatusId='$status', DateManaged = NOW() WHERE ApplicantId='$id'") or die(mysql_error());
$try1 = mysql_fetch_assoc($try);
$status1 = $try1["ApplicantStatusId"];
if( $status1 == 2 ){
header('location: ../employeepage.php');
exit();
}
else{
$sql1 = "INSERT INTO scholar_profile (Firstname, Middlename, Lastname, Address, EmailAddress, BirthDate, BirthPlace, Religion, Age, Gender, ContactNo, Skill, Talent, LevelId, GWA, CategoryId, StatusId, SchoolId, BarangayId) SELECT Firstname, Middlename, Lastname, Address, EmailAddress, BirthDate, BirthPlace, Religion, Age, Gender, ContactNo, Skill, Talent, LevelId, GWA, CategoryId, StatusId, SchoolId, BarangayId
FROM new_applicants
WHERE new_applicants.ApplicantId = '$id'" or die(mysql_error());
}
When the applicantstatus becomes 2 = revoked, it should not copy the data to scholar_profile. But when I tried this, it still copies. What's wrong with this? thanks.
You're updating a table, so mysql_fetch_assoc won't return anything. I.e. $status1 will be null. If you want to select that data (ApplicantStatusID, ...) you'll have to use a SELECT statement instead.
You could just change the where clause of the SQL statement:
WHERE new_applicants.ApplicantId = '$id' and new_Applicants.ApplicantStatusId <> 2"
Then you don't have to worry about the logic in php.
you are fetching $try1 = mysql_fetch_assoc($try); on an UPDATE statment
which is not true.
fetch is only with SELECT statment

Categories