PHP to SqlServer, Getting the last inserted identity - php

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.

Related

moving rows to another table and also inserting additional values

Im currently moving rows from "mycart" table to "itemorders" table.
$query = "INSERT into orders
(email,address,postalcode,contactNo,orderdate,status) values
('".$email."','".$address."','".$postalcode."','".$contactNo."','".$orderdate."','".$status."');";
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity) SELECT itemID,itemName,itemSize,itemPrice,quantity FROM mycart WHERE email='".$email."' ";
$result = mysqli_multi_query($conn,$query);
$ordersID = mysqli_insert_id($conn);
Currently, i have an additional field called ordersID in "itemorders" table, the first query also Auto increments a ordersID. I want to insert the $ordersID value that i have used in the first query into the second query. How can i do that?
Use the LAST_INSERT_ID() function in MySQL. It gets the last auto-increment ID, just as mysqli_insert_id() does.
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity,orderSID)
SELECT itemID,itemName,itemSize,itemPrice,quantity, LAST_INSERT_ID()
FROM mycart
WHERE email='".$email."' ";

Get data from table and Insert into another table from while loop

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

SQL/PHP INSERT INTO multiple rows with $row

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

How to get the result of an insert query

I want to get the result of an insert query like this :
$query = "INSERT INTO articles (Title,Description) VALUES ('{$title}','{$description}')";
$result = mysqli_query($connection, $query);
When I insert this article , I want his ID to use it in an other table ! the $result gives a true or false !
You can get the ID of the inserted row by calling the function mysqli_insert_id() directly after your mysqli_query().
$query = "INSERT INTO articles (Title,Description) VALUES ('{$title}','{$description}')";
$result = mysqli_query($connection, $query);
$id = mysqli_insert_id($connection);
use mysqli_insert_id ()
$insertId = mysqli_insert_id ( $connection );
Use this it return the value of your table fiele which is (peimary key) in this table
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());

PHP insert into database query

I am trying to insert values into a database table, a row is inserted but blank no values are inserted. Only the order_id which is the primary key with auto increment increase.
php code:
<?php
$user_get = mysql_query("SELECT * FROM users");
while($row_user = mysql_fetch_assoc($user_get)){
if($row_user['username'] == $_SESSION['username']){
$row_user['first_name'] = $res1;
$row_user['last_name'] = $res2;
$store_order ="INSERT INTO oko (user, product) VALUES ('$res1', '$res2')";
mysql_query($store_order);
}
}
?>
Your assignments are backwards. I think you meant to:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
Don't you mean:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
You could also update the SELECT to have a WHERE clause that checks $_SESSION['username'].
You could also just do an INSERT/SELECT:
INSERT INTO oko (user, product)
SELECT
first_name, last_name
FROM
users
WHERE
username = '$_SESSION["username"]'
Your code is vulnerable to injection. You should use properly parameterized queries with PDO/mysqli

Categories