So pretty much my issue is that I need to send multiple SQL entries using information based on another SQL entry.
I've simplified the code down that I was using so it's easily understandable.
$sql = mysql_query("SELECT product FROM `cart` WHERE username = '".$user."' LIMIT 10");
while ($rowcart = mysql_fetch_row($sql)) {
$sendorder = "INSERT INTO Orders (order_id, product) VALUES ('NULL', '".$rowcart[0]."')";
mysql_query($sendorder);
}
When I ran it, it had failed to work; so I tried to echo $sendorder to see exactly what was sending and it turns out it's copying the INSERT INTO part on each entry, instead of just copying the values.
Example output:
INSERT INTO Orders (order_id, product) VALUES ('NULL', 'Cakes')
INSERT INTO Orders (order_id, product) VALUES ('NULL', 'Sweets')
INSERT INTO Orders (order_id, product) VALUES ('NULL', 'Cakes')
INSERT INTO Orders (order_id, product) VALUES ('NULL', 'Brownies')
INSERT INTO Orders (order_id, product) VALUES ('NULL', 'Cakes')
You said, "I need to send multiple SQL entries using information based on another SQL entry." The following approach is more efficient than what you are attempting. Note that I use neither php nor mysql so I might have some syntax errors.
insert into orders
(product)
select product
from cart
where username = $user
As far as the limit 10 goes, if you want to restrict the person to 10 items, you should do something to ensure that only 10 rows go into the cart table.
Mysqli example
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_database');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("SELECT product FROM `cart` WHERE username = ? LIMIT 10");
$stmt->bind_param('s', $user);
$stmt->execute();
$stmt->bind_result($product);
while($stmt->fetch()) {
$tvalue[] = $product;
}
$stmt = $mysqli->prepare("INSERT INTO Orders (product) VALUES (?)");
$stmt->bind_param("s", $one);
foreach ($tvalue as $one) {
$stmt->execute();
}
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
?>
If i understand correctly, what you want to do is to send an unique query, you can do this by appending every value to be inserted at the end of a single query string:
<?php
// code
$sql=mysql_query("SELECT product FROM cart WHERE username='".$user."' LIMIT 10");
$result=mysql_query($sql);
if(mysql_num_rows($result)) {
$rowcart=mysql_fetch_row("$result");
$sendorder="INSERT INTO Orders (order_id, product) VALUES ('NULL', '".$rowcart[0]."')";
while($rowcart=mysql_fetch_row($result))
$sendorder.=", ('NULL', '".$rowcart[0]."')";
mysql_query($sendorder);
}
// code
?>
I assume, your order_id is a primary key, and auto_increment. You can leave that:
INSERT INTO Orders (product) VALUES ('Cakes')
or if you really want to insert it, then use
INSERT INTO Orders (order_id, product) VALUES (NULL, 'Cakes')
if you add quotes ' around it, then it will be parsed as a string. And since, that is not a string, but integer, it will cause syntax error.
You should be able to do this in a single SQL statement something like this..
INSERT INTO Orders(order_id,product)
SELECT null,product
FROM cart
WHERE username = $name
LIMIT 0,10
To refactor even further I would suggest you probably dont need to insert the null value just do:
INSERT INTO Orders(product)
SELECT product
FROM cart
WHERE username = $name
LIMIT 0,10
If your table is structured to allow NULL in the order_id col then this will be populated as null by default.
And as Dan just said doesnt seem to be much point putting a limit on either
Related
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
I have multiple table connected together by a few different foreign keys (see attahced image).
I am trying to insert into the projects table. I've been trying to accomplish this through the following code below, but it's not working. Right now I am getting an error saying that neither client_id_fk, project_manager_id_fk have a value. That makes sense since I didn't include them in the insert, but aren't auto incrementing and I also can't just add a random int to those fields since that throws an error as well. It technically works if I set the client_id_fk and project_manager_id_fk to NULL, but then there's no data in the other tables...Please help
$sql1 = "INSERT INTO PROJECTS (Project_Name, StartDate) VALUES( '".$_POST["Project_Name"]."','".$_POST["StartDate"]."')";
$sql2 = "INSERT INTO CLIENTS(Client_Name, Client_Email, Client_Phone) VALUES ('".$_POST["Client_Name"]."','".$_POST["Client_Email"]."','".$_POST["Client_Phone"]."')";
$sql3 = "INSERT INTO PROJECT_MANAGERS(ProjectManager_Name,Project_Manager_Email, Project_Manager_Phone) VALUES ('".$_POST["ProjectManager_Name"]."','email', 'phone')";
$sql4 = "INSERT INTO TYPE_OF_WORK(TypeOfWork) VALUES ('".$_POST["TypeOfWork"]."')";
Pattern:
-- Insert data into slave tables
INSERT INTO slave_1 (columns_1) VALUES ('values_1');
INSERT INTO slave_2 (columns_2) VALUES ('values_2');
-- Insert data into main table,
-- query FK values from slaves
-- using values inserted above
-- as filtering conditions
INSERT INTO main (columns_main, fk_column_1, fk_column_2)
SELECT 'values_main', slave_1.id, slave_2.id
FROM ( SELECT id FROM slave_1 WHERE columns_1 = 'values_1' ) slave_1
JOIN ( SELECT id FROM slave_2 WHERE columns_2 = 'values_2' ) slave_2
If it is possible that some subquery in last INSERT may return more than 1 row then wrap output column in this subquery into MAX() function (you will receive id for the last row matched - i.e. just inserted).
Step back and think about the relationships you're modelling. You have told MySQL that a Project has a Client and a Project Manager; that makes sense. Then you've tried to insert a Project with only this information:
INSERT INTO PROJECTS (Project_Name, Start_Date) ...
The error you're getting is asking you "which Client is this Project for, and who is the Project Manager?" That's something only you can know.
If it's a new Client, you need to insert that before the Project; if it's a new Project Manager, you need to insert that before the Project too. Once you've inserted them, you need to get their IDs, e.g. with the LAST_INSERT_ID() function.
If it's an existing Client and/or Project Manager, you need to look up their IDs based on whatever logic makes sense in your application.
Once you have those two IDs, you can create you Project:
INSERT INTO PROJECTS (Project_Name, Start_Date, Client_Id, Project_Manager_Id) ...
This is wrong:
$sql1 = "INSERT INTO PROJECTS (Project_Name, StartDate) VALUES( '".$_POST["Project_Name"]."','".$_POST["StartDate"]."')";
$sql2 = "INSERT INTO CLIENTS(Client_Name, Client_Email, Client_Phone) VALUES ('".$_POST["Client_Name"]."','".$_POST["Client_Email"]."','".$_POST["Client_Phone"]."')";
$sql3 = "INSERT INTO PROJECT_MANAGERS(ProjectManager_Name,Project_Manager_Email, Project_Manager_Phone) VALUES ('".$_POST["ProjectManager_Name"]."','email', 'phone')";
$sql4 = "INSERT INTO TYPE_OF_WORK(TypeOfWork) VALUES ('".$_POST["TypeOfWork"]."')";
Because you are trying to INSERT into projects a client.id and a project_manager.id that does not exist in the database. So the above should actually be written like this (in case you use mysqli):
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// First add the client in case the table is completely empty
$stmt = mysqli_prepare($link, "INSERT INTO clients(name, email, phone) VALUES (?,?,?);");
mysqli_stmt_bind_param($stmt, 'sss', $_POST["Client_Name"], $_POST["Client_Email"], $_POST["Client_Phone"]);
/* execute prepared statement */
mysqli_stmt_execute($stmt);
/* close statement and connection */
mysqli_stmt_close($stmt);
// Then add the project_manager in case the table is completely empty
$stmt = mysqli_prepare($link, "INSERT INTO project_managers(name, email, phone) VALUES (?,?,?);");
mysqli_stmt_bind_param($stmt, 'sss', $_POST["ProjectManager_Name"], 'email', 'phone');
/* execute prepared statement */
mysqli_stmt_execute($stmt);
/* close statement and connection */
mysqli_stmt_close($stmt);
// Also add the type_of_work in case the table is completely empty
$stmt = mysqli_prepare($link, "INSERT INTO type_of_work(TypeOfWork) VALUES (?);");
mysqli_stmt_bind_param($stmt, 's', $_POST["TypeOfWork"]);
/* execute prepared statement */
mysqli_stmt_execute($stmt);
/* close statement and connection */
mysqli_stmt_close($stmt);
// Finally add your project
$stmt = mysqli_prepare($link, "INSERT INTO projects (project_name, start_date, client_id, project_manager_id) SELECT ?,?,client.id,project_managers.id FROM client,project_managers WHERE client.name = ? AND client.email = ? AND client.phone = ? AND project_managers.name = ?;");
mysqli_stmt_bind_param($stmt, 'ssssss', $_POST["Project_Name"],$_POST["StartDate"],$_POST["Client_Name"], $_POST["Client_Email"], $_POST["Client_Phone"],$_POST["ProjectManager_Name"]);
/* execute prepared statement */
mysqli_stmt_execute($stmt);
/* close statement and connection */
mysqli_stmt_close($stmt);
/* close connection */
mysqli_close($link);
I am having a little issue getting data from a table with while loop. What i want to do is simple I want to take all data from table cart with cookie value from table orders that matches a cookie value and query tables cart to extract data that matches the cookie value in the cart table and place them in table orders_final . Now this is . Now the final part after querying cart table with cookie value gotten from order table, i now want to place the data into orders_final table with all that matches that cookie value from order and cart
$zomo = $_COOKIE['shopa']; // this is the cookie that is stored in the cart table and updated when the transaction is successful
$get_products = "SELECT * FROM `cart` WHERE cookie_value = '$zomo'";
$limo = mysqli_query($con, $get_products);
while($colo = mysqli_fetch_array($limo)){
$product_id = $colo['product_id'];
$order_quantity = $colo['order_quantity'];
$cookie_value = $colo['cookie_value'];
//var $dance is when i update the table with data after payment and data gotten from my payment processing company
$dance = "UPDATE `orders` SET `status`='$r_status',`time`='$r_time',`date`='$r_date',`reference`='$r_reference',`transaction_status`='$r_transaction_status',`transaction_method`='$r_transaction_method',`final_price`='$r_final_price',`order_id`='$r_order_id',`currency`='$r_currency',`referrer`='$r_referrer' WHERE cookie_bought = '$zomo'";
$uii = mysqli_query($con, $dance);
if ($uii){
//this variable insert is where i want to insert all data gotten from cart table above and insert into orders_final, where order table holds the cookie value which was created during shopping which is cookie name shopa held in the variable zomo
$insert = "INSERT INTO `orders_final`(`product_id`, `cookie_value`, `trx_id`, `order_quantities`) VALUES ('$product_id','$zomo','$r_reference','$order_quantity')";
$bena = mysqli_query($con, $insert);
if ($bena){
$delc = "DELETE FROM `cart` WHERE cookie_value = '$zomo'";
$tipee = mysqli_query($con, $delc);
if ($tipee){
perform_success();
}
}
}
}
A better approach is to run fewer queries, that do more. Instead of selecting an entire table and looping over it to run up to 3 queries per iteration (which quickly becomes a lot of queries!), you can use a INSERT INTO...SELECT query instead. Using a transaction, it's also possible to ensure that everything goes through before committing the changes - so you don't end up deleting something that didn't transfer properly.
The code below has been altered to reduce the amount of queries down to three (and none is looped!), and usage of prepared statements has been implemented.
$stmt = $con->prepare("INSERT INTO orders_final (`product_id`, `cookie_value`, `trx_id`, `order_quantities`)
SELECT product_id, ?, order_quantity, ?
FROM cart
WHERE cookie_value=?");
$stmt->bind_param("sss", $zomo, $r_reference, $zomo);
if ($stmt->execute()) {
$stmt->close();
$stmt = $con->prepare("UPDATE orders
SET status=?, time=?, date=?, reference=?, transaction_status=?,
transaction_method=?, final_price=?, order_id=?,
currency=?, referrer=?
WHERE cookie_bought=?");
$stmt->bind_param("sssssssssss", $r_status, $r_time, $r_date, $r_reference, $r_transaction_status, $r_transaction_method, $r_final_price, $r_order_id, $r_currency, $r_referrer, $zomo);
$dance = "UPDATE `orders` SET `status`='$r_status',`time`='$r_time',`date`='$r_date',
`reference`='$r_reference',`transaction_status`='$r_transaction_status',`transaction_method`='$r_transaction_method',`final_price`='$r_final_price',`order_id`='$r_order_id',`currency`='$r_currency',`referrer`='$r_referrer' WHERE cookie_bought = '$zomo'";
$stmt = $con->prepare("DELETE FROM cart WHERE cookie_value=?");
$stmt->bind_param("s", $zomo);
$stmt->execute();
$stmt->close();
}
mysqli::prepare()
mysqli_stmt::bind_param()
MySQL INSERT INTO..SELECT
I'm trying to get the last inserted identity in my Orders table in order to insert the same ID into a linked OrderItems table, for each item in my cart array. My Orders table "orderID" is my identity variable, but when I try to pull the most recently inserted value, the result is "null." The original INSERT query into the Orders table is successful, but for some reason the "SELECT ##IDENTITY" query is not.
PHP Code
$ordersquery= "INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES ('{$phonenumber}', '{$time}', 'online')";
echo $ordersquery."\n";
$result= mssql_query($ordersquery, $db);
var_dump($result);
echo mssql_get_last_message();
$idquery= "SELECT ##IDENTITY as id";
$result= mssql_query($idquery, $db);
$id= mssql_fetch_array($result)[$id];
var_dump($id);
foreach ($cart as $item) {
$itemID= $item['id'];
$quantity= $item['quantity'];
$orderitemsquery= "INSERT INTO OrderItems VALUES ('{$id}' '{$itemID}', '{$quantity}')";
if ($resultitems= mssql_query($orderitemsquery, $db)){
echo $orderitemsquery;
}
}
Result
INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES ('(433) 943-4334', '2015-05-10 14:46:40', 'online')
boolean true
The statement has been terminated.
null
boolean false
Oracle doesn`t have autoincrement. The best you can do, is to get the id first, then do the insert. You get the id like this:
$statement = oci_parse(OCI_CONN, "Select my_seq.nextval from dual");
if (oci_execute($statement)) {
$row = oci_fetch_assoc($statement);
$id = $row['NEXTVAL'];
}
$query = "INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES (?,?,?); SELECT SCOPE_IDENTITY()";
$resource=sqlsrv_query($conn, $query, $arrParams);
sqlsrv_next_result($resource); //note this line!!
sqlsrv_fetch($resource);
echo sqlsrv_get_field($resource, 0);
Or - if you prefer "mssql_" extension functions:
$sql = "INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES (?,?,?); SELECT SCOPE_IDENTITY()";
$results = mssql_fetch_assoc(mssql_query($sql));
$lastid=$results[0];
SCOPE_IDENTITY is generally better because ##IDENTITY is across scopes - it's the last identity inserted into ANY table in the current session, so you better be careful with ##IDENTITY - you can get a value from a trigger or something.
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