Move MySQL table row to another table using PDO - php

i tried to follow this mysql - move rows from one table to another with action to perform a "move to archive" function using PDO and i am failing miserably.
So i have created a job card system, and to cut it short, when a job is complete, i have a "ARCHIVE" button that essentially needs to move the selected job card from table "repairs" into table "archived_repairs". The 2 tables are exactly the same, it just needs to be deleted from repairs table and moved to archived_repairs table in case we need to come back to it at a later stage.
This is the button/link i am using on my CRUD table:
<td>Archive</td>
The above is fine and dandy and goes to a page i named "archive_repair.php" with the following php code:
<?php
require_once "connection.php";
if (isset($_REQUEST['archive_id']))
{
try
{
$job_number = $_REQUEST['archive_id'];
$select_stmt = $db->prepare('SELECT * FROM repairs WHERE job_number =:job_number');
$select_stmt->bindParam(':job_number', $job_number);
$select_stmt->execute();
$row = $select_stmt->fetch(PDO::FETCH_ASSOC);
extract($row);
}
catch(PDOException $e)
{
$e->getMessage();
}
}
if (isset($_REQUEST['btn_archive']))
{
$job_number = $_REQUEST['job_number'];
$date = $_REQUEST['date'];
$client_full_name = $_REQUEST['client_full_name'];
$client_email = $_REQUEST['client_email'];
$client_phone = $_REQUEST['client_phone'];
$item_for_repair = $_REQUEST['item_for_repair'];
$repair_description = $_REQUEST['repair_description'];
$hardware_details = $_REQUEST['hardware_details'];
$diagnostic_fee = $_REQUEST['diagnostic_fee'];
$tech_assigned = $_REQUEST['tech_assigned'];
$current_status = $_REQUEST['current_status'];
$technician_notes = $_REQUEST['technician_notes'];
$admin_notes = $_REQUEST['admin_notes'];
$invoice_status = $_REQUEST['invoice_status'];
$invoice_number = $_REQUEST['invoice_number'];
if (empty($invoice_status))
{
$errorMsg = "Please change Invoice Status Before Archiving this Job Card";
}
else if (empty($invoice_number))
{
$errorMsg = "Please Enter a SAGE Invoice Reference Before Archiving this Job Card";
}
else
{
try
{
if (!isset($errorMsg))
{
$archive_stmt = $db->prepare('INSERT INTO archived_repairs job_number=:job_number, date=:date, client_full_name=:client_full_name, client_email=:client_email, client_phone=:client_phone, item_for_repair=:item_for_repair, repair_description=:repair_description, hardware_details=:hardware_details, diagnostic_fee=:diagnostic_fee, tech_assigned=:tech_assigned, current_status=:current_status, technician_notes=:technician_notes, admin_notes=:admin_notes, invoice_status=:invoice_status, invoice_number=:invoice_number');
$archive_stmt->bindParam(':job_number', $job_number);
$archive_stmt->bindParam(':date', $date);
$archive_stmt->bindParam(':client_full_name', $client_full_name);
$archive_stmt->bindParam(':client_email', $client_email);
$archive_stmt->bindParam(':client_phone', $client_phone);
$archive_stmt->bindParam(':item_for_repair', $item_for_repair);
$archive_stmt->bindParam(':repair_description', $repair_description);
$archive_stmt->bindParam(':hardware_details', $hardware_details);
$archive_stmt->bindParam(':diagnostic_fee', $diagnostic_fee);
$archive_stmt->bindParam(':tech_assigned', $tech_assigned);
$archive_stmt->bindParam(':current_status', $current_status);
$archive_stmt->bindParam(':technician_notes', $technician_notes);
$archive_stmt->bindParam(':admin_notes', $admin_notes);
$archive_stmt->bindParam(':invoice_status', $invoice_status);
$archive_stmt->bindParam(':invoice_number', $invoice_number);
if ($archive_stmt->execute())
{
$delete_stmt = $db->prepare('DELETE FROM repairs WHERE job_number =:job_number');
$delete_stmt->bindParam(':job_number', $job_number);
$delete_stmt->execute();
header("refresh:1;repairs.php");
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
?>
This is my connection.php file:
<?php
$db_host="localhost"; //localhost server
$db_user="ecemscoz_ecemsapp"; //database username
$db_password="C3m3t3ry!#"; //database password
$db_name="ecemscoz_ecemsapp"; //database name
try
{
$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
$e->getMessage();
}
?>
When i click on the ARCHIVE button/link, the page is just blank (white screen), no errors show, nothing is moved to the other database and nothing is deleted. Ive only been coding PHP since 2020 so still new at this, but from my understanding this should of worked... Am i missing something in my code that i am not seeing?

You'll have a much easier time doing this directly in MySQL.
Something like the following should be essentially all you need.
$archive_stmt = $db->prepare("INSERT INTO archived_repairs (
job_number,
date,
client_full_name,
client_email,
client_phone,
item_for_repair,
repair_description,
hardware_details,
diagnostic_fee,
tech_assigned,
current_status,
technician_notes,
admin_notes,
invoice_status,
invoice_number
) (
SELECT
job_number,
date,
client_full_name,
client_email,
client_phone,
item_for_repair,
repair_description,
hardware_details,
diagnostic_fee,
tech_assigned,
current_status,
technician_notes,
admin_notes,
invoice_status,
invoice_number
FROM
repairs
WHERE
job_number =:job_number )");
$archive_stmt->bindParam(':job_number', $job_number);
if ($archive_stmt->execute())
{
$delete_stmt = $db->prepare('DELETE FROM repairs WHERE job_number =:job_number');
$delete_stmt->bindParam(':job_number', $job_number);
$delete_stmt->execute();
header("refresh:1;repairs.php");
}

Related

How to prevent duplicate data in sql databse

I have a form where i save students login data to a database. The form includes the "admission_number", "username" and "password" fields. i want to show an error if the admission number is already existing and a user tries to add it again. Here's my php code for inserting the record.
<?php
if(isset($_POST['submit']))
{
$server = 'localhost';
$username = 'root';
$password = '';
$course_code=$_POST['course_code'];
$course_title=$_POST['course_title'];
$course_units=$_POST['course_units'];
$course_semester=$_POST['course_semester'];
$con=($GLOBALS["___mysqli_ston"] = mysqli_connect($server, $username, $password));
if(!$con)
{
exit('Error: could not establish connection to the server');
}
else
{
$con_db=((bool)mysqli_query($con, "USE esther"));
if(!$con_db)
{
exit('Error: Failed to connect to the database');
}
else
{
if(!empty($course_code) && !empty($course_title) && !empty($course_units) && !empty($course_semester))
{
$insert="INSERT INTO `course_table` VALUES('', '".$course_code."' ,'".$course_title."','".$course_units."','".$course_semester."')";
$query=mysqli_query($GLOBALS["___mysqli_ston"], $insert);
$dup_admission_number = mysql_query("SELECT admission_number FROM users_table WHERE admission_number = $admission_number");
}
if (#mysql_query($dup_admission_number)) {
echo 'Your admission number is already in our database.';
exit;
}
if($query)
{
echo 'course added successfully!';
header("location:add_course.php");
}
else { echo 'Error while adding Course.'; }
}
else
{
echo '*** fields cannot be blank ***.';
}
}
}
?>
To check admission number is unique or not you have to execute bellow query
$sql: "select id from student where admission_number = <> LIMIT 0,1";
if this query show result then you current form's admission number is not unique.
this process you can do using ajax request or you can check it before insert query being process.
or you can manage it in mysql by giving unique key constraint to admission number.
This is the Mysql Query
INSERT INTO sometable (data1, data2, data13)
SELECT 'username' FROM sometable
WHERE NOT EXISTS
(SELECT username FROM sometable WHERE login='someusername');

Value == DisplayText in Field Options or else Fields are Blank

I've already posed this question on the jquery-jtable Github issues section here: https://github.com/hikalkan/jtable/issues/703 . There doesn't seem to be much knowledge being shared there at this time and this issue is significantly hamstringing further development of my project.
I am practically certain I am missing something relatively simple because based on the documentation here: http://www.jtable.org/ApiReference#fopt-options this really should be straightforward with no issues.
Note, this simplified version of code should demonstrate the issue and is not representative of exactly how the code is being implemented. that is, I am strictly trying to solve the reproducible issue not how best to use it in my much larger project.Here's a copy paste of the issue:
Let's make the SQL table:
--Create "employee titles" table
create table employee_titles (employeetitleid int not null IDENTITY, employeetitle varchar(50) not null,
constraint PK_employee_titles_employeetitleid
primary key clustered (employeetitleid))
go
Now let's make the jtable:
<html>
<head>
<link href="/jtabphp/themes/redmond/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
<link href="/jtabphp/scripts/jtable/themes/lightcolor/blue/jtable.css" rel="stylesheet" type="text/css" />
<script src="/jtabphp/scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="/jtabphp/scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<script src="/jtabphp/scripts/jtable/jquery2.3.0.jtable.js" type="text/javascript"></script>
</head>
<body>
<div id="EmployeeTitles" style="width: 600px;"></div>
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#EmployeeTitles').jtable({
title: 'Employee Titles',
actions: {
listAction: 'PersonActions.php?action=list',
},
fields: {
employeetitleid: {
key: true,
create: false,
edit: false,
title: 'Title ID',
width: '10%'
},
employeetitle: {
title: 'Employee Title',
options: 'DropdownSelectors.php?Selector=employeetitle',
optionsSorting: 'text',
width: '45%'
}
}
});
//Load person list from server
$('#EmployeeTitles').jtable('load');
});
</script>
</body>
</html>
Let's create the personactions.php file which runs the SQL queries for action==list:
<?php
// Connect to SQL Server
include '../../phpconfig/connectstrings.php';
try
{
$conn = new PDO ( "sqlsrv:server = $serverstring; Database = $databasestring", "$usernamestring", "$passwordstring");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
catch(Exception $e)
{
die(var_dump($e));
}
try {
//Getting records (listAction)
if($_GET["action"] == "list")
{
//Get records from database
$sql_select = "SELECT employeetitleid, employeetitle FROM employee_titles";
$stmt = $conn->query($sql_select);
//Add all records to an array
$rows = $stmt->fetchall(PDO::FETCH_ASSOC);
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
//Creating a new record (createAction)
else if($_GET["action"] == "create")
{
//Insert record into database
$sql_insert = "INSERT INTO employee_titles (employeetitle) VALUES (?)";
$stmt = $conn->prepare($sql_insert);
$stmt->bindValue(1, $_POST['employeetitle']);
$stmt->execute();
//Get last inserted record (to return to jTable)
$sql_select = "SELECT employeetitleid, employeetitle FROM employee_titles WHERE employeetitleid = ##IDENTITY";
$stmt = $conn->prepare($sql_select);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Record'] = $row;
print json_encode($jTableResult);
}
//Updating a record (updateAction)
else if($_GET["action"] == "update")
{
//Update record in database
$sql_update = "UPDATE employee_titles SET employeetitle = ? WHERE employeetitleid = ?;";
$stmt = $conn->prepare($sql_update);
$stmt->bindValue(1, $_POST['employeetitle']);
$stmt->bindValue(2, $_POST['employeetitleid']);
$stmt->execute();
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
//Deleting a record (deleteAction)
else if($_GET["action"] == "delete")
{
//Delete from database
$sql_delete = "DELETE FROM employee_titles WHERE employeetitleid = ?;";
$stmt = $conn->prepare($sql_delete);
$stmt->bindValue(1, $_POST['employeetitleid']);
$stmt->execute();
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
//Close database connection
$conn = null;
}
catch(Exception $ex)
{
//Return error message
$jTableResult = array();
$jTableResult['Result'] = "ERROR";
$jTableResult['Message'] = $ex->getMessage();
print json_encode($jTableResult);
}
?>
Finally, let's make the DropdownSelectors.php file that is going to query our dropdown contents. depending on how I construct this file I will get 2 different results with neither being satisfactory.
In this 1st example I am going to make [DisplayText] == [Value]. This will correctly display the employee title information in the jtable view and correctly populate the dropdown for create/edit. However, the [Value] reported by the dropdown is not nearly as useful for later queries as it would be if it were actually the employeetitleid as opposed to just a repeat of the employeetitle. The code as shown in both examples produces a perfect match of the type of array expected by jtable as referenced here: http://www.jtable.org/apireference#fopt-options . This should not be in dispute since the create/edit dropdown will work in either example.
Example DropdownSelectors.php #1:
<?php
// Connect to SQL Server
include '../../../phpconfig/connectstrings.php';
try
{
$conn = new PDO ( "sqlsrv:server = $serverstring; Database = $databasestring", "$usernamestring", "$passwordstring");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
catch(Exception $e)
{
die(var_dump($e));
}
if ($_GET['Selector'] == "employeetitle") {
$sql_select = "SELECT employeetitle [DisplayText], employeetitle [Value] FROM employee_titles";
$stmt = $conn->prepare($sql_select);
$stmt->execute();
$rows= $stmt->fetchAll(PDO::FETCH_ASSOC);
$options[Result] = 'OK';
$options[Options] = $rows;
print json_encode($options);
}
?>
In this 2nd example I am going to make [DisplayText] and [Value] pull from different columns in the employee_titles table. This will cause the employee title column of the jtable to be blank but still correctly populate the dropdown for create/edit. In this case, the [Value] reported by the dropdown is very useful for later queries as it actually reports the employeetitleid as opposed to just a repeat of the employeetitle. The code as shown in both examples produces a perfect match of the type of array expected by jtable as referenced here: http://www.jtable.org/apireference#fopt-options . This should not be in dispute since the create/edit dropdown will work in either example. It is completely unacceptable that the displayed jtable column appear blank, however.
Example DropdownSelectors.php #2:
<?php
// Connect to SQL Server
include '../../../phpconfig/connectstrings.php';
try
{
$conn = new PDO ( "sqlsrv:server = $serverstring; Database = $databasestring", "$usernamestring", "$passwordstring");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
catch(Exception $e)
{
die(var_dump($e));
}
if ($_GET['Selector'] == "employeetitle") {
$sql_select = "SELECT employeetitle [DisplayText], employeetitleid [Value] FROM employee_titles";
$stmt = $conn->prepare($sql_select);
$stmt->execute();
$rows= $stmt->fetchAll(PDO::FETCH_ASSOC);
$options[Result] = 'OK';
$options[Options] = $rows;
print json_encode($options);
}
?>
Now that you have all of the code necessary to completely reproduce this very reproducible issue can anyone tell me how to fix it so htat the listed fields display the DisplayText and the dropdown options issue the vlaue that equates to an ID #? I am beginning to believe there is a display bug in jtable itself and that a small fix somewhere would cause the information to appear in the jtable view.
See the linked github issue for some of the workarounds I have attempted and why they do not work.
Okay! I solved this one. Holy cow do I feel dumb. I had a faulty understanding of how Value relates to the record and field name. I had assumed Value was strictly the information passed when a dropdown selection was made. However, as I see now, Value also corresponds to the the record that is contained in the jtable field. Thus, the fieldname will have to correspond to the column name the data comes under just like a standard jtable field does. Value must correspond to that column. So, to fix the provided example we do the following:
if ($_GET['Selector'] == "employeetitleid") {
$sql_select = "SELECT employeetitle [DisplayText], employeetitleid [Value] FROM employee_titles";
$stmt = $conn->prepare($sql_select);
$stmt->execute();
$rows= $stmt->fetchAll(PDO::FETCH_ASSOC);
$options[Result] = 'OK';
$options[Options] = $rows;
print json_encode($options);
}
and
employeetitleid: {
title: 'Employee Title',
dependsOn: 'anotherfield',
options: function (data) { if (data.source == 'list') { return 'DropdownSelectors.php?Selector=employeetitleid&filter=>0'; }
return './../DropdownSelectors.php?Selector=employeetitleid&filter==' + data.dependedValues.anotherfield },
optionsSorting: 'text',
width: '45%'
}
The above example also includes the logic to operate the DepndsOn feature for cascaded dropdowns which is how I ran into this issue to begin with (having [Value]==[DisplayText] "worked well until then). In this example the jtable will show a column name of "Employee title" and the fields will show the text strings that correlate to the title id number. However the actual data being worked with is the title id number which, not surprisingly, makes all of the queries and the field configurations must easier and more efficient.

Error adding order: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

Hey guys I would love your help in regards to the code below, I am quite new to php and and sql, and I am trying to blind these values for a order check out process. There are multiple pages that I need to capture the information from....
I have looked over this code for hours and I am unable to find where I am going wrong...
This may be because I am really not sure where I need to be looking to fix this problem. Any help or advice would help so much!
function writeOrderToDatabase(){
// open database connection
include 'includes/connection.php';
// store order date in Australian format for printouts etc
$_SESSION['orderDate'] = date('d-m-Y');
try{
// create our sql insert orders statement
$sql = "INSERT INTO orders SET orderNbr=: orderNbr,custNbr=:custNbr,orderDate=:orderDate, OrderNetValue=:OrderNetValue,deliverTo = :deliverTo,
deliveryAddress1 = :deliveryAddress1, deliveryAddress2 = :deliveryAddress2, deliverySuburb = :deliverySuburb,
deliveryState = :deliveryState, deliveryPostCode = :deliveryPostCode, deliverySuburb = :deliverySuburb, deliveryState = :state, deliveryPostCode = :deliveryPostCode, deliveryInstructions = :deliveryInstructions, shippingValue=:shippingValue,
paymentType=:paymentType, paymentRef=:paymentRef;";
// prepare the statement
$statement = $pdo->prepare($sql);
$orderNbr = 0;
// bind the values
$statement->bindValue(':orderDate', date('Y-m-d'));
$statement->bindValue(':custNbr', $_SESSION['custNbr']);
$statement->bindValue(':dispatchDate', $_SESSION['dispatchDate']);
$statement->bindValue(':deliveryDate', $_SESSION['deliveryDate']);
$statement->bindValue(':OrderNetValue', $_SESSION['OrderNetValue']);
$statement->bindValue(':deliverTo', $_SESSION['deliverTo']);
$statement->bindValue(':deliveryAddress1', $_SESSION['deliveryAddress1']);
$statement->bindValue(':deliveryAddress2', $_SESSION['deliveryAddress2']);
$statement->bindValue(':deliverySuburb', $_SESSION['deliverySuburb']);
$statement->bindValue(':deliveryState', $_SESSION['deliveryState']);
$statement->bindValue(':deliveryPostCode', $_SESSION['deliveryPostCode']);
$statement->bindValue(':deliveryInstructions', $_SESSION['deliveryInstructions']);
$statement->bindValue(':shippingValue', $_SESSION['shippingValue']);
$statement->bindValue(':paymentType', $_SESSION['paymentType']);
$statement->bindValue(':paymentRef', $_SESSION['paymentRef']);
$statement->bindValue(':sellingPrice', $_SESSION['sellingPrice']);
$statement->bindValue(':newQtyOnHand', $_SESSION['newQtyOnHand']);
// execute the statement
$success = $statement->execute();
} // end try
catch (PDOException $e) {
echo 'Error adding order: ' . $e->getMessage();
exit();
} // end catch
// test the result and get order nbr just created or display appropriate message
if ($success) {
echo $sql = 'SELECT orderNbr FROM orders ORDER BY orderNbr';
foreach ($conn->query($sql) as $row) {
print $row['orderNbr'] . "\t";
}
}
else {
die("<p>Unable to retreive Order Nbr </p>");
}
// read cart and insert orderedItem record(s) and update stock on hand in product records
foreach($_SESSION['cart'] as $prodNbr => $value) {
// store required details in variables
$qtyOrdered = $_SESSION['cart'][$prodNbr]['qtyOrdered'];
$qtyOnHand = $_SESSION['cart'][$prodNbr]['qtyOnHand'];
$sellingPrice = $_SESSION['cart'][$prodNbr]['price'];
try {
// create orderedItem table sql insert statement
$sql = "INSERT INTO orderedItem SET orderNbr=:custNbr,prodNbr=: prodNbr, qtyOrdered=:qtyOrdered,sellingPrice = :sellingPrice;";
} // end try
catch (PDOException $e) {
echo 'Error adding orderedItem: ' . $e->getMessage();
exit();
} // end catch
// test the result and display appropriate message
if (!$success) {
die("<p>Unable to execute the orderedItem table insert</p>");
}
// create new quantity on hand value for the product record
$newQtyOnHand = $qtyOnHand - $qtyOrdered;
try {
// create product table sql update statement
$sql="UPDATE product SET prodNbr= :prodNbr,prodName= :prodName,price= :price,qtyOnHand= :qtyOnHand,description= :description, photo= :photo,thumbNail= :thumbNail ,suppCode= :suppCode ;";
} // end try
catch (PDOException $e) {
echo 'Error updating product qtyOnHand: ' . $e->getMessage();
exit();
} // end catch
// test the result and display appropriate message
if (!$success) {
die("<p>Unable to execute the product table update</p>");
}
} // end of foreach
} // end of function
Here:
$statement->bindValue(':dispatchDate', $_SESSION['dispatchDate']);
$statement->bindValue(':deliveryDate', $_SESSION['deliveryDate']);
$statement->bindValue(':sellingPrice', $_SESSION['sellingPrice']);
$statement->bindValue(':newQtyOnHand', $_SESSION['newQtyOnHand']);
These bind don't exist in the query.
Besides,
orderNbr=: orderNbr
should be
orderNbr = :orderNbr
Please note you don't bind it either.
Also, you're having twice the following parameters in the query:
deliveryState = :state
deliveryState = :deliveryState
deliveryPostCode = :deliveryPostCode
deliveryPostCode = :deliveryPostCode
You have a bad placeholder token first off: orderNbr=: orderNbr needs to be orderNbr=:orderNbr; Note the whitspace. Secondly, even if that was correct i dont see you binding :orderNbr anywhere.
I would think though that the order number should be an autoincrement integer field, and if that is the case you should not include it in your insert.

Insert to database into two tables

This code really made me confused.
The first and second time I ran it, it worked perfectly but after that it stopped working
Let me explain it:
I work with 2 tables.
The first table I insert to it the current date, current time and the id of the user the id I take it from the session.
Which I believe works fine.
My problem is in the second table the error I get is the error i typed in the " print " after the second insert.
this is my code :
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['con_id'])) {
header("location: login.html");
exit();
}
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='';
$con= mysql_connect($DB_HOST ,$DB_USER , $DB_PASSWORD);
if (!$con) {
die('Failed to connect to server :'.mysql_error());
}
$db=mysql_select_db($DB_DATABASE);
if (!$db) {
die("unable to select database");
}
//first table
$qry="insert into shipment values('',NOW(),CURTIME(),'".$_SESSION['con_id']."');";
$resultop=mysql_query($qry);
//to take the id frome last insert because i need it in the second insert
$SNo=mysql_insert_id();
if ($resultop) {
$options=$_POST['op'];//this is the name of the check boxe's
if (empty($options)) {
header("location: manage_itemsE.php");}
// this is the second table .. my reaaal problem
$qun=$_POST['Quantit'];
$size =count($options);
for ($i =0; $i<$size; $i++) {
$qqry="insert into shipmentquantity values('".$options[$i]."','".$SNo."','".$qun[$i]."');"; // $options is array of the id's which i took from the checkbox's in the html ... $qun is array of the values i took form html ... i sure this is right ;)
$resultqun=mysql_query($qqry);
}
if ($resultqun) {
header("location: shipment_order.php");
}
else print "error in the Quantity";
}
else print "error in the shipmet";
Just add some debug statements to find out what is going wrong. Something like -
$resultqun = mysql_query($qqry) or print mysql_error();
You need to do some reading about SQL injection as this script is vulnerable. Checkout these pages on the use of prepared statements - PDO::prepare and mysqli::prepare
UPDATE - here is an example using PDO to interact with your db -
<?php
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['con_id'])) {
header("location: login.html");
exit();
}
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='';
$db = new PDO("mysql:dbname=$DB_DATABASE;host=127.0.0.1", $DB_USER, $DB_PASSWORD);
//first table
$qry = "INSERT INTO shipment VALUES(NULL, CURRENT_DATE, CURRENT_TIME, ?)";
$stmt = $db->prepare($qry);
$resultop = $stmt->execute(array($_SESSION['con_id']));
if(!$resultop){
print $stmt->errorInfo();
} else {
$SNo = $db->lastInsertId();
$options = $_POST['op'];//this is the name of the check boxe's
if (empty($options)) {
header("location: manage_itemsE.php");
exit;
}
// this is the second table .. my reaaal problem
$qun = $_POST['Quantit'];
$size = count($options);
$stmt = $db->prepare("INSERT INTO shipmentquantity VALUES(?, ?, ?)");
for($i = 0; $i < $size; $i++) {
$resultqun = $stmt->execute(array($options[$i], $SNo, $qun[$i]));
}
if($resultqun) {
header("location: shipment_order.php");
} else {
print $stmt->errorInfo();
}
}
What is your primary key for the 'shipmentquantity' table? It looks like you are trying to enter two values of '3' for the primary key and that's where it's going awry.
DESCRIBE `shipmentquanitity`

How do I use Interbase transactions with PHP?

I have a PHP site connected to an Interbase DB. The DB contains orders which users can load and are displayed on screen. The user can make changes to the order and save them. This works but if 2 users load and save the same record then the order contains the changes made by the last user who saved.
When the 2nd user tries to save I want a message to pop up saying the order has been changed and stop the order from being saved.
I know that interbase has transactions to do this as I have a desktop app that implements transactions and the above scenario. However, I do not know how to do the same thing with PHP in a web environment.
The desktop app keeps the db open all the time and the transaction is kept alive from the time it was read to committed. With PHP the db and transaction is opened/created only when each query is run. From what I read the transaction is rolled back at the end of the script if it's not committed.
Code loading an order
PHP Code:
public function GetOrderDetails($in_OrderID)
{
$qry = "SELECT ID, ... , FROM CUSTOMER_INVOICE WHERE ID = $in_OrderID";
$this->dbconn = ibase_connect ($this->host, $this->username, $this->password);
$this->dbtrans = ibase_trans( IBASE_DEFAULT,$this->dbconn );
$result = ibase_query ($this->dbtrans, $qry);
while( $row = ibase_fetch_row($qryResult) )
{
}
ibase_free_result($in_FreeQry);
ibase_close($this->dbconn);
}
Code saving order
PHP Code:
public function SaveOrderDetails()
{
$DoCommit = false;
try
{
$this->dbconn = ibase_connect ($this->host, $this->username, $this->password);
$this->dbtrans = ibase_trans( IBASE_DEFAULT,$this->dbconn );
// Insert/Update the order
if( $this->UpdateOrder() )
{
// Insert Order Items
if( $this->InsertOrderItems() )
{
$DoCommit = true;
}
else
{
$this->ErrorMsg = "ERROR 0003: Order Items could not be inserted";
}
}
else
{
$this->ErrorMsg = "ERROR 0002: Order could not be inserted/updated";
}
if( $DoCommit )
{
if( ibase_commit($this->dbtrans) )
{
$OrderResult = true;
}
else
{
ibase_rollback($this->dbtrans);
$this->ErrorMsg = "ERROR 0004: DB Qry Commit Error";
print $this->ErrorMsg ;
}
}
else
{
ibase_rollback($this->dbtrans);
}
}
catch( Exception $e )
{
ibase_rollback($this->dbtrans);
$this->ErrorMsg = "ERROR 0001: DB Exception: " . $e;
}
ibase_close($this->dbconn);
}
If anyone can tell me where I'm going wrong that would be great. Or, if no one uses Interbase how would you do it with MySQL? I don't want to go down the table locking, timestamp route.
Thanks
Ray
you must use primary key to avoid it. u can use generator to get unique id for each order.

Categories