Insert into Multiple Tables using PHP with LAST_INSERT_ID() - php

Below is the code that I've tried but I can't seem to make the right tweaks to get the script to run properly.
$sql = 'INSERT INTO clients (first_name, last_name, email) VALUES('.$_POST['first_name'].', '.$_POST['last_name'].', '.$_POST['email'].')
INSERT INTO client_data (client_id, phone, zip, note) VALUES(LAST_INSERT_ID(), '.$_POST['phone'].', '.$_POST['zip'].', '.$_POST['message'].')';
mysql_query($sql) or die (mysql_error());
Any help is much appreciated.

You cannot execute two sql statements with mysql_query();
Use something like this:
$sql = 'INSERT INTO clients (first_name, last_name, email) VALUES('.$_POST['first_name'].', '.$_POST['last_name'].', '.$_POST['email'].')';
mysql_query($sql);
$clientId = mysql_insert_id();
$sql = 'INSERT INTO client_data (client_id, phone, zip, note) VALUES('.$clientId.', '.$_POST['phone'].', '.$_POST['zip'].', '.$_POST['message'].')';
mysql_query($sql) or die (mysql_error());
But please read up on SQL injections and how to prevent them.

Just make 2 queries:
$sql_insert_clients = "INSERT INTO clients (first_name, last_name, email) VALUES(".$_POST['first_name'].", ".$_POST['last_name'].", ".$_POST['email'].")";
mysql_query($sql_insert_clients) or die (mysql_error());
$sql_insert_client_data = "INSERT INTO client_data (client_id, phone, zip, note) VALUES(".mysql_insert_id().", ".$_POST['phone'].", ".$_POST['zip'].", ".$_POST['message'].")";
mysql_query($sql_insert_client_data) or die (mysql_error());

You should break it up into two separate mysql_query calls and use the mysql_insert_id function:
$firstName = mysql_real_escape_string($_POST["first_name"]);
$lastName = mysql_real_escape_string($_POST["last_name"]);
$email = mysql_real_escape_string($_POST["email"]);
$phone = mysql_real_escape_string($_POST["phone"]);
$zip = mysql_real_escape_string($_POST["zip"]);
$message = mysql_real_escape_string($_POST["message"]);
mysql_query("INSERT INTO clients (first_name, last_name, email) VALUES ('{$firstName}', '{$lastName}', '{$email}')") or die(mysql_error());
mysql_query("INSERT INTO client_data (client_id, phone, zip, note) VALUES ('". mysql_insert_id() ."', '{$phone}', '{$zip}', '{$message}')") or die(mysql_error());

Your just missing the semi-colon to split the Insert's
$sql = 'INSERT INTO clients (first_name, last_name, email)
VALUES('.$_POST['first_name'].', '.$_POST['last_name'].', '.$_POST['email'].')'."; ".' INSERT INTO client_data (client_id, phone, zip, note) VALUES(LAST_INSERT_ID(), '.$_POST['phone'].', '.$_POST['zip'].', '.$_POST['message'].')';
mysqli_multi_query($sql) or die (mysql_error());
the SQL query it should be running (with dummy content) is
INSERT INTO clients (first_name, last_name, email) VALUES('test', 'surname', email); INSERT INTO client_data (client_id, phone, zip, note) VALUES(LAST_INSERT_ID(), 'phone', 'zip', 'message');

Related

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.

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;

php issue with inserting into sql

I am having an issue inserting into mysql db using php.
specifically this code is giving me problems:
$sql = "INSERT INTO '$mysql_database'.'$UsersTable' ('firstName', 'lastName', 'password', 'email','userType')VALUES ('$firstName', '$lastName', '$password','$email','$userType')";
I can't seem to find the error with syntax here. All the information to me seems correct. where am I going wrong ?
try this
$sql = "INSERT INTO $mysql_database.$UsersTable (firstName, lastName, password, email,userType)VALUES ('$firstName', '$lastName', '$password','$email','$userType')";
remove Quote from table column
Try this query
$sql = "INSERT INTO $mysql_database.$UsersTable (firstName, lastName, password, email,userType)VALUES ('$firstName', '$lastName', '$password','$email','$userType')";
Hello you can't use single Quote from table column name so remove it
$sql = "INSERT INTO $mysql_database.$UsersTable (firstName, lastName, password, email,userType)VALUES ('$firstName', '$lastName', '$password','$email','$userType')";
otherwise use this way
$sql = "INSERT INTO $mysql_database.$UsersTable (`firstName`, `lastName`, `password`, `email`,`userType`)VALUES ('$firstName', '$lastName', '$password','$email','$userType')";

Multiple INSERT query's fetching last_insert_id of each each

mysql_query( "INSERT INTO users(email, password) VALUES ('$email','$password')" );
$user_id = mysql_insert_id( );
mysql_query( "INSERT INTO business_details ( business_id, name, address, city, state, country, pincode) VALUES ('$category','$business_name', '$business_address', '$city', '$state', '$country', '$pincode')" );
$idB = mysql_insert_id( );
mysql_query( "INSERT INTO user_profiles (name, phone, user_id, business_details_id) VALUES ('$person_name', '$phone_number', '$user_id', '$idB')" );
What will be the best way to insert all queries in one? Is it possible?
No, it isn't supported in MySQL - only Oracle can do it.
MySQL doesn't support multi-table insertion in a single INSERT statement

Duplicate MySQL Record with AI ID Field

I am trying to duplicate my MySQL record using the following function. It says I have an error in my SQL, which I cannot see. I added a few echo's at the bottom to help diagnose. Also, is there any easier way that naming each row individually? (row[$x])?
The function is basically reading whichever ID is posted to it, then writing it back into the DB as if the user was simply entering it themselves without pressing the duplicate button.
I have tried other code on stack and I thought I'd write one I actually understood so here it is!
EDIT: It seems that my second query is the problematic one as well.
Thank you!
function procDupRec(){
$id = mysql_real_escape_string($_GET['duplicate']);
$query = "SELECT * FROM contacts WHERE id=$id";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)){
$category = $row[1];
$dateEntered = $row[2];
$account = $row[3];
$firstName = $row[4];
$lastName = $row[5];
$company = $row[6];
$titlePos = $row[7];
$officeNum = $row[8];
$phoneExt = $row[9];
$homeNum = $row[10];
$mobileNum = $row[11];
$pagerNum = $row[12];
$faxNum = $row[13];
$address1 = $row[14];
$address2 = $row[15];
$city = $row[16];
$state = $row[17];
$zip = $row[18];
$email = $row[19];
$website = $row[20];
$notes = $row[21];
$editBit = $row[22];
$protection = $row[23];
$lastIP = $_SERVER['REMOTE_ADDR'];
}
$query2 = mysql_query("INSERT INTO contacts (category, dateEntered, account, firstName, lastName, company, titlePos, officeNum, phoneExt, homeNum, mobileNum, pagerNum, faxNum, address1, address2, city, state, zip, email, website, notes, editBit, protection, lastIP) VALUES ('$category', '$dateEntered', '$account', '$firstName', '$lastName', '$company', '$titlePos', '$officeNum', '$phoneExt', '$homeNum', '$mobileNum', '$pagerNum', '$faxNum', '$address1', '$address2', '$city', '$state', '$zip', '$email', '$website', '$notes', '$editBit', '$protection', '$lastIP')");
$result2 = mysql_query($query2);
echo $query2;
echo mysql_error();
}
Echoing a query will not work after you executed the query. That will only contain a result.
You should store the query before executing it, like this
$query2 ="INSERT INTO contacts (category, dateEntered, account, firstName, lastName, company, titlePos, officeNum, phoneExt, homeNum, mobileNum, pagerNum, faxNum, address1, address2, city, state, zip, email, website, notes, editBit, protection, lastIP) VALUES ('$category', '$dateEntered', '$account', '$firstName', '$lastName', '$company', '$titlePos', '$officeNum', '$phoneExt', '$homeNum', '$mobileNum', '$pagerNum', '$faxNum', '$address1', '$address2', '$city', '$state', '$zip', '$email', '$website', '$notes', '$editBit', '$protection', '$lastIP')";
mysql_query($query2);
With this you can examine the query with echo $query2
Another option to duplicate:
$query = "INSERT INTO contacts
(category, dateEntered, account, firstName, lastName, company, titlePos, officeNum, phoneExt, homeNum, mobileNum, pagerNum, faxNum, address1, address2, city, state, zip, email, website, notes, editBit, protection, lastIP)
(SELECT category, dateEntered, account, firstName, lastName, company, titlePos, officeNum, phoneExt, homeNum, mobileNum, pagerNum, faxNum, address1, address2, city, state, zip, email, website, notes, editBit, protection, lastIP FROM contacts WHERE id=$id)"
mysql_query($query);

Categories