Submit two table of data in one form - php

I have a form which contain two table. Each of the table able to add table row. which mean when submit a form using isset $_POST by using "for" right? the things that i concern about is how to submit a single form which contain two table (both of them have function add table row) in single database table. Both of table contain slightly different attribute but in the same database table. i was searching this for a week and didnt found solution yet. I only able to submit a form which contain one table (which have add table row). How about if there is two table but insert into same database table?
if(isset($_POST['submitbtn'])){
//others
$merchant = $_POST['merchant'];
$remark = $_POST['remark'];
$docno = $_POST['docno'];
$category = $_POST['category'];
$claim_amount = $_POST['claim_amount'];
//airfare
$airline = $_POST["airline"];
$origin = $_POST["origin"];
$destination = $_POST["destination"];
$descript = $_POST["desc"];
$docno_air = $_POST["docno_air"];
$category_air = $_POST["category_air"];
$claim_amount_fare = $_POST["claim_amount_fare"];
$email = $ColUser['Email'];
$euser = $_SESSION['UserId'];
$reportName = $_POST['reportname'];
$start_date = date("Y-m-d");
$status="open";
$purpose = $_POST["purpose"];
//get approval
$getapproval = "SELECT * FROM `approve_by` WHERE `user_id` = '".$_SESSION['UserId']."'";
$approvalget = mysqli_query($mysqli,$getapproval);
$appid = mysqli_fetch_assoc($approvalget);
$app1 = $appid['approval_1'];
$app2 = $appid['approval_2'];
$app3 = $appid['approval_3'];
//generate travel id
$travelprefix= "SELECT * FROM `prefix` WHERE `description` = 'Travel'";
$result_travel = mysqli_query($mysqli, $travelprefix);
$travel_info = mysqli_fetch_assoc($result_travel);
$travel_pre = $travel_info['prefix'];
$travel_old_num = $travel_info['running_number'] + 1;
$travel_new = sprintf("%05d", $travel_old_num);
$travel_date_append = date('mY');
$travel_number = $travel_pre."-".$travel_date_append."-".$travel_new;
//generate report id
$reportprefix= "SELECT * FROM `prefix` WHERE `description` = 'REPORT'";
$result_report = mysqli_query($mysqli, $reportprefix);
$report_info = mysqli_fetch_assoc($result_report);
$report_pre = $report_info['prefix'];
$report_old_num = $report_info['running_number'] + 1;
$report_new = sprintf("%05d", $report_old_num);
$report_date_append = date('mY');
$report_number = $report_pre."-".$report_date_append."-".$report_new;
if (!empty($_POST['airline']))
{
for ($i = 0; $i < count($_POST["airline"]); $i++){
$airline = $_POST["airline"][$i];
$origin = $_POST["origin"][$i];
$destination = $_POST["destination"][$i];
$descript = $_POST["desc"][$i];
$docno_air = $_POST["docno_air"][$i];
$category_air = $_POST["category_air"][$i];
$claim_amount_fare = $_POST["claim_amount_fare"][$i];
//$upload_dir = 'upload';
//$targetPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
$targetPaths="upload/";
$filefare = $targetPaths.rand(1000,100000)."-".$_FILES['bill_image_air']['name'][$i];
$file_loc = $_FILES['bill_image_air']['tmp_name'][$i];
$file_basename = substr($filefare, 0, strripos($filefare, '.'));
//$flink='http://localhost/new_exp/'.$file;
move_uploaded_file($file_loc,$filefare);
$mrecordprefix= "SELECT * FROM `prefix` WHERE `description` = 'Category'";
$mresult_record = mysqli_query($mysqli, $mrecordprefix);
$mrecord_info = mysqli_fetch_assoc($mresult_record);
$mrecord_pre = $mrecord_info['prefix'];
$mrecord_old_num = $mrecord_info['running_number'] + 1;
$mrecord_new = sprintf("%05d", $mrecord_old_num);
$mrecord_date_append = date('mY');
$mrecord_number = $mrecord_pre."-".$mrecord_date_append."-".$mrecord_new;
$save_running_records = "UPDATE `prefix` SET `running_number`=? WHERE `description` = 'Category'";
$save_running_report = "UPDATE `prefix` SET `running_number`=? WHERE `description` = 'Report'";
$save_running_travel = "UPDATE `prefix` SET `running_number`=? WHERE `description` = 'Travel'";
$save_new_record = "INSERT INTO `report`(`reportname`, `report_ref`, `UserId`, `CategoryId`, `travel_record`, `remark`, `claim_amount`, `bill_image`, `bill_image_type`, `docno`, `origin`, `airline`, `destination`, `email_from`, `approval_1`, `approval_2`, `approval_3`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$save_count = "INSERT INTO `categorycount`(`CategoryId`, `amount`, `userid`, `categoryno`) VALUES (?, ?, ?, ?)";
$stmt6 = $mysqli->prepare($save_running_records);
$stmt4 = $mysqli->prepare($save_running_report);
$stmt2 = $mysqli->prepare($save_running_travel);
$stmt5 = $mysqli->prepare($save_new_record);
$stmt7 = $mysqli->prepare($save_count);
$stmt6->bind_param('s', $mrecord_old_num);
$stmt4->bind_param('s', $report_old_num);
$stmt2->bind_param('s', $travel_old_num);
$stmt5->bind_param('ssiisssbssssssiii', $reportName, $report_number, $euser, $category_air, $travel_number, $descript, $claim_amount_fare, $filefare, $filefare, $docno_air, $origin, $airline, $destination, $email, $app1, $app2, $app3);
$stmt7->bind_param('isis', $category_air, $claim_amount_fare, $euser, $mrecord_number);
if ($stmt5->execute() == false){
echo 'Fifth query failed: ' . $mysqli->error;
} else {
if ($stmt2->execute() == false){
echo 'gl B query failed: ' . $mysqli->error;
} else {
if ($stmt4->execute() == false){
echo 'gl B query failed: ' . $mysqli->error;
} else {
if ($stmt7->execute() == false) {
echo 'gl B query failed: ' . $mysqli->error;
} else {
if($stmt6->execute() == false){
echo 'gl C query failed: ' . $mysqli->error;
}
$stmt6->close();
}
$stmt7->close();
}
$stmt4->close();
}
$stmt2->close();
}
$stmt5->close();
}
}
airfare table image
others expenses table image
My current problem is now how to handle if table in other expense tab is empty? because when i try to submit form and fill in all the input except for the others expense tab table which i let it empty. when i submit the form, the empty row in other expense tab table is insert in database table as well..

Related

form have to click submit twice before success message in php

I am trying to do a reservation/booking page, so I have a form that gets information from the user and details about the services that they would like and add it to the database. I can insert records with no problems, like the record gets recorded only once and a success message if the data get inserted successfully and a fail message if otherwise should follow. The problem is the message would display after clicking the submit button twice or after the page refreshes.
This is how the code of the message looks:
if ($res_bookings){
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
And for the whole php code
<?php
//to get data from form
if(isset($_POST['submit'])){
//assign values
$customer_name = mysqli_real_escape_string($conn, $_POST['customer_name']);
$customer_number = mysqli_real_escape_string($conn ,$_POST['customer_number']);
$customer_email = mysqli_real_escape_string($conn, $_POST['customer_email']);
$event_type = mysqli_real_escape_string($conn, $_POST['event']);
$start = mysqli_real_escape_string($conn, $_POST['event_start']);
$end = mysqli_real_escape_string($conn, $_POST['event_end']);
$address = mysqli_real_escape_string($conn, $_POST['event_address']);
$menus = $_POST['menu'];
$extras = $_POST['extra'];
$booking_id = rand(000, 999);
$event_id = rand(000, 999);
$payment_id = rand(000, 999);
//no empty values to be inserted in database
if($customer_name == ""){
$_SESSION['name'] = "<p class='failed'>PLEASE FILL NAME</p>";
die();
}
if($customer_number == "" && $customer_email == ""){
$_SESSION['contacts'] = "<p class='failed'>PLEASE FILL CONTACTS</p>";
die();
}
if(empty($menus) || empty($extras)){
$_SESSION['menu'] = "<p class='failed'>PLEASE PICK YOUR MENU OR EXTRAS</p>";
die();
}
////for storing event details to event_details table
$query = "INSERT INTO event_details
SET id = ?,
startTime = ?,
endTime = ?,
eventAddress = ?,
event_type = (
SELECT id
FROM events
WHERE id = ?);";
$stmt = $conn->prepare($query);
$stmt->bind_param("isssi", $event_id, $start, $end, $address, $event_type);
$res_event = $stmt->execute();
if (!$res_event){
echo $conn->error;
}
//create booking record
$query_2 = "INSERT INTO bookings
SET id = ?,
customer_name = ?,
customer_contact_no = ?,
customer_email = ?,
eventID = (
SELECT id
FROM event_details
WHERE id = ?);";
$stmt_2 = $conn->prepare($query_2);
$stmt_2->bind_param("isssi", $booking_id, $customer_name, $customer_number, $customer_email, $event_id);
$res_book = $stmt_2->execute();
if (!$res_book){
echo $conn->error;
}
//create menu record
$menu_query = "INSERT INTO menus_bookings
SET
bookingID = (
SELECT id
FROM bookings
WHERE id = ?),
type = (
SELECT id
FROM menus_types
WHERE id = ?);";
$menu_stmt = $conn->prepare($menu_query);
$menu_stmt->bind_param("ii", $booking_id, $menu);
foreach ($menus as $menu){
$res_menu = $menu_stmt->execute();
}
if(!$res_menu){
echo $conn->error;
}
///create extras record
$extras_query = "INSERT INTO extras_bookings
SET
bookingID = (
SELECT id
FROM bookings
WHERE id = ?),
type = (
SELECT id
FROM extras_types
WHERE id = ?);";
$extras_stmt = $conn->prepare($extras_query);
$extras_stmt->bind_param("ii", $booking_id, $extra);
foreach ($extras as $extra){
$res_extras = $extras_stmt->execute();
}
if(!$res_extras){
echo $conn->error;
}
//calculate fees
$menu_sql = "SELECT SUM(mt.price) as 'menu total'
FROM menus_types mt, menus_bookings mb
WHERE mt.id = mb.type
AND mb.bookingID = ?;";
$stmt_menu = $conn->prepare($menu_sql);
$stmt_menu->bind_param("i", $booking_id);
$stmt_menu->execute();
$result_menu = $stmt_menu->get_result();
$row_menu = $result_menu->fetch_assoc();
$menu_total = $row_menu['menu total'];
$extras_sql = "SELECT SUM(et.price) as 'extras total'
FROM extras_types et, extras_bookings eb
WHERE et.id = eb.type
AND eb.bookingID = ?;";
$stmt_extras = $conn->prepare($extras_sql);
$stmt_extras->bind_param("i", $booking_id);
$stmt_extras->execute();
$result_extras = $stmt_extras->get_result();
$row_extras = $result_extras->fetch_assoc();
$extras_total = $row_extras['extras total'];
$total = $menu_total + $extras_total;
$min = $total * .50;
//create payment details
$query_pay = "INSERT INTO payment_details
SET id = ?,
extras_total = ?,
menus_total = ?,
total = ?,
minPayment = ?;
";
$stmt_pay = $conn->prepare($query_pay);
$stmt_pay->bind_param("iiiii", $payment_id, $extras_total, $menu_total, $total, $min);
$res_pay = $stmt_pay->execute();
if(!$res_pay){
echo $conn->error;
}
//add receipt to booking record
$query_booking = "UPDATE bookings
SET receiptID = (
SELECT id
FROM payment_details
WHERE id = ?)
WHERE id = ?;
";
$stmt_bookings = $conn->prepare($query_booking);
$stmt_bookings->bind_param("ii", $payment_id, $booking_id);
$res_bookings = $stmt_bookings->execute();
if ($res_bookings){
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
}
?>
I am not used to using PHP at all, but I think the issue is in the PHP part and not in the HTML.
You are writing this data to the $_SESSION variable and not actually outputting it to the page.
If you wish to show the success message after the form is submitted just use:
if ($res_bookings) {
echo "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
echo "<h2 class='failed'>BOOKING FAILED</h2>";
}
change this last part of your code:
$stmt_bookings = $conn->prepare($query_booking);
$stmt_bookings->bind_param("ii", $payment_id, $booking_id);
$res_bookings = $stmt_bookings->execute();
if ($res_bookings){
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
}
to this :
$stmt_bookings = $conn->prepare($query_booking);
$stmt_bookings->bind_param("ii", $payment_id, $booking_id);
$res_bookings = $stmt_bookings->execute();
$_SESSION['done'] = "<h2 class='success'>BOOKED SUCCESSFULLY</h2>";
} else {
$_SESSION['done'] = "<h2 class='failed'>BOOKING FAILED</h2>";
}
which means immediately after code execution, success message will be displayed else failed message appears.

Inserting values into another table using a conditional statement

I'm trying to insert values to another table using conditional statement but the values does not insert inside the table.
<?php
if($_POST['save'])
{
$pr_no = $_POST['pr_no'];
$s = mysqli_query($connect,"SELECT purchase_no FROM `sms_request` WHERE purchase_no = '".$pr_no."'");
if(mysqli_num_rows($s) > 0)
{
echo"<script type='text/javascript'>
alert('Purchase No. Existed!');
window.location.href = 'sms_supply management.php';
</script> ";
}
else
{
$fcluster = $_POST['fund_cluster'];
$osection = $_POST['office_section'];
$pr_no = $_POST['pr_no'];
$rcode = $_POST['responsibility_code'];
$desig = $_POST['desig'];
$requester = $_POST['requester'];
$loc = $_POST['loc'];
$purpose = $_POST['prpose'];
$ename = $_POST['entity_name'];
$date = $_POST['date'];
$dateA = date("Y-m-d",strtotime($date));
$radioo = $_POST['supply_type'];
$ins = mysqli_query($connect, "INSERT INTO sms_purchaserecord(purchase_no, supply_type) VALUES ('".$pr_no."', '".$radioo."')");
$insS = mysqli_query($connect, "INSERT INTO sms_ris(purchase_no, ris_num) VALUES ('".$pr_no."', '".$pr_no."')");
$insert = mysqli_query($connect, "INSERT INTO sms_request(purchase_no,sms_request.date, entity_name, fund_cluster, office_section, responsibility_code, purpose, stat) VALUES ('".$pr_no."','".$dateA."','".$ename."', '".$fcluster."', '".$osection."', '".$rcode."','".$purpose."', '1')");
$inS = mysqli_query($connect, "INSERT INTO sms_iar(iar_num, purchase_no) VALUES ('".$pr_no."', '".$pr_no."')");
$select = mysqli_query($connect, "SELECT request_IDnum FROM sms_request WHERE purchase_no = '".$pr_no."'");
while ($row = mysqli_fetch_array($select)){
$rnum = $row['request_IDnum'];
}
$select2 = mysqli_query($connect, "SELECT * FROM sms_branchloc WHERE loc_ID_no = '".$loc."'");
while ($row1 = mysqli_fetch_array($select2)){
$loc_num = $row1['loc_ID_no'];
}
if ($rnum != NULL AND $loc_num != NULL){
$insert2 = mysqli_query($connect, "INSERT INTO sms_requester(request_IDnum, name, loc_ID_no, position) VALUES ('".$rnum."', '".$requester."', '".$loc_num."', '".$desig."')");
}
if ($radioo == 'expandable'){
$insertI = mysqli_query($connect, "INSERT INTO inventory_status(stock_prop_num, description, unit, quantity, price) VALUES ('".$pr_num."','".$unit."','".$desc."','".$qty."','".$cost."')");
}
// If I choose expandable on the radio button it will insert into the inventory_status table
foreach ($_POST['sp_num'] as $row=>$sp_numm) {
$sp_num = $sp_numm;
$unit = $_POST['unt'][$row];
$desc = $_POST['sdesc'][$row];
$qty = $_POST['sqty'][$row];
$cost = $_POST['cost'][$row];
$query = mysqli_query($connect,"INSERT INTO sms_supply (supply_qty,purchase_no,unit_cost,supply_unit,supply_desc,stockproperty_num) VALUES ('".$qty."','".$pr_no."', '".$cost."', '".$unit."','".$desc."', '".$sp_num."')");
}
echo"<script type='text/javascript'>
alert('Purchase Request Save.');
window.location.href = 'sms_supply management.php';
</script>";
}
}
What I wanted to do is if I choose expandable on the radio button it will insert the values into the inventory_status table. The block of code that didn't work is
if ($radioo == 'expandable')
{
$insertI = mysqli_query($connect, "INSERT INTO
inventory_status(stock_prop_num, description, unit, quantity, price) VALUES('".$pr_num."', '".$unit."','".$desc."', '".$qty."', '".$cost."')");
Do I need to connect the 2 tables with a primary key and foreign key?

Data not inserting to database table

When I choose the expandable radio button and press the save button it should save its data to inventory_status table but the data wont insert into the inventory_status table. I've seen similar questions but still couldn't figure out the cause of the problem.
<?php
if($_POST['save']){
if ($_POST['supply_type'] == "expandable"){
$insertI = (mysqli_query($connect, "INSERT INTO inventory_status(stock_prop_no, unit, description, quantity, price) VALUES ('".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')"));
}
$pr_no = $_POST['pr_no'];
$s = mysqli_query($connect,"SELECT purchase_no FROM `sms_request` WHERE purchase_no = '".$pr_no."'");
if(mysqli_num_rows($s) > 0)
{
echo"
<script type='text/javascript'>
alert('Purchase No. Existed!');
window.location.href = 'sms_supply management.php';
</script>
";
}
else{
$fcluster = $_POST['fund_cluster'];
$osection = $_POST['office_section'];
$pr_no = $_POST['pr_no'];
$rcode = $_POST['responsibility_code'];
$desig = $_POST['desig'];
$requester = $_POST['requester'];
$loc = $_POST['loc'];
$purpose = $_POST['prpose'];
$ename = $_POST['entity_name'];
$date = $_POST['date'];
$dateA = date("Y-m-d",strtotime($date));
$radioo = $_POST['supply_type'];
$ins = mysqli_query($connect, "INSERT INTO sms_purchaserecord(purchase_no, supply_type) VALUES ('".$pr_no."', '".$radioo."')");
$insS = mysqli_query($connect, "INSERT INTO sms_ris(purchase_no, ris_num) VALUES ('".$pr_no."', '".$pr_no."')");
$insert = mysqli_query($connect, "INSERT INTO sms_request(purchase_no,sms_request.date, entity_name, fund_cluster, office_section, responsibility_code, purpose, stat) VALUES ('".$pr_no."','".$dateA."','".$ename."', '".$fcluster."', '".$osection."', '".$rcode."','".$purpose."', '1')");
$inS = mysqli_query($connect, "INSERT INTO sms_iar(iar_num, purchase_no) VALUES ('".$pr_no."', '".$pr_no."')");
$select = mysqli_query($connect, "SELECT request_IDnum FROM sms_request WHERE purchase_no = '".$pr_no."'");
while ($row = mysqli_fetch_array($select)){
$rnum = $row['request_IDnum'];
}
$select2 = mysqli_query($connect, "SELECT * FROM sms_branchloc WHERE loc_ID_no = '".$loc."'");
while ($row1 = mysqli_fetch_array($select2)){
$loc_num = $row1['loc_ID_no'];
}
if ($rnum != NULL AND $loc_num != NULL){
$insert2 = mysqli_query($connect, "INSERT INTO sms_requester(request_IDnum, name, loc_ID_no, position) VALUES ('".$rnum."', '".$requester."', '".$loc_num."', '".$desig."')");
}
foreach ($_POST['sp_num'] as $row=>$sp_numm) {
$sp_num = $sp_numm;
$unit = $_POST['unt'][$row];
$desc = $_POST['sdesc'][$row];
$qty = $_POST['sqty'][$row];
$cost = $_POST['cost'][$row];
$query = mysqli_query($connect,"INSERT INTO sms_supply (supply_qty,purchase_no,unit_cost,supply_unit,supply_desc,stockproperty_num) VALUES ('".$qty."','".$pr_no."', '".$cost."', '".$unit."','".$desc."', '".$sp_num."')");
}
echo"
<script type='text/javascript'>
alert('Purchase Request Save.');
window.location.href = 'sms_supply management.php';
</script>
";
}
}
This is the table structure of our inventory_status table:
I found one issue on your following query. sms_request.date should be sms_request_date
$insert = mysqli_query($connect, "INSERT INTO sms_request(purchase_no,sms_request.date, entity_name, fund_cluster, office_section, responsibility_code, purpose, stat) VALUES ('".$pr_no."','".$dateA."','".$ename."', '".$fcluster."', '".$osection."', '".$rcode."','".$purpose."', '1')");
Other thing
All these '".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')" variables are not defined. so you have to take this condition in loop.
For i.e.
foreach ($_POST['sp_num'] as $row=>$sp_numm) {
$sp_num = $sp_numm;
$unit = $_POST['unt'][$row];
$desc = $_POST['sdesc'][$row];
$qty = $_POST['sqty'][$row];
$cost = $_POST['cost'][$row];
if ($_POST['supply_type'] == "expandable"){
$insertI = (mysqli_query($connect, "INSERT INTO inventory_status(stock_prop_no, unit, description, quantity, price) VALUES ('".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')"));
}
$query = mysqli_query($connect,"INSERT INTO sms_supply (supply_qty,purchase_no,unit_cost,supply_unit,supply_desc,stockproperty_num) VALUES ('".$qty."','".$pr_no."', '".$cost."', '".$unit."','".$desc."', '".$sp_num."')");
}

Concatenation of strings not working..!

I am using php mysql pdo in here and trying to concatenate fname and lname but nothing going right am encountering {"error":true,"error_msg":"Unknown error occurred in registration!"} ..plzz help me out,pardon me if am wrong
.php
<?php
/*
starts with database connection
and gives out the result of query
in json format
*/
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
//proceed if fields are not empty
if (!empty($_POST['salutation']) && !empty($_POST['fname']) && !empty($_POST['mname']) && !empty($_POST['lname']) && !empty($_POST['pob']) && !empty($_POST['dob']) && !empty($_POST['qualification']) && !empty($_POST['pg']) && !empty($_POST['pgy']) && !empty($_POST['graduation']) && !empty($_POST['gy']) && !empty($_POST['schooling']) && !empty($_POST['sy']) && !empty($_POST['religion']) && !empty($_POST['caste']) && !empty($_POST['subcaste']) && !empty($_POST['familyname']) && !empty($_POST['fathername']) && !empty($_POST['mothername']) && !empty($_POST['brothers']) && !empty($_POST['sisters'])){
//reciving the post parameters
$salutation =$_POST['salutation'];
$fname = trim($_POST['fname']);
$mname = trim($_POST['mname']);
$lname = trim($_POST['lname']);
$pob = trim($_POST['pob']);
$dob = trim($_POST['dob']);
$qualification = trim($_POST['qualification']);
$pg = trim($_POST['pg']);
$pgy = trim($_POST['pgy']);
$graduation = trim($_POST['graduation']);
$gy = trim($_POST['gy']);
$schooling = trim($_POST['schooling']);
$sy = trim($_POST['sy']);
$religion = trim($_POST['religion']);
$caste = trim($_POST['caste']);
$subcaste = trim($_POST['subcaste']);
$familyname = trim($_POST['familyname']);
$fathername = trim($_POST['fathername']);
$mothername = trim($_POST['mothername']);
$brothers = trim($_POST['brothers']);
$sisters = trim($_POST['sisters']);
/*
validation process
begins from here
*/
// create a new user profile
$user = $db->storeUserProfile($salutation, $fname, $mname, $lname, $pob, $dob, $qualification, $pg, $pgy, $graduation, $gy, $schooling, $sy, $religion, $caste, $subcaste, $familyname, $fathername, $mothername, $brothers, $sisters);
if ($user){
// user stored successfully as post params passed
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["salutation"] = $user["salutation"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["mname"] = $user["mname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["pob"] = $user["pob"];
$response["user"]["dob"] = $user["dob"];
$response["user"]["qualification"] = $user["qualification"];
$response["user"]["pg"] = $user["pg"];
$response["user"]["pgy"] = $user["pgy"];
$response["user"]["graduation"] = $user["graduation"];
$response["user"]["gy"] = $user["gy"];
$response["user"]["schooling"] = $user["schooling"];
$response["user"]["sy"] = $user["sy"];
$response["user"]["religion"] = $user["religion"];
$response["user"]["caste"] = $user["caste"];
$response["user"]["subcaste"] = $user["subcaste"];
$response["user"]["familyname"] = $user["familyname"];
$response["user"]["fathername"] = $user["fathername"];
$response["user"]["mothername"] = $user["mothername"];
$response["user"]["brothers"] = $user["brothers"];
$response["user"]["sisters"] = $user["sisters"];
$response["user"]["uuid"] = $user["unique_id"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}else{
//missing the required fields
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
this is the database part using pdo.
php
public function storeUserProfile($salutation, $fname, $mname, $lname, $pob, $dob, $qualification, $pg, $pgy, $graduation, $gy, $schooling, $sy, $religion, $caste, $subcaste, $familyname, $fathername, $mothername, $brothers, $sisters){
try {
$characters = '0123456789';
$uuid = '';
$random_string_length = 6;
for ($i = 0; $i < $random_string_length; $i++) {
$uuid .= $characters[rand(0, strlen($characters) - 1)];
}
$sql = "INSERT INTO profile_info(salutation, fname, mname, lname, fullname, pob, dob, qualification, pg, pgy, graduation, gy, schooling, sy, religion, caste, subcaste, familyname, fathername, mothername, brothers, sisters, unique_id, created_at) VALUES ( '$salutation', '$fname', '$mname', '$lname', '$fname'.', '.'$lname', '$pob', '$dob', '$qualification', '$pg', '$pgy', '$graduation', '$gy', '$schooling', '$sy', '$religion', '$caste', '$subcaste', '$familyname', '$fathername', '$mothername', '$brothers', '$sisters', '$uuid', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
//concatenate the strings
$sql = "UPDATE profile_info SET fullname = CONCAT(fname, ', ', lname)";
$dbh = $this->db->prepare($sql);
$dbh->execute();
// get user details
$sql = "SELECT * FROM profile_info WHERE familyname = '$familyname' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
return false;
}
The concatenation of first name and last name in your INSERT query is incorrect. Use a $fullname variable to specify full name of the person, and use that variable in your INSERT query. That way you won't have to update the row because you have already inserted the row with the correct full name.
Your code should be like this:
// your code
$fullname = $fname . ", " . $lname;
$sql = "INSERT INTO profile_info(salutation, fname, mname, lname, fullname, pob, dob, qualification, pg, pgy, graduation, gy, schooling, sy, religion, caste, subcaste, familyname, fathername, mothername, brothers, sisters, unique_id, created_at) VALUES ( '$salutation', '$fname', '$mname', '$lname', '$fullname', '$pob', '$dob', '$qualification', '$pg', '$pgy', '$graduation', '$gy', '$schooling', '$sy', '$religion', '$caste', '$subcaste', '$familyname', '$fathername', '$mothername', '$brothers', '$sisters', '$uuid', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM profile_info WHERE familyname = '$familyname' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
// your code
If I understand the issue properly, the values are not being inserted because you are executing, instead, a SELECT statement. SELECT statements do not modify table data. You would instead do something like this:
UPDATE profile_info SET fullname = CONCAT(fname, ', ', lname);
Note, this would update the entire table....
This will fill in a pre-existing column with the new concatenated value made from the fname and lname values of each row.
Of course, if your table does not currently have a column for fullname, add one:
ALTER TABLE profile_info ADD COLUMN fullname varchar(25);
UPDATE
Take this line out:
$sql = UPDATE profile_info SET fullname = CONCAT(fname, ', ', lname);
And change this line:
$sql = "INSERT INTO profile_info(salutation, fname, mname, lname, fullname, pob, dob, qualification, pg, pgy, graduation, gy, schooling, sy, religion, caste, subcaste, familyname, fathername, mothername, brothers, sisters, unique_id, created_at) VALUES ( '$salutation', '$fname', '$mname', '$lname', '$fname'.', '.'$lname', '$pob', '$dob', '$qualification', '$pg', '$pgy', '$graduation', '$gy', '$schooling', '$sy', '$religion', '$caste', '$subcaste', '$familyname', '$fathername', '$mothername', '$brothers', '$sisters', '$uuid', NOW())";
You'll see I added 'fullname' in the columns list, and this in the values list: '$fname'.', '.'$lname',
using PHP's concatenation operator .
The correct way to accomplish this is to simply concatenate the values and insert them at the very same time you insert the rest of the values. Let me know if that does it for you.
A side note, editing your original code does make the question more confusing for viewers who came in after the edits were made. Consider adding notes about any edits to the code, instead of editing the original example.

PHP MySqli Inserting

I have this script:
<?php
ini_set('max_execution_time', 0);
ini_set('display_errors','1');
ini_set('default_charset','utf-8');
include("includes/mysqli.php");
$con->set_charset("utf8");
$sql = "INSERT INTO clans(id, clanid, name, badge, status, playercount, score, requiredtrophies, warswon, warslost, warstied, location,warfrequency, exp, level, description, playerjson, lastupdate)
VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, now())";
$stmt = $con->prepare($sql); //prepare update statement
$stmt->bind_param('ssisiiiiiissiiss',$clanid,$name,$badge,$status,$playercount,$score,$requiredtrophies,$warswon,$warslost,$warstied,$location,$warfrequency,$exp,$level,$description,$playerarray);
$stmts = $con->prepare("SELECT * FROM activeclans WHERE id > 137439657919 ORDER BY id ASC"); //Prepare select statement
$stmts->execute(); //execute select statement
$result = $stmts->get_result(); //get select statement results
while ($row = $result->fetch_assoc()) {
$clanid = $row['id'];
$clanurl = "http://185.112.249.77:9999/Api/clan?clan=$clanid";
$jsondata = file_get_contents($clanurl);
$data = json_decode($jsondata,true);
if($data['name'] != null){
$name = $data['name'];
}else{
$name = "";
}
$badge = $data['badge'];
if($data['status'] != null){
$status = $data['status'];
}else{
$status = "";
}
$playercount = $data['playerCount'];
$score = $data['score'];
$requiredtrophies = $data['requiredTrophies'];
$warswon = $data['warsWon'];
$warslost = $data['warsLost'];
$warstied = $data['warsTied'];
if($data['clanLocation'] != null){
$location = $data['clanLocation'];
}else{
$location = "";
}
if($data['warFrequency'] != null){
$warfrequency = $data['warFrequency'];
}else{
$warfrequency = "";
}
$exp = $data['exp'];
$level = $data['level'];
$description = $data['description'];
$playerarray = json_encode($data['players']);
/* Execute update statement */
$stmt->execute();
}
echo $stmt->affected_rows;
$stmt->close();
$stmts->close();
$con->close();
?>
And it is basically inserting around 157K (157 THOUSAND) rows of data. And the data is quite big as well! You can't check the file_get_contents URL out because the port is open only to localhost.
What is the quickest way to insert all this data? It has been running for almost 24 hours now and done 65K. I did try and use transactions but that didn't work well. It gave my 502 Bad Gateway and therefore I lost a lot of time on the script because it rolled back after adding 3 thousand rows (which was however quite quick!)
Also it is possible that the script may at some point fail and leave some of the varchar fields as null hence I have made it so that they end up as an empty string so that there aren't any mySql errors (I got those exceptions thrown when using transactions)
This is the code I used with the transaction stuff. I'm pretty new to prepared statements. I converted this code from standard queries to prepared today and then tried transactions.
<?php
ini_set('max_execution_time', 0);
ini_set('display_errors','1');
ini_set('default_charset','utf-8');
include("includes/mysqli.php");
$con->set_charset("utf8");
$sql = "INSERT INTO clans(id, clanid, name, badge, status, playercount, score, requiredtrophies, warswon, warslost, warstied, location,warfrequency, exp, level, description, playerjson, lastupdate)
VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, now())";
$stmt = $con->prepare($sql); //prepare update statement
$stmt->bind_param('ssisiiiiiissiiss',$clanid,$name,$badge,$status,$playercount,$score,$requiredtrophies,$warswon,$warslost,$warstied,$location,$warfrequency,$exp,$level,$description,$playerarray);
$stmts = $con->prepare("SELECT * FROM activeclans WHERE id > 137439657919 ORDER BY id ASC"); //Prepare select statement
$stmts->execute(); //execute select statement
$result = $stmts->get_result(); //get select statement results
try{
$con->autocommit(FALSE);
while ($row = $result->fetch_assoc()) {
$clanid = $row['id'];
$clanurl = "http://185.112.249.77:9999/Api/clan?clan=$clanid";
$jsondata = file_get_contents($clanurl);
$data = json_decode($jsondata,true);
if($data['name'] != null){
$name = $data['name'];
}else{
$name = "";
}
$badge = $data['badge'];
if($data['status'] != null){
$status = $data['status'];
}else{
$status = "";
}
$playercount = $data['playerCount'];
$score = $data['score'];
$requiredtrophies = $data['requiredTrophies'];
$warswon = $data['warsWon'];
$warslost = $data['warsLost'];
$warstied = $data['warsTied'];
if($data['clanLocation'] != null){
$location = $data['clanLocation'];
}else{
$location = "";
}
if($data['warFrequency'] != null){
$warfrequency = $data['warFrequency'];
}else{
$warfrequency = "";
}
$exp = $data['exp'];
$level = $data['level'];
$description = $data['description'];
$playerarray = json_encode($data['players']);
/* Execute update statement */
if(!$stmt->execute()){
throw new Exception("Cannot insert record. Reason :".$stmt->error);
}
}
$con->commit();
}catch (Exception $e) {
echo 'Transaction failed: ' . $e->getMessage();
$con->rollback();
}
echo $stmt->affected_rows;
$stmt->close();
$stmts->close();
$con->close();
?>
Thanks :)
$sql="
INSERT INTO
ue_game_alliance_rank_rights
(
rank
, `right`
)
VALUES
";
$insertQuery = array();
$insertData = array();
foreach ($rights_status['add'] AS $row ) {
$insertQuery[] = '(?,?)';
$insertData[] = $rank;
$insertData[] = $row['id'];
}
if (!empty($insertQuery)) {
$sql .= implode(', ', $insertQuery);
$stmt = $this->db->prepare($sql);
$stmt->execute($insertData);
}
}
That's an example of the basic technique, you would need to swap the functions for their equivalent mysqli_* functions. For each field having data inserted into it, you need:
$insertData[] = $row['id'];
$row needs to match whatever you've used in your foreach loop and ['id'] needs to be whatever the name of the field is that you're inserting into.
$insertQuery[] = '(?,?)';
You need as many placeholders as fields that you'll be inserting into.
Overall it creates a bulk insert, so you need to have the data to be inserted in an array. Given the amount of data that you're inserting, use transactions, you'll probably need to experiment to see how many rows you can bulk insert at a time before the server complains

Categories