How to insert two variable value into single field in php? - php

code:
<?php
if(isset($_POST['add_new']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$field = $_POST['field'];
$message = $_POST['message'];
$comment1 =array($_POST['comment1'],$s_date);
$comment2 = $_POST['comment2'];
$status = $_POST['status'];
$s_date = date('Y-m-d');
$interested_in = $_POST['interested_in'];
$academic_details = $_POST['academic_details'];
$city = $_POST['city'];
$sql = "insert into enquires2(name,email,phone,field,message,comment1,comment2,status,s_date,interested_in,academic_details,city,admin_idd)values('$name','$email','$phone','$field','$message','$comment1','$comment2','$status','$s_date','$interested_in','$academic_details','$city','$admin_id')";
$result = mysqli_query($link,$sql);
if($result == true)
{
$msg .= "<p style='color:green;'>You are successfully add new enquiry</p>";
}
else
{
$msg .= "<p style='color:red;'>Error!</p>";
}
}
?>
In this code I want to pass two value in single variable i.e.
$comment1 = array($_POST['comment1'],$s_date);
which show (array) when I print query ($sql). How can I pass two value into single variable ? please help me.

Another option if you don't want to concatenate , use serialize function make an associative array and serialize it and store to db
for example :
$comment1 =serialize(array("comment"=>$_POST['comment1'],"date"=>$s_date));
and when you get form db ,just use
$data = unserialize($yourDataFromDb);
and you get your values like
$data["comment"] // Your comment
$data["date"] // your date

Simply use concatenation
$comment1 = $_POST['comment1'] . $s_date;
But if you want to parse later and keep sepration between comment and date you can use any format like
$comment1 = $_POST['comment1'] . "--date--" . $s_date;
Later you can simply use print_r (explode("--date--",$str));
Something like multivalue field.

You already record the value of $s_date in a separate "date" field, so there's no need to record it again within the comment field.
If you want to combine them for display or reporting purposes later on, then you can easily do that in the object or UI layer using simple string concatenation. I would advise you not to do this when storing the data as you're attempting - otherwise you're just duplicating the same value twice in the row for no obvious reason, as well as making it more difficult to separate what the user actually wrote from the date you inserted into it.

Related

How to populate html texbox with mysql query?

Im trying to populate the textboxes of a CRUD with the information obtained from a query. I use a stored procedure which already works.
I mainly want to give an ID, click search and populate the rest of the texboxes with the clients rest of information. The rest of the buttons already work so I think my problem is located in this section of code:
if(isset($_POST['btnBuscar']))
{
$opc = "buscar";
$idcliente = ($_POST['txtIdCliente']);
$nombre = ($_POST['txtNombre']);
$apaterno = ($_POST['txtApPat']);
$amaterno = ($_POST['txtApMat']);
$tel = ($_POST['txtTel']);
$email = ($_POST['txtEmail']);
$fecalta = ($_POST['txtFechaAlta']);
$query = "CALL sp_clientes('$opc',$idcliente,'$nombre','$apaterno','$amaterno',$tel,'$email','$fecalta')";
if(mysqli_query($con,$query)){
header("location:Clientes.php?searched=1");
this next part where I have doubts
($_POST['txtIdCliente']) = $reg['IdCliente'];
($_POST['txtNombre'])= $reg['Nombre'];
($_POST['txtApPat']) = $reg['APaterno'];
($_POST['txtApMat']) = $reg['ApMaterno'];
($_POST['txtTel']) = $reg['Telefono'];
($_POST['txtEmail']) = $reg['Email'];
($_POST['txtFechaAlta']) = $reg['FecAlta'];
}
Here is the example. you can achieve more by appending HTML in PHP
echo '<input type="text" style="background-color:blue" id="'.$_POST['txtNombre'].'" name="content'.$_POST['txtNombre'].'" value="'.$_POST['txtNombre'].'"></input>';

PHP Array to string to mysql - empty record

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.

removing unwanted characters from string in php

I'm using a database to store variables of user names and then access them using php. A form with post method is used to invoke a php file which access the database, retrieves all the user names and then compares them with the entered values. The user names are stored in $row['name'] variable and the name is stored in $photographer variable.
The problem is that there are some characters attached in string of variable $row['name'] when being accessed from db which I can't get rid of.
I thought using these variables directly might be causing some problems so I saved their values in other two variables. But the problem didn't go away.
Below is the php code:
//pin check module
$connection = mysqli_connect("localhost","root","","members") or die(mysqli_error($connection));
$select_query_pin = "SELECT name, pin FROM members";
$select_query_pin_result = mysqli_query($connection, $select_query_pin) or die (mysqli_error($connection));
$total = mysqli_num_rows($select_query_pin_result);
$pin = $_POST['pin'];
$title = explode(",",$_POST['title']);
$url = explode(",",$_POST['url']);
$photographer = $_POST['photographer'];
$genere = explode(",",$_POST['genere']);
$entry = sizeof($title);
while ($total) {
--$total;
$row = mysqli_fetch_array($select_query_pin_result);
$name_sample = $row['name'];
$test_sample = $photographer;
// chop($name_sample);
// chop($test_sample);
preg_replace( "/\r|\n/", "", $name_sample );
// for ($i = 0; $i < strlen($name_sample); $i++) {
// if ($name_sample[$i] == " ")
// echo 'true';
// }
var_dump($name_sample,$test_sample);
if ($name_sample === $test_sample)
echo 'true<br>';
else
echo "false<br>";}
As you can see, I tried using the chop and preg_replace methods but it didn't work. When I check the strings using var_dump, it gives unequal lengths for equal strings. The html view of above code is this:html output
Is there a way to deal with it?

How to make many variables look neater php

I have a form on a website in which when the page is loaded, it gets all the values for the fields from a database, but when they click submit and the required fields are not filled out, it throws them back and all the data they changed is now reverted to the previous state as if they hadn't touched it at all.
I have decided to put it in variables where if the submit button hasnt been clicked, the variable is the result from the database, but if it has been clicked the variable is the $_POST of the form that has been "submitted".
My question is, how do I make this look "neater" in the code as currently its just 20+ variables, defined twice, in an if statement:
if(!isset($_POST['submit']))
{
$jobtitle = $record['job_title'];
$sitecontact = $record['site_contact'];
$siteph = $record['site_phno'];
$siteadd = $record['site_add'];
$sitesuburb = $record['site_suburb'];
$sitepc = $record['site_pc'];
$jobref = $record['job_ref'];
$quoteref = $record['quote_ref'];
$systembrand = $record['cctv_alarm_brand'];
$jobtype = $record['job_type'];
$datebooked = $record['date_booked'];
[...]
}else{
$jobtitle = $_POST['title'];
$sitecontact = $_POST['cname'];
$siteph = $_POST['cnum'];
$siteadd = $_POST['address'];
$sitesuburb = $_POST['suburb'];
$sitepc = $_POST['postcode'];
$jobref = $_POST['jobref'];
$quoteref = $_POST['quoteref'];
$systembrand = $_POST['brand'];
$jobtype = $_POST['job_type'];
$datebooked = $_POST['date'];
$timebooked = $_POST['time'];
[...]
}
Any advise is greatly appreciated.
Here's how I would do it:
Change the name of the variables so they use the same column names in your database. This will make your code less confusing too in the future for others and for yourself.
Import variables used in the array using extract().
Code:
// turn $record['name'] to $name. be careful because this will overwrite variables
extract($record);
$jobtitle = $jobtitle ?: $_POST['jobtitle'];
Use operator ?
If Condition is true ? then value X : otherwise value Y
$jobtitle = (isset($_POST['submit'])) ? $_POST['title'] : $record['job_title'];
[...]

SimpleXML to get specific data from an XML file

I am making a plugin for JomSocial that will display billing information for a logged-in user, based on an XML file. I have made good headway creating the plugin, I just cant seem to get the syntax right to create php statements so I can populate data in various places on the page. Here is the XML file:
<Inquiry>
<Billing>
<Version>4.5.1</Version>
<startTime><![CDATA[4/15/2014 11:09 PM]]></startTime>
<endTime><![CDATA[4/15/2014 11:12 PM]]></endTime>
<Date>20140415</Date>
<MemberId ID="0ESING">
<BillingInfo>
<StatementEndDate>20140430</StatementEndDate>
<BillingSubAccount>
</BillingSubAccount>
<BalanceForward>628.32</BalanceForward>
<BalanceDue>372</BalanceDue>
<Payments>-300</Payments>
</MemberId>
<MemberId ID="F00421">
</BillingInfo>
<BillingInfo>
<StatementEndDate>20140430</StatementEndDate>
<BillingSubAccount>
</BillingSubAccount>
<BalanceForward>1158.36</BalanceForward>
<BalanceDue>93.45</BalanceDue>
<Payments>-1158.36</Payments>
Here is the PHP so far:
$user =& CFactory::getRequestUser();
$cuser = CFactory::getUser();
$owner = CFactory::getUser($row->user->id);
$ptype = $cuser->getProfileType();
$billingid = $owner->getInfo('FIELD_BILLINGID');
$lastname = $owner->getInfo('FIELD_FAMILYNAME');
$uname = $cuser->username;
$memid = $cuser->id;
$name = $cuser->getDisplayName();
$isMine = COwnerHelper::isMine($cuser->id, $user->id);
$config = CFactory::getConfig();
$source = file_get_contents('data/201404.xml');
$xml = new SimpleXMLElement($source);
$balance = $xml->Billing->MemberId->BillingInfo->BalanceDue;
$BalanceForward = $xml->Billing->MemberId->BillingInfo->BalanceForward;
$Payments = $xml->Billing->MemberId->BillingInfo->Payments;
ob_start();
if( $isMine ) {
if($ptype == '2') {
if(strcasecmp($uname, $billingid) == 0) {
Then, in page to call the fields:
<?php echo "<div>Balance Due: $". $balance ." | Balance Forward: $" . $BalanceForward . " | Payment: $" . $Payments . "</div>"; ?>
This pulls in the first record of the XML file. I was trying something like this for hours:
$source = file_get_contents('data/201404.xml');
$xml = new SimpleXMLElement($source);
$balance = $xml->Billing->MemberId[.$uname.]->BillingInfo->BalanceDue;
$BalanceForward = $xml->Billing->MemberId[.$uname.]->BillingInfo->BalanceForward;
$Payments = $xml->Billing->MemberId[.$uname.]->BillingInfo->Payments;
to no avail. I would like to 'pull' the child node from the XML where the MemberId ID= "yadayada" is equal to the $uname. I hope I am being clear, this is my first post on Stackoverflow!
Using the square bracket notation accesses the attribute by it's name, so you are asking for member[0ESING] which isn't right because the attribute is named ID.
You can iterate of the members to find the match like so:
foreach($xml->Billing->MemberId as $member){
if($member['ID'] == $uname){
$balance = $member->BillingInfo->BalanceDue;
$BalanceForward = $member->BillingInfo->BalanceForward;
$Payments = $member->BillingInfo->Payments;
}
}
Why are you not using simplexml_load_file() instead? It saves you the hassle in loading the file manually and putting it in a simplexml_element instead. Furthermore, I think your issues arrise because the XML file itself is invalid, it need 1 root element but instead seems to contain zero (or multiple, depends on how one would read the file).

Categories