I am trying to build a sale invoice page that takes multiple products as input and also some information about the customer. It interacts with four MySQL tables (sales, sale_details, posting, and product_inventory). You'll get the idea of what will happen if a query fails. I want to avoid this. For this purpose I am trying to implement transactions feature of the InnoDB database engine using PHP and MySQL (PHPMyAdmin). Another problem is I've heard that autocommit is turned off by default do I need to turn it ON and then OFF every time I fire a query? Here is my PHP code snippet:
$sal_date = trim($_POST["sale_date"]);
$cust_id = trim($_POST["cust_id"]);
$book_no = trim($_POST["sal_book_no"]);
$rem = $_POST["sal_remarks"];
$st = trim($_POST["sub_total"]);
$disc = floatval($_POST["total_disc"]) + floatval($_POST["adj_disc"]);
$total = trim($_POST["grand_total"]);
$query1 = mysqli_query($link, "INSERT INTO sales
(cust_id, book_no, sale_date, sub_total, discount, total, remarks)
VALUES ('$cust_id', '$book_no', '$sal_date', '$st', '$disc', '$total', '$rem')") or die(mysqli_error($link));
$query2 = mysqli_query($link, "SELECT LAST_INSERT_ID() as last_row") or die(mysqli_error($link));
$sal_id = mysqli_fetch_array($query2);
$sal = intval($sal_id["last_row"]);
$the_query1 = mysqli_query($link, "INSERT INTO `posting`(`type`, `account_id`, `tr_id`, `tr_date`, `debit`) VALUES ('SI','$cust_id','$sal', '$sal_date', '$total')") or die(mysqli_error($link));
$the_query2 = mysqli_query($link, "INSERT INTO `posting`(`type`, `account_id`, `tr_id`, `tr_date`, `credit`) VALUES ('SI','10002','$sal', '$sal_date', '$total')") or die(mysqli_error($link));
for($count=0; $count<$_POST["total_item"]; $count++)
{
$prod_id = floatval(trim($_POST["product_name"][$count]));
$quantity = floatval(trim($_POST["qty"][$count]));
$disc = floatval(trim($_POST["disc"][$count]));
$query3 = mysqli_query($link, "INSERT INTO sale_details (sal_id, prod_id, quantity, discount) VALUES ('$sal', '$prod_id', '$quantity', '$disc')") or die(mysqli_error($link));
$query4 = mysqli_query($link, "INSERT INTO product_inventory (invoice_id, product_id, qty_out, in_date) VALUES ('$sal', '$prod_id', '$quantity', '$sal_date')") or die(mysqli_error($link));
}
I'll appreciate your suggestions.
You can use this method
mysqli_query($db, "START TRANSACTION");
$query1 = mysqli_query($db, "Query 1");
$query2 = mysqli_query($db, "Query 2");
$query3 = mysqli_query($db, "Query 3");
if($query1 && $query2 && $query3) {
mysqli_query($db, "COMMIT");
} else {
mysqli_query($db, "ROLLBACK");
}
Related
I have a page that is taking a kind of long time to load, and I'm almost sure that this is caused by too many sql requests (AKA caused by my bad SQL skills). Is there anyway to join these 3 queries into one?
What I want to do with this query is to try to select a specific id from cardapios and, if there is anything there (if $num_rows > 0) the only thing I want to do is select that id. If there is nothing there, then I want to insert something and then select the id of that.
$query = "SELECT id FROM cardapios WHERE nome='$nome'";
$sql = mysqli_query($con,$query);
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0){
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
$num_rows = 0;
}}else{
$query = "INSERT INTO cardapios (nome, kcal, semana)
VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
$sql = mysqli_query($con,$query);
$query = "SELECT id FROM cardapios WHERE nome='$nome' ";
$sql = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
}
}
I am trying to put all of this into one query but getting nowhere. Is there anyway to use just one query for doing all of this?
Thanks in advance!
You can replace the last query by getting the mysqli_insert_id($con); as you already have the insert id available after the insert
$query = "SELECT id FROM cardapios WHERE nome='$nome'";
$sql = mysqli_query($con,$query);
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0){
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
$num_rows = 0;
}
}else{
$query = "INSERT INTO cardapios (nome, kcal, semana)
VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
$sql = mysqli_query($con,$query);
if ( $sql !== false) { // did insert work
$_SESSION['id_cardapio'] = mysqli_insert_id($con);
} else {
// insert did nto work??
}
}
I have a MYSQL table named issues_tot including following columns:
v_code, oid, amount, mod_date
02) Then I need to update or insert records of the table according to the given condition as follows:
if(($vt == $vote)||($of == $ono)){
03) update is working properly, but insert is not (else part). My code is showing below:
if (isset($_POST["submit"]))
{
$ono =$_POST["oid"];
$amt =$_POST["amt"];
$allo=mysql_fetch_array(mysql_query("SELECT * FROM allocation WHERE al_code='{$_GET['al_code']}'"));
$vote=$allo['v_code'];
$current_date = date("Y-m-d H:i:s");
$query ="select * from issues_tot where v_code='$vote' ";
$result = mysql_query($query) or die ( mysql_error());
$row = mysql_fetch_assoc($result);
$vt = $row['v_code'] ;
$of = $row['oid'] ;
if(($vt == $vote)||($of == $ono)){
$query ="UPDATE issues_tot SET oid = $ono, amount = amount + $amt WHERE v_code=$vote";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
}else {
$query ="INSERT INTO issues_tot (v_code, oid, amount, mod_date) VALUES ('$vote', '$ono', '$amt', '$current_date')";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
}
}
I can not understand what I am going wrong. Can anyone help me ?. Pls
I Queried Database Table 'users' for 'user_id'. and get an array of ids.
$sel = "SELECT user_id FROM users WHERE status='Approved'";
$result = #mysqli_query ($dbcon, $sel);
Then i inserted values into another table income for all those user ids.
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$ins = "INSERT INTO income (user_id, income_amount) VALUES ('$row', '100')";
$giv = #mysqli_query ($dbcon, $ins);
}
Notice: Array to string conversion in E:\xampp\htdocs\project\t.php on line 109
Can anyone help me resolve this issue.
$sel = "SELECT user_id FROM users WHERE status='Approved'";
$result = #mysqli_query ($dbcon, $sel);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$ins = "INSERT INTO income (user_id, income_amount) VALUES ('" . $row['user_id'] . "', '100')";
$giv = #mysqli_query ($dbcon, $ins);
}
First , Check if $results is in array ..you can put some error handling checked is_array($result).
If it is fine then pass it to mysqli_fetch_array().
Do't add suppress # error ,while developing.
i would like to suggest you a single query for that so after that you need not to use while loop to insert your data in income table:
Just try it :
INSERT INTO income (user_id,income_amount) SELECT user_id,'100' AS income_amount FROM users WHERE status = 'Approved';
You can use it like that way :
$sel = "INSERT INTO income (user_id,income_amount) SELECT user_id,'100' AS income_amount FROM users WHERE status = 'Approved'";
$result = #mysqli_query ($dbcon, $sel);
I'm making a form that submits a story into a MySQL table called 'work'. I want to later take the id of the newly created record and put the information into a different table.
But when I submit the story, it says:
$workid is undefined.
I can't see the problem though because I believe I've defined it?
<?php
if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) {
$title = strip_tags($_POST['title']);
$story = strip_tags($_POST['story']);
$title = mysqli_real_escape_string($db, $title);
$story = mysqli_real_escape_string($db, $story);
$genre = $_POST['genre'];
$rating = $_POST['rating'];
$query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
$result = $db->query($query);
$data = $result->fetch_assoc();
if ($data['count'] > 0) {
echo "<p>Story already exists!</p>";
} else {
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc())
$workid = $row["id"]; //workid is written here but still considered undefined
}
$query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
$result = $db->query($query);
$query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
$result = $db->query($query);
if ($result) {
echo "<p>Story submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
}
?>
You never did a $db->query() on your INSERT INTO... query string, so it was never inserted, and was overwritten by your SELECT id ... query.
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$db->query($query); // Missing this $db->query()
$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc())
$workid = $row["id"];}
Your $workid might not be initialized, depending on your condition and the result of your SQL query: so try to avoid next operations that will causes warnings/errors by using continue or else
for some reason, I can't get this to work.
Thanks in advance, a secnod eye might help!
$sql3 = "SELECT order_id FROM orders WHERE order_code = '$order_code'";
$result3 = $conn->query($sql3) or exit("Error code ({$conn->errno}): {$conn->error}");
$row = mysqli_fetch_assoc($result3);
$order_id = $row['order_id'];
$deliv_date = date('Y-m-d');
$sql = "UPDATE orders SET deliv_date = $deliv_date
WHERE order_id = $order_id";
$result = $conn->query($sql) or exit("Error code ({$conn->errno}): {$conn->error}");
$sql1 = "INSERT INTO invoice VALUES (0,'$order_code','$deliv_date','','$order_id')";
$result1 = $conn->query($sql1) or exit("Error code ({$conn->errno}): {$conn->error}");
try this
$sql = "UPDATE `orders` SET `deliv_date` = '".$deliv_date."'
WHERE `order_id` = '".$order_id."'"