I am looking to post data into two database tables from a single form.
My databases are arranged as below:
Database 1 - 'watchlists':
watchlist_id
user_id
name
description
category
Database 2 - 'watchlist_films':
watchlist_id
film_id
My current MySQL query looks like this: $query = "INSERT INTO watchlist_films (watchlist_id, film_id) VALUES ('$watchlist_name['watchlist_id']', '$rt_id') WHERE watchlists ('watchlist_id') = " . $watchlist_name['watchlist_id'];, but I'm not sure if there's got to be some form of INNER JOIN somewhere?
Not sure what other information/code to provide, so I apologise if there's too little detail here, but, if there's anything else which is needed, just drop me a comment and I'll put up anything else which is required. I'm a relative PHP newbie, so apologies if this seems like a really simple question!
Update based on comments:
I have now got half of my query working, and have updated the logic to reflect it. The new query is basically doing the following:
INSERT new Watchlist to 'watchlists' table
SELECT watchlist_id of new Watchlist from 'watchlists' table WHERE watchlist_name = $watchlist_name (name of new Watchlist just created) and user_id = $user_id
INSERT watchlist_id (selected from previous query) AND film_id into 'watchlist_films' table
based on your comments, my queries now look like so:
if ($submit == 'Submit') {
require_once("db_connect.php");
$watchlist_name = clean_string($_POST['watchlist-name']);
$watchlist_description = clean_string($_POST['watchlist-description']);
$watchlist_category = $_POST['watchlist-category'];
$addWatchlist_bad_message = '';
$addWatchlist_good_message = '';
if ($db_server) {
if (!empty($watchlist_name)) {
$watchlist_name = clean_string($watchlist_name);
$watchlist_description = clean_string($watchlist_description);
mysql_select_db($db_database);
// Insert new Watchlist into Watchlist index
$insert_new_watchlist = "INSERT INTO watchlists (user_id, name, description, category) VALUES ('$user_id', '$watchlist_name', '$watchlist_description', '$watchlist_category')";
mysql_query($insert_new_watchlist) or die("Insert failed. " . mysql_error() . "<br />" . $insert_new_watchlist);
// Select new Watchlist ID
$select_new_watchlist = "SELECT watchlist_id FROM watchlists WHERE name = " . $watchlist_name;
$new_watchlist_id = mysql_query($select_new_watchlist) or die("Insert failed. " . mysql_error() . "<br />" . $select_new_watchlist);
// Add film to new Watchlist
$add_new_film = "INSERT INTO watchlist_films (watchlist_id, film_id) VALUES ('$new_watchlist_id', '$rt_id')";
mysql_query($add_new_film) or die("Insert failed. " . mysql_error() . "<br />" . $add_new_film);
$addWatchlist_good_message = '<div class="alert alert-success">Watchlist created successfully!</div>';?>
<script>
$('a.add-watchlist').trigger('click');
</script><?php
}
} else {
$addWatchlist_bad_message = '<div class="alert alert-error">Error: could not connect to the database.</div.';?>
<script>
$('a.add-watchlist').trigger('click');
</script><?php
}
require_once("db_close.php");
}
My query, however, seems to be failing at the SELECT statement, in between adding the new Watchlist to the Watchlist index and adding the film to the newly created Watchlist.
try this
$query1 = "INSERT INTO watchlist_films (watchlist_id, film_id)
VALUES ('" . $watchlist_name['watchlist_id'] . "', '$rt_id')";
$query2= "INSERT INTO watchlists ('watchlist_id')
VALUES (" . $watchlist_name['watchlist_id'] . ")";
$result = mysqli_multi_query($query1, $query2);
You will need to write an INSERT for each table.
$mysqli->query("INSERT INTO watchlist_films (watchlist_id, film_id)
VALUES ('" . $watchlist_name['watchlist_id'] . "', '$rt_id')");
$mysqli->query("INSERT INTO watchlists ('watchlist_id')
VALUES (" . $watchlist_name['watchlist_id'] . ")");
Related
i am using INSERT INTO SELECT Statement Syntax to insert values from another table into my main table
in my php project
$student_id=1; // dummy id set in a variable
include 'conndb.php';
$sql = "INSERT INTO `student_resulttbl` ( subject_name,)\n"
. "SELECT subject,\n"
. "FROM `subjecttbl`\n"
. "WHERE subject_class ='$class' AND subject_session = '2020/2021'";
It worked well but my issue is how to insert variable $student_id along with this on student_resulttbl. pls note $student_id is not coming from subjecttbl. Its set already. Thank you
If you want to INSERT $student_id to student_resulttbl table you should do query like this:
INSERT INTO `student_resulttbl` ( subject_name, student_id ) VALUES (
( SELECT subject FROM `subjecttbl`
WHERE subject_class ='$class'
AND subject_session = '2020/2021'
),
$student_id);
The summary code:
$student_id=1; // dummy id set in a variable
include 'conndb.php';
$sql = "INSERT INTO `student_resulttbl` ( subject_name, student_id ) VALUES ("
. "(SELECT subject FROM `subjecttbl` "
. "WHERE subject_class ='$class' "
. "AND subject_session = '2020/2021'"
. "), $student_id)";
You can INSERT multiple columns with INSERT INTO command. More information there:
w3schools.com/sql/sql_insert_into_select.asp
or
https://www.w3schools.com/sql/sql_insert.asp
or
https://www.dofactory.com/sql/insert
do you mean something like this?
$student_id=1; // dummy id set in a variable
include 'conndb.php';
$sql = "INSERT INTO `student_resulttbl` ( student_id, subject_name,)\n"
. "SELECT " . mysqli_real_escape_string($connection, $Student_id) . ", subject\n"
. "FROM `subjecttbl`\n"
. "WHERE subject_class ='$class' AND subject_session = '2020/2021'";
but have a look at prepared statements.
Is there a reason why you use newlines in SQL-Statements?
I need to send the values of username, password, mail, first name and last name into two different tables in my database. I have made that possible with this code, and i get the values correct. I have one problem tho. When the user-info goes into "users" table, it auto-generates one userId. That same userId i need to use and put into the other table "usermeta" to connect the information to the correct user. What happens now is that i get a userId in the users table, but in the usermeta table the userId is = 0 on all new users. Can anyone help me?
if (isset($_POST['username']) and isset ($_POST['password'])) {
$username = $mysqli->real_escape_string($_POST['username']);
$password = md5($mysqli->real_escape_string($_POST['password']));
$email = $mysqli->real_escape_string($_POST['mail']);
$fname = $mysqli->real_escape_string($_POST['fname']);
$lname = $mysqli->real_escape_string($_POST['lname']);
$query = <<<END
INSERT INTO users(username,pass,email,admin)
VALUES('{$username}','{$password}','{$email}','{$_POST['admin']}')
END;
$q = <<<END
INSERT INTO usermeta(first_name,last_name)
VALUES('{$fname}','{$lname}')
END;
if ($mysqli->query($query) !== TRUE) {
die("Could not query database" . $mysqli->errno . " : " . $mysqli->error);
}
if ( $mysqli->query($q) !== TRUE) {
die("Could not query database" . $mysqli->errno . " : " . $mysqli->error);
header('Location:home.php');
}
}
I got a form further down in the code that the info comes from that's going to the database, but it's the php-code that makes the error i assume to i exclude that code.
Thanks!
EDIT:
I've tried to implement your different comments. Thanks alot for the answers!
If i try to get the latest id inbetween the $query and $q, the output is 0. If i use the command:
if ($mysqli->query($query) === TRUE) {
$last_id = $mysqli->insert_id;
echo $last_id;
} else {
echo "Error: " . $query . "<br>" . $mysqli->error;
}
I get the correct id. But how can i use that variable to the new $q? It seems that the function breaks after the if is done.
Thanks! :)
You can use LAST_INSERT_ID() to retrieve the value of the auto-increment id that was created in your last insert. (Docs here)
So try:
$q = <<<END
INSERT INTO usermeta(first_name,last_name, userId)
VALUES('{$fname}','{$lname}', LAST_INSERT_ID();)
END;
Okey i managed to get it done. Thanks guys for the help!
The working code looks like this:
$query = <<<END
INSERT INTO users(username,pass,email,admin)
VALUES('{$username}','{$password}','{$email}','{$_POST['admin']}')
END;
if ($mysqli->query($query) === TRUE) {
$last_id = $mysqli->insert_id;
} else {
echo "Error: " . $query . "<br>" . $mysqli->error;
}
$q = <<<END
INSERT INTO usermeta(first_name,last_name, user_id)
VALUES('{$fname}','{$lname}','{$last_id}')
END;
if ($mysqli->query($q) !== TRUE) {
die("Could not query database" . $mysqli->errno . " : " . $mysqli->error);
}
I have an array of column names and column data types and now i wish to create a mysql table using these two arrays. Here's my code so far:
<?php
//print_r($_GET);
$col_names=[]; //this will store column names received from user
$col_types=[];//this will store column data types selected by user
if(isset($_GET['col_num'])){
$table_name=$_GET['table_name'];
$n=$_GET['col_num'];
for($i=0;$i<$n;$i=$i+1){
$index_names = "col".$i;
$index_type = "type".$i;
$col_names[$i] = $_GET[$index_names];
$col_types[$i] = $_GET[$index_type];
}
}
$con=mysqli_connect('localhost','root');
if(!$con){
die("Error conncecting: ". mysqli_error($con));
}
else{
mysqli_select_db($con,'temp');
$query = "CREATE TABLE $table_name (
for($i=0; $i<$n ;$i=$i+1)
{
echo "$col_names[$i]" . " " . "$col_types[$i]" . "(10)"
}
);";
/*
If suppose the col_names array contains : [Name,Age] and col_types contains: [Varchar,Int] then i need these two attributes to be incorporated in my Create query and so i have put them in a for loop.
*/
mysqli_query($query);
}
?>
Now i know that something's wrong with the "Create Query" that i have written but i am not able to figure out how to frame the query.Also how should i place the comma in case of multiple columns?
You are doing wrong, Use something like this,
$query = "CREATE TABLE $table_name ( ";
for($i=0; $i<$n ;$i=$i+1)
{
$query .= "$col_names[$i]" . " " . "$col_types[$i]" . "(10)" ;
}
$query .= " ); ";
echo $query;//output and check your query
mysqli_query($query);
This is required for a condition based, if Approved or Declined situation. A grid type of form with 25 rows of 30 fields gets submitted for a bulk insert. The last 25 inserted rows will be inserted into a temp_Orders table, then based on the if approve, the same data (last inserted rows in the temp_Orders) need be immediately copied to the real_Orders.
$query = "insert into temp_users (fname,sname,lname,email,dob,date_signup,date_expire) values ";
$count = count($_POST['fname']);
for($x=0;$x < $count; $x++)
{
$fname = $_POST['fname'][$x];
$sname = $_POST['sname'][$x];
$lname = $_POST['lname'][$x];
$dob = $_POST['dob'][$x];
$email = $_POST['email'][$x];
echo $fname . $sname . $lname . $dob . $email . '<br>';
$emty_tbl = "TRUNCATE temp_users";
$result_emty_tbl = mysql_query($emty_tbl);
if(!$result_emty_tbl){
die(mysql_error());
#mysql_free_result($result_emty_tbl);
}
$query .= "(
'$fname',
'$sname',
'$lname',
'$email',
'$dob',
'$today',
'$nextyear')";
/* If not last iteration, add a comma and a space */
if ($x < ($count - 1)) {
$query .= ", ";
}
$result = mysql_query($query);
}
if(!$result){
die(mysql_error());
#mysql_free_result($result);
} else {
$totalRID = mysql_affected_rows();
$lastRID = mysql_insert_id();
echo "Total records <b>" . $totalRID . " </b>entered into the database!" . "<br>";
echo "Current record number <b>" . $lastRID . " </b>entered into the database!" . "<br>";
echo "<form name='postbackid' method='post'>
<input type='hidden' name='lastrecord' value='$lastRID'>
<input type='button' value='Approved' name='approved' onclick='return Approved();'>
<input type='button' value='Declined' name='declined' onclick='return Declined();'>
</form>";
}
}
}
$postbackid=$_POST['lastrecord'];
echo $postbackid;
$sqlinsert = "INSERT INTO users (fname, sname, lname, dob, email, date_signup, date_expire)
SELECT fname, sname, lname, dob, email, date_signup, date_expire
FROM temp_users
WHERE id='$postbackid'";
$resultinsert = mysql_query($sqlinsert, $link);
as samimi_it has put it -> mysql_insert_id() will only trace the very last inserted id(uid)
therefore you will either need to:
Keep track of the rows within your code - easy way out, but with the highest problems
change the way you handle your data, add an additional column onto your temp order rows, like ref/order_no etc and keep that within your code, thereafter if approved simple copy run a query, insert into real_orders (select where order_no = {saved order_no})
or remove redundant data by, having one table "orders"
include new columns; approved int 0 = false, 1 = true and order_no (to reference the order)
insert the rows into the orders table with approved = 0.
then once approved simple do an update orders set approved = 1 where order_no = {order_no_from_code}.
hope this points you in the right direction.
My part_no column has the following format: 000-00000-00 for all records.
I need to extract the five middle characters from part_no and place it in the core column when I create the record.
I can't get my script to work.
I'm not getting any errors. Just not working.
$order = "INSERT INTO cartons_added (add_time, type, part_no, add_type, add_qty, add_ref, add_by, add_notes)
VALUES
('$date',
'$_POST[type]',
'$_POST[part_no]',
'$_POST[add_type]',
'$_POST[add_qty]',
'$_POST[add_ref]',
'$_POST[add_by]',
'$_POST[add_notes]')";
$result = mysql_query($order);
$query2 = "select part_no from cartons_current";
$sel = mysql_query($query2);
$res = mysql_result($sel);
while($row = mysql_fetch_row($res)) {
$core_digits = split('-',$row[0]);
$core =$core_digits[1];
$query3 = "insert into cartons_current(core) values($core)";
$sel2 = mysql_query($query3);
}
You can update your cartons_current table based on your cartons_added table with something like:
INSERT INTO cartons_current(core)
SELECT SUBSTR(part_no, 5, 5) FROM cartons_added
You will probably want to limit that with a WHERE clause or maybe deal with what happens when this value is already in cartons_current (use either INSERT IGNORE or ON DUPLICATE KEY UPDATE)
You are right, the script has no error.
I think the problem is on your SQL that made you can't insert a new row, specifically on the table structure. Maybe you defined a PRIMARY KEY without AUTO_INCREMENT, defined a INDEX or UNIQUE key that is not the core key or there have some other key that did not have default value. Remember that you can't insert a row without defining all required field.
You script is selecting all part_no and for every part_no you are inserting a new row in the same table, so maybe there is the problem.
I think what you want is update every result to add they core value, you can do that with UPDATE as this code:
function getValue($value) {
return "'" . trim(mysql_real_escape_string($value)) . "'";
}
mysql_query('INSERT INTO `cartons_added` (`add_time`, `type`, `part_no`, `add_type`, `add_qty`, `add_ref`, `add_by`, `add_notes`)
VALUES (' .
getValue($date) . ', ' .
getValue($_POST[type]) . ', ' .
getValue($_POST[part_no]) . ', ' .
getValue($_POST[add_type]) . ', ' .
getValue($_POST[add_qty]) . ', ' .
getValue($_POST[add_ref]) . ', ' .
getValue($_POST[add_by]) . ', ' .
getValue($_POST[add_notes]) .
')');
$partNoQuery = mysql_query('SELECT `part_no` FROM `cartons_current`');
while($partNoResult = mysql_fetch_assoc($partNoQuery)) {
list($prefix, $core, $suffix) = explode('-', $partNoResult['part_no']);
mysql_query('UPDATE cartons_current SET `core` = \'' . $core . '\' WHERE `part_no` = \'' . $partNoResult['part_no'] . '\'');
}
I added getValue function to escape posted data to prevent SQL injection.
Try removing this
$res = mysql_result($sel);
And change your while to reference the main query resource
while($row = mysql_fetch_row($sel)) {
I don't understand your logic with your tables though. You're inserting data into the cartons_added table but then you're selecting from cartons_current?
Also, split is deprecated as of PHP 5.3.0
You said five middle "characters", so I'd add quotes around your variable like so:
$query3 = "insert into cartons_current(core) values('$core')";
(Also, there's only about a gazillion answers on SO about SQL injection, and using pdo)
INSERT INTO cartons_current(core)
SELECT
substr(part_no,position('-' IN part_no)+1,position('-' IN substr(part_no,position('-' IN part_no)+1))-1)
FROM cartons_added;