Please help...
I would like to know how you display multiple html id's (e.g. firstname & surname) in one .php variable (e.g $firstname )...
Here's my code:
$customerFirstname = $_POST['firstname'];
$customerSurname = $_POST['surname'];
$customerFullname = ''; // first & surname id's of customer retrieved from enquiryForm
Thanks in advance...
Thanks All for your comment... really appreciated
Try with concatination of two strings like
$customerFirstname = $_POST['firstname'];
$customerSurname = $_POST['surname'];
$customerFullname = $customerFirstname .' '. $customerSurname;
Not sure whether you mean an array or a string, so I'll provide an example of both.
Array:
$customerFullName = array($customerFirstName, $customerLastName);
Concatenation:
$customerFullName = $customerFirstName . ' ' . $customerLastName;
Just concatenate the variables in other. Like it:
$customerFirstname = $_POST['firstname'];
$customerSurname = $_POST['surname'];
$customerFullname = $customerFirstname.' '.$customerSurname;
The quick and easy solution , Use an array . A better approach , use an object . In the second case you can group all user related functions , properties together , so my vote goes for objects .
Related
I have two arrays. I want to add : in between them and add them both into another array.
$temp = json_decode($csv[$indexLoc['allowance_json']], TRUE);
$details = is_array($temp)?(array_key_exists('details', $temp)?$temp['details']:''):'';
$anytime = is_array($temp)?(array_key_exists('anytime', $temp)?$temp['anytime']:''):'';
$deals[$counter]['deal_mins'] = $details .":". $anytime;
I need that code above to work.
I have also the basic one that always works
$deals[$counter]['deal_mins'] = is_array($temp)?(array_key_exists('details', $temp)?$temp['details']:''):'';
That one works, but I need to have two arrays separated by : instead.
Are you getting any errors? Your code looks fine.
$allowance_json = '{"details":"foo", "anytime":"bar"}';
$temp = json_decode($allowance_json, TRUE);
if (is_null($temp)) throw new Exception(json_last_error());
$details = (isset($temp['details']) ? $temp['details'] : '');
$anytime = (isset($temp['anytime']) ? $temp['anytime'] : '');
echo $details . ':' . $anytime;
That output is a string. The string values you pulled out of there concatenated by a :. With the line of code below you are pushing that string back into an array. Is that what you want?
$deals[$counter]['deal_mins'] = $details . ":" . $anytime;
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.
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'];
[...]
This one should be easy and it's killing me I can't find the solution!
I have a SQL query return records from a database. The two fields I am using are $row["staff_id"] and $row["name"].
From that I want to build a dynamic variable which is something like:
$staffid_1 = "Mark Smith";
$staffid_2 = "Sally Baker";
$staffid_3 = "Peter Pan";
The varibale name is created dynamically be combining "staffid_" and $row["staff_id"] for the first part then $row["name"] for the name.
I've tried:
${$staff_id . $row["staff_id"]} = $row["name"];
echo ${$staff_id . $row["staff_id"]} . "<br>";
But no luck! Any assistance would be appreciated :)
I would think you might be best to change your query to return the first part of it, then whatever you're calling it from to concatenate it together, eg
Query:
SELECT '$staffid_' + ltrim(rtrim(cast(staff_id as varchar))) + ' = "' + name + '"'
FROM [table list]
ORDER BY ...
Then concatenate the individual rows of result set as required, with in-between as you seem to require.
Okay so in PHP you have an awesome option to use a double leveled variable which basically means this :
$$varname = $value;
This results in the fact that if you have a string variable ,
(for example $staffid = "staffid_1") that you can do the following:
$staffid = "Jasonbourne";
$$staffid = "Matt Damon";
// Will result in
$JasonBourne = "Matt Damon";
So for your example:
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
Will result in the variable : $staff_id_1 = "Mark Smith";
To read more about double - leveled variables :
http://php.net/manual/en/language.variables.variable.php
EDIT: If you wanna loop through the rows :
foreach ($sql_result as $row) {
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
}
I'm new to PHP. I'm trying to split up my array (done successfully) and submit them as individual submisions into my MYSQL Table (via FOR loops). However, using the code below, it only submits the LAST object in the array. And thus defeats the whole purpose of the desired function. Can anybody show me a way to avoid this?
$directives = "(John Doe, Directive, Time)(Jane Doe, Directive2, Time2)";
$action = explode("(" ,str_replace (")","",$directives));
for ($i = 0; $i < count($action); ++$i){
$newdata = explode("," , $action[$i]);
$name = $newdata[0];
$namesplit = explode(" " , $name);
$actiondo = $newdata[1];
$date = $newdata[2];
$sqlaction="INSERT INTO TABLE (Firstname, lastname, Description, Action, date)
VALUES
('$namesplit[0]','$namesplit[1]',' Directive','$actiondo','$date')";
}
You are overwriting your query in $sqlaction with each loop iteration, thus this is not useful.
You also don't need a query for each row. You can build up a query that would allow insert of all rows with a single query. Something like this:
$query = 'INSERT INTO TABLE (Firstname, lastname, Description, Action, date)
VALUES ';
for ($i = 0; $i < count($action); ++$i){
$newdata = explode("," , $action[$i]);
$name = $newdata[0];
$namesplit = explode(" " , $name);
$actiondo = $newdata[1];
$date = $newdata[2];
$query .= "('" . $namesplit[0] . "','" . $namesplit[1] . "'Directive','" . $actiondo . "','" . $date . "'),";
}
$query = rtrim(',', $query);
// not shown - execute query using $query
First, you would have to put the code that actually puts stuff in the database inside the loop in order to do lots of individual submissions. All your code currently does is just set the same string over and over. That's why only the last one gets inserted.
Second, why don't you just do one insert? You can have multiple values parentheses, you know. Like this:
VALUES (x, y, z), (x2, y2, z2), (x3, y3, z3)
Third, your design is just asking for trouble because you're making so many assumptions about your data. Imagine that there's a person like "James Earl Jones" in your list. Here's how it would go:
$namesplit = explode(" ", 'James Earl Jones');
echo $namesplit[0]; // = James
echo $namesplit[1]; // = Earl
Oops, now his name is just "James Earl."
To avoid this kind of thing, you have to check the data carefully before inserting it, and you really need to think about what might happen if there are extra commas or spaces every time you do those explodes.