MySQL INSERT with a field coming from another table fails - php

I Need to insert data in a table but 1 of the fields will come from another table but not working...
Code as below:
//Save payment to table paylog
$sql = "INSERT INTO `paylog`(`payment_id`, `date_approved`, `newcredit`, `before`) VALUES (?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss',$payment->id,$dateApproved,
$payment->transaction_amount,(SELECT credit from tokens WHERE token=$payment->external_reference LIMIT 1));
$stmt->execute();
$stmt->close();
Assistance welcome
Paulo

Just move that SELECT subquery up inside of $sql, keep $payment->external_reference as a binded parameter.
See https://stackoverflow.com/a/42132551/7977859

Related

how to use 2 inserts in the same record PHP SQL

I am using the below code to grab a users ID from another table and creating a new record in this table. in the same row there is a field called action and I would like to insert either 'Log-In' or 'Log-Out' in this field for the same record.
my question is im not sure how to incorporate it with the code below without the database creating a new blank line
try{
// check for user ID in sessions table and apply to new session_log record
$sql = "INSERT INTO session_logs (USER_ID, first, last, email) SELECT USER_ID, first, last, email FROM sessions WHERE email=:email";
$stmt = $pdo->prepare($sql);
// Bind parameters to statement
$stmt->bindParam(':email', $_REQUEST['email']);
// Execute the prepared statement
$stmt->execute();
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
Unfortunately, Table and Column names CANNOT be replaced by parameters in PDO so you cant just bind the SELECT column as a value or similar, however, you can manipulate the string yourself to add in the required value like so:
$action = 'Log-In'; // if you get this value from user input in any way, be sure to sanitize it with something like `mysqli_real_escape_string`
$sql = "INSERT INTO session_logs (USER_ID, first, last, email, action) SELECT USER_ID, first, last, email, '$action' FROM sessions WHERE email=:email";

get the id of the last inserted row in mysql

I have looked everywhere and keep getting different answers and incorrect code. All I want to do is after I have added a field to my database in MySQL is to get the user_id of the field that has just been created. I just cannot seem to do it?
I am using this to input the field and thanks for any help. It has a auto_increment value of user_id which is what I need to get.
mysqli_query($con,"INSERT INTO users_accounts (business, email_uniq)
VALUES ('$business', '$email_uniq')");
use this after insert query
$last_row = mysqli_insert_id($con);
You can return the primary key of the last row inserted with
$last_id = mysqli_insert_id($con);
You can find more information here: http://php.net/manual/en/mysqli.insert-id.php
After executing the query, you can use mysqli::$insert_id value or mysqli_insert_id function to retrieve the last generated id, like this:
mysqli_query($con,"INSERT INTO users_accounts (business, email_uniq) VALUES ('$business', '$email_uniq')");
$insert_id = mysqli_insert_id($con);
or using the object functions:
$con->query("INSERT INTO users_accounts (business, email_uniq) VALUES ('$business', '$email_uniq')");
$insert_id = $con->insert_id;
edit: Not related, but definitly important!
If the values for either of these parameters $business or $email_uniq are user supplied, it is highly recommended to make sure they are filtered properly. The easiest way is by using a prepared statement for security (http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Here is your code using prepared statements:
$stmt = $con->prepare("INSERT INTO users_accounts (business, email_uniq) VALUES (?,?)");
$stmt->bind_param("ss", $business, $email_uniq);
$stmt->execute();
$insert_id = $con->insert_id;

PDO lastInsertId in the same query

Hello so I have a table named tblcontactlist and have 5 columns (contactID, contactName, contactEmail, contactNumber, hashed_id) and this is my working query
$query = "INSERT INTO tblcontactlist (contactName, contactEmail, contactNumber) VALUES (:cname, :cea, :cnum)";
$stmt = $dbc->prepare($query);
$stmt->bindParam(':cname', $contactName);
$stmt->bindParam(':cea', $emailAdd);
$stmt->bindParam(':cnum', $contactNumber);
$stmt->execute();
$last_id = $dbc->lastInsertId('contactID');
$hashed_id = sha1($last_id);
$query2 = "UPDATE tblcontactlist SET hashed_id=:hid WHERE contactID=:cid";
$stmt2 = $dbc->prepare($query2);
$stmt2->bindParam(':hid', $hashed_id);
$stmt2->bindParam(':cid', $last_id);
$stmt2->execute();
What this basically does is insert a new record then updates the latest inserted record with a hashed id on the hashed_id column. Is there a proper way of doing this? I mean shorter code or better code. Thanks!
lastInsertId presupposes that you have a previous INSERT beforehand, that you don't have. In this case, lastInsertId is the max contactID. So I would perform a query to get and hash the max contactID and then perform one insert query (and no update).
//fetch Max contactID
$res=$dbc->prepare("SELECT MAX(contactID) FROM tblcontactlist");
$res->execute();
$fetchMax=$res->fetch(PDO::FETCH_NUM);
$last_id=$fetchMax[0];
//hash the max contactID
$hashed_id = sha1($last_id);
//for reusability you can create a function with the above code.
And now perform the insert query:
$query = "INSERT INTO tblcontactlist (contactName, contactEmail, contactNumber, hashed_id) VALUES (:cname, :cea, :cnum, :hid)";
$stmt = $dbc->prepare($query);
$stmt->bindParam(':cname', $contactName);
$stmt->bindParam(':cea', $emailAdd);
$stmt->bindParam(':cnum', $contactNumber);
$stmt->bindParam(':hid', $hashed_id);
$stmt->execute();
Is that better for you?

Getting the id of the last inserted record from an MSSQL table using PDO and PHP

I am trying to get the id of the last record inserted in an mssql database using pdo via php. I HAVE read many posts, but still can't get this simple example to work, so I am turning to you. Many of the previous answers only give the SQL code, but don't explain how to incorporate that into the PHP. I honestly don't think this is a duplicate. The basic insert code is:
$CustID = "a123";
$Name="James"
$stmt = "
INSERT INTO OrderHeader (
CustID,
Name
) VALUES (
:CustID,
:Name
)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
I have to use PDO querying an MSSQL database. Unfortunately, the driver does not support the lastinsertid() function with this database. I've read some solutions, but need more help in getting them to work.
One post here suggests using SELECT SCOPE_IDENTITY(), but does not give an example of how incorporate this into the basic insert code above. Another user suggested:
$temp = $stmt->fetch(PDO::FETCH_ASSOC);
But, that didn't yield any result.
If your id column is named id you can use OUTPUT for returning the last inserted id value and do something like this:
$CustID = "a123";
$Name="James"
$stmt = "INSERT INTO OrderHeader (CustID, Name)
OUTPUT INSERTED.id
VALUES (:CustID, :Name)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result["id"]; //This is the last inserted id returned by the insert query
Read more at:
https://msdn.microsoft.com/en-us/library/ms177564.aspx
http://php.net/manual/es/pdo.lastinsertid.php

Grab the last insert id from one table to put into another table

probably a simple one for you developers out there
I have this code to insert an order_id and order_name into the 'orders' table:
<?php
// start the session handler
require_once('dbfunction.php');
//connect to database
$conn = DB();
require_once('header.php');
//should we process the order?
if (isset($_POST['process'])) {
$order_name = $_POST['order_name'];
//create initial order
$stmt = $conn2->prepare("INSERT INTO orders (order_name) VALUES (?)");
//bind the parameters
$stmt->bind_param('s', $order_name);
// Execute query
$stmt->execute();
I now want to insert the order items into the order_items table and I cant seem to keep that same ID that was created when inserting into the 'orders' table and add it to the 'order_items' table along with the order_items. Here is my code:
//this gets the most recent auto incremented ID from the database - this is the order_id we have just created
$order_id = mysql_insert_id();
//loop over all of our order items and add to the database
foreach ($_SESSION['order'] as $item) {
$prod_id = $item['prod_id'];
$quantity = $item['quantity'];
$prod_type = $item['prod_type'];
$stmt = $conn2->prepare("INSERT INTO order_items (order_id, prod_id, quantity, prod_type) VALUES (?, ?, ?, ?)");
//bind the parameters
$stmt->bind_param('iiis', $order_id, $prod_id, $quantity, $prod_type);
// Execute query
$stmt->execute();
}
echo "<p class='black'>Order Processed</p>";
I would guess it's because whatever database library you are using is doing something to invalidate the mysql_insert_id (assuming it's even using the mysql functions). I'd suggest you look into the library to find out what method they suggest you use instead.
SQL Server has ##IDENTITY
It looks like mySQL has LAST_INSERT_ID();
My guess is you are using mySQL. If not, then please let me know the version so I can update

Categories