PHP Array to string to mysql - empty record - php

I am on point where I have to usk on forum.
So, I have an array that is my return from join table sql query.
i am displaying it correctly without the problem.
but some of those values I want to put in different table of mysql database.
$array = joint_table();
$array_value = array['key'];
I can echo array_value and it's displaying correctly, also checked variable type and it returns STRING.
however when I am inserting it into the table, it's empty cell.
I am inserting other stuff like date() and such and that is inserted correctly.
So my sql query works fine, besides I am using same query in other places without problem.
Only values I have from that array are not inserting, but still can echo them.
<?php
$page_title = 'Complete Task';
require_once('includes/load.php');
// Checkin What level user has permission to view this page
page_require_level(2);
$task = join_task_table((int)$_GET['id']);
?>
<?php
if(isset($_POST['complete_task'])){
$area = $task['area'] ;
$jig = $task['jig'];
$desc = $task['description'];
$freq = $task['freq'];
$date = make_date();
$user = current_user();
$user_done = remove_junk(ucfirst($user['name']));
$comment = remove_junk($db->escape($_POST['comment']));
if(empty($errors)){
$sql = "INSERT INTO tpm_history (area_name,jig_name,description,frequency,date_done,done_by_user,comment)";
$sql .= " VALUES ('{$area}','{$jig}','{$desc}','{$freq}','{$date}','{$user_done}','{$comment}')";
$result = $db->query($sql);
if($result && $db->affected_rows() === 1){
$session->msg('s',"Job Completed");
redirect('home.php', false);
} else {
$session->msg('d',' Sorry failed to complete the task!');
redirect('task_complete.php?id='.$task['id'], false);
}
} else{
$session->msg("d", $errors);
redirect('task_complete.php?id='.$task['id'],false);
}
}
?>
I am lost. Help.

Related

Printing single result from db2 query in php

I'm running a query on db2 in a php script, which is running successfully but I can't get it to echo the actual ID of the record I've selected. It does echo my success statement showing it ran successfully but I need the actual sessionid for comparison in another query.
Here I'm selecting the record, executing the query and checking for execution, but I'm also trying to use fetch_row and result to return the single selected ID:
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
$executeSessionMax = odbc_execute($prepareSessionMax);
while(odbc_fetch_row($executeSessionMax)){
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
}
How can I return the sessionID into a variable properly from db2?
You are passing the wrong parameter to the odbc_fetch_row() as $executeSessionMax is either a True or False depending on successful execution.
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
$executeSessionMax = odbc_execute($prepareSessionMax);
while(odbc_fetch_row($prepareSessionMax )){
// correction here ^^^^^^^^^^^^^^^^^^
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
}
You could recode as this specially as a MAX() will only ever return one row so the while loop is not needed either.
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
if (odbc_execute($prepareSessionMax)) {
odbc_fetch_row($prepareSessionMax );
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
// if echo gets lost try writing to a file
error_log("maxResult = $maxResult", 3, "my-errors.log");
} else {
// something went wrong in the execute
}
You could also try
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$result = odbc_exec($DB2Conn, $latest_result);
$rows = odbc_fetch_object($result);
echo $row->SESSIONID;
$maxResult = $row->SESSIONID;

how to insert multiple row data into multiple row in php mysql

I have retrieved data from the table and all the retrieved data to be stored in another table in each row. I have tried the below code but it is inserting only "
$roll_no = $_POST['roll_no'];
$name = $_POST['name'];
$class = $_POST['class'];
$section = $_POST['section'];
$m_am = $_POST['m_am'];
$a_pm = $_POST['a_pm'];
$date = $_POST['date'];
echo $a_pm .'<br>'.$m_am.'<br>'.$roll_no;
/*$sql_2 = mysql_query("INSERT INTO stud_class_attendance (`sca_rollno`, `sca_name`, `sca_class`, `sca_section`,`sca_am`, `sca_pm`,
?>"
Use mysqli instead of mysql to prevent hacking
and also validate the user input use htmlentities() or htmlspecialchars()
<?php
$roll_no = htmlspecialchars($_POST['roll_no']);
$name = htmlspecialchars($_POST['name']);
$class = htmlspecialchars($_POST['class']);
$section = htmlspecialchars($_POST['section']);
$m_am = htmlspecialchars($_POST['m_am']);
$a_pm = htmlspecialchars($_POST['a_pm']);
$date = htmlspecialchars($_POST['date']);
echo $a_pm .'<br>'.$m_am.'<br>'.$roll_no;
$sql_2 = mysqli_query("INSERT INTO stud_class_attendance (`sca_rollno`, `sca_name`, `sca_class`, `sca_section`,`sca_am`, `sca_pm`, `date`)
values ('$roll_no','$name','$class','$section','$m_am','$a_pm','$date');
$sql_2->execute();
?>
You need a loop for that..
Execute your first query. get all the records from the first query. iterate them and insert one by one in database
See the example
$select = mysql_query("SELECT
name,rollno,class,section,a_am,a_pm,`date`
FROM `student`");
// check if event 1 row exists in database
if(mysql_num_rows($select) > 0 ){
// while loop to iterate every row one by one
$count =0;
while ($row = mysql_fetch_assoc($select)) {
$insert = mysql_query("INSERT INTO `stud_class_attendance`
(`sca_rollno`, `sca_name`, `sca_class`, `sca_section`,`sca_am`, `sca_pm`)
VALUES
('".$row['rollno']."','".$row['name']."','".$row['class']."',
'".$row['section']."','".$row['a_am']."','".$row['a_pm']."')");
// check if the query was executed
if(mysql_insert_id() > 0){
$count++;
}
}
}
echo $count." rows inserted";
$sql='
INSERT INTO `stud_class_attendance` (
`sca_rollno`, `sca_name`,`sca_class`, `sca_section`,`sca_am`, `sca_pm`
)
SELECT rollno,name,class,section,a_am,a_pm FROM `student`
';
$sql2=mysqli_query($sql);
$sql2->execute();

Why is my php/mysql update not accurate?

I have a webpage with a button on it. When the button it clicked it sends a request to a page with this code on it
$userName = "tdscott";
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$divID = explode('?', $url);
$id = 0;
$id = explode('#',$divID[1])[1];
$func = $divID[2];
$find = mysqli_fetch_array(mysqli_query($con,"SELECT likes FROM status WHERE id='$id'"))['likes'];
if ($func == "addLike")
{
$promoted = $userName . "-";
mysqli_query($con, "UPDATE status SET promotedBy = CONCAT(promotedBy,'$promoted') WHERE id='$id'");
$find++;
mysqli_query($con,"UPDATE status SET likes = '$find' WHERE id='$id'");
echo $find;
}//end if addLike
elseif($func === "removeLike")
{
echo "ERROR";
}//end if removeLike
elseif ($func === "getLikes")
{
echo $find;
}//end if getLikes
mysqli_close($con);
I left of the database connection information. But for some reason when this is called it produces inaccurate results. For example... Sometimes it will put multiple instances of $promoted in the promotedBy field in my table and sometimes it will update other rows in the table that the id does not equal the current $id. I am wondering if somehow it is getting the $id variable mixed up from when I submitted it with a different value before. Is there a way to reset the variables before I call it each time?
Please note: In the if statement, we are only looking at the addLike portion. I included the other just in case it was causing the problem.
unset($id);
Sorry should have done more research.

Insert multiple rows in to mysql and restrict one of the rows to be entered only once

I have an invoice form which posts multiple rows to an insert page for insertion to multiple rows.My stumbling block is that when I insert the multiple order items with a foreach statement I also insert the invoice gross for each row. How would I go about only inserting for example the "invoice gross amount"on the last line of the insert in a column of my choosing.
I have enclosed the code I am using to insert the form, and before it is mentioned, I have stripped out calls to data cleansing functions for clarity.
<?php
//Lets connect to the database
if(mysqli_connect_errno()){
exit("Failed to connect to the database".mysqli_connect_error());}
//We first insert the header line of the purchase invoice, then we get the insert id and switch to the details table and insert
//the purchased items details
$query ="INSERT INTO acc_posting_headers (company_id,supplier_id,header_ref,header_date,header_type,posting_ref,due_date)
values
('$company_id','$supplier_id','$receipt_ref','$invoice_date','$header_type','$syspost_ref','$due_date')";
//Execute the $sql query on the server to insert the values
if ($conn->query($query) === TRUE) {
$last_post_header_id = $conn->insert_id;
$post_header_id = $last_post_header_id;
/* We have now switched to the details table, so we got the last insert id, we have set the variable
$post header and now insert each purchased item */
foreach ($_POST['lst_nominal_code'] as $row=>$id){
$nominal_code = $_POST['hidden_nominal_code'][$row];
$quantity = $_POST['txt_quantity_'][$row];
$item_cost = $_POST['txt_item_cost'][$row];
$line_total = $_POST['txt_line_total'][$row];
$description = $_POST['txt_description'][$row];
$trade_creditors = 2109;
$invoice_gross = $_POST['txt_gross'];
$vat_line = $_POST['txt_line_vat_'][$row];
$nominal_id = $id;
$subtotal = $_POST['txt_subtotal'];
$vat_total = $_POST['txt_vat_total'];
$vat_control = 2200;
$query = ("INSERT INTO acc_posting_details
(post_header_id,nominal_acc_no,quantity,price,line_total,line_vat,vat_total,description,subtotal,debit,credit)
VALUES
('$post_header_id','$nominal_code','$quantity','$item_cost','$line_total','$vat_line','0','$description','$subtotal','$line_total','0'),
('$post_header_id','$vat_control','0','0','0','$vat_total','total VAT','vat content','0','$vat_total','0'),
('$post_header_id','$trade_creditors','0','0','0','0','0','trade Creditors','0','0','$invoice_gross')");
if ($conn->query($query) === TRUE) {
Header("Location:../add_purchase_invoice.php");
} else {
echo 'Error: '. $conn->error;
}
}
}
$conn->close();
?>
<?php
// echo "<pre>";
// print_r($_POST);
// echo "<pre>";
//echo "vat control".$vat_control;
//echo "vat total is:".$vat_total
?>
Solved, it was quiet easy really once I had a good look,by changing the order of the insert and removing from the "foreach" I achieved what I wanted with the following code. Thanks to all that helped.
<?php session_start();?>
<?php require_once('../Connections/connpay.php'); ?>
<?php require_once('../functions/global_functions.php'); ?>
<?php require_once('../functions/account_functions.php'); ?>
<?php
$supplier_id = clean_data($_POST['lst_supplier']);
$receipt_ref = clean_data($_POST['txt_receipt_ref']);
$invoice_date = clean_data($_POST['txt_receipt_date']);
$due_date = clean_data ($_POST['txt_receipt_due']);
$due_date = clean_data($_POST['txt_receipt_due']);
$company_id = clean_data($_POST['hidden_company_id']);
$syspost_ref = clean_data($_POST['txt_post_ref']);
$header_type = "puchase_invoice";
$nominal_id = clean_data($_POST['lst_nominal_code']);
?>
<?php
//Lets connect to the database
if(mysqli_connect_errno()){
exit("Failed to connect to the database".mysqli_connect_error());}
//We first insert the header line of the purchase invoice, then we get the insert id and switch to the details table and insert
//the purchased items details
$query ="INSERT INTO acc_posting_headers (company_id,supplier_id,header_ref,header_date,header_type,posting_ref,due_date)
values
('$company_id','$supplier_id','$receipt_ref','$invoice_date','$header_type','$syspost_ref','$due_date')";
//Execute the $sql query on the server to insert the values
if ($conn->query($query) === TRUE) {
// we now get the last insert id, and set it to a variable, we also declare the vat & gross amount variables
$last_post_header_id = $conn->insert_id;
$post_header_id = $last_post_header_id;
$vat_control = 2200;
$vat_total = clean_data($_POST['txt_vat_total']);
$trade_creditors = 2109;
$invoice_gross = clean_data($_POST['txt_gross']);
//We are now at the posting details table, we insert the trade creditors and total vat cr amounts first.
$query = ("INSERT INTO acc_posting_details
(post_header_id, nominal_acc_no ,quantity,price,line_total,line_vat,vat_total,description,subtotal,debit,credit)
VALUES
('$post_header_id','$trade_creditors','0','0','0','0','0','trade Creditors','0','0','$invoice_gross'),
('$post_header_id','$vat_control','0','0','0','$vat_total','0','vat content','0','$vat_total','0')");
$conn->query($query);
// Now that we have inserted the two lines to show the trade creditors and vat CR and DR amounts we
//carry on and insert each invoice line from the posted array.
foreach ($_POST['lst_nominal_code'] as $row=>$id){
$nominal_code = $_POST['hidden_nominal_code'][$row];
$quantity = clean_data($_POST['txt_quantity_'][$row]);
$item_cost = clean_data($_POST['txt_item_cost'][$row]);
$line_total = clean_data($_POST['txt_line_total'][$row]);
$description = clean_data($_POST['txt_description'][$row]);
$vat_line = clean_data($_POST['txt_line_vat_'][$row]);
$nominal_id = $id;
$subtotal = clean_data($_POST['txt_subtotal']);
$query = ("INSERT INTO acc_posting_details
(post_header_id, nominal_acc_no ,quantity,price,line_total,line_vat,vat_total,description,subtotal,debit,credit)
VALUES
('$post_header_id','$nominal_code','$quantity','$item_cost','$line_total','$vat_line','0','$description','0','$line_total','0')");
// execute the insert query and push on to the purchase invoice page.
if ($conn->query($query) === TRUE) {
Header("Location:../add_purchase_invoice.php");
} else {
echo 'Error: '. $conn->error;
}
}
}
$conn->close();
?>
<?php
//echo "<pre>";
// print_r($_POST);
// echo "<pre>";
?>
It sounds like your core challenge is determining when you are in the last iteration of your foreach loop, so that you can then modify the query. Is that right?
You could use a counter to help. Something along these lines:
$i = 0;
$len = count($_POST['lst_nominal_code']);
foreach ($_POST['lst_nominal_code'] as $row=>$id) {
// Assign (don't forget to sanitize!) all the POST variables
<snip>
if ($i == $len - 1) {
// This is the last line! We want a different query, with $invoice_gross included
$query = "...";
} else {
// This is NOT the last line, use the default query without $invoice_gross
$query = "...";
}
$conn->query($query);
$i++;
}

table updates empty spaces when user do not enter anything to the textbox

i am doing a project where one may update the name, position, department and tag of the employee.
But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.
my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.
my php code (it now updating) but errors found:
<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);
if(isset($_POST['submitted']))
{
$sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
$result = mysql_query($sql) or die (mysql_error());
if(!$result || mysql_num_rows($result) <= 0)
{
return false;
}
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";
mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
}
?>
*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help
MisaChan
You use $_POST for 'name/pos/dep/tag' and $_GET for 'emp' so you're probably not getting the values.
Change the GETs to POST - that should do it.
Since you're updating, I'd recommend using POST over GET.
GET is more appropriate for searching.
Also, you can put all your update queries into one update query.
Like so.
$name = $_POST['name'];
$pos = $_POST['pos'];
$dep = $_POST['dep'];
$tag = $_POST['tag'];
$emp = $_POST['emp'];
$qry_start = "UPDATE gpl_employees_list SET ";
$where = " WHERE emp_id = $emp";
$fields = "";
$updates = "";
if($name){
$updates .= " `emp_name` = $name,";
}
if($pos){
$updates .= " `emp_pos` = $pos,";
}
if($dep){
$updates .= " `emp_dep` = $dep,";
}
if($tag){
$updates .= " `emp_tag` = $tag,";
}
$updates = substr($updates, 0, -1); //To get rid of the trailing comma.
$qry = $qry_start . $updates . $where;
this is what i used to keep it working :) i hope this could be a source for others as well :)
$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos'] = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep'] = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag'] = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val
$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
$queryString .="`".$key."`='".$val."',";
}
}
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
After making changes to an SQL database, remember to commit those changes, otherwise they'll be ignored.

Categories