How to make many variables look neater php - 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'];
[...]

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>';

How to insert two variable value into single field in 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.

php form with multiple item checkbox populate excel spreadsheet

I am building a form in php that will send the owner an email with the request and link to a page where a table will show all requests. I keep getting "array" in the output with the multiple item checklist... Here is what I have
<form>
<input type="checkbox" name="multimedia[]" value="Assessment" />Assessment<br/>
<input type="checkbox" name="multimedia[]" value="elearning module" />E-Learning Module<br />
<input type="checkbox" name="multimedia[]" value="Photography" />Photography<br />
Video Shoot
Other
<?php
$multimedia = array();
echo implode(',', $_POST['multimedia']);
$multimedia_string = implode(',', $multimedia);
?>
//variables in each cell
$variables = array();
$variables['fname'] = $_POST['fname'];
$variables['lname'] = $_POST['lname'];
$variables['email'] = $_POST['email'];
$variables['projectTitle'] = $_POST['projectTitle'];
$variables['$multimedia_string'] = $_POST['$multimedia_string'];
$variables['credentialing'] = $_POST['credentialing'];
$variables['description'] = $_POST['description'];
$variables['results_data_page'] = $results_data_page;
Change this:
$variables['$multimedia_string'] = $_POST['$multimedia_string'];
...to:
$variables['multimedia_string'] = implode(',', $_POST['multimedia']);
Explanation:
PHP interprets $_POST['multimedia'] as an array due to having the square brackets [] after the name, as in multimedia[], so you can implode it using the comma as a separator and get a string returned.
There are some other issues, so try this instead:
<?php
//variables in each cell
$variables = array();
$variables['fname'] = $_POST['fname'];
$variables['lname'] = $_POST['lname'];
$variables['email'] = $_POST['email'];
$variables['projectTitle'] = $_POST['projectTitle'];
$variables['multimedia_string'] = implode(',', $_POST['multimedia']);
$variables['credentialing'] = $_POST['credentialing'];
$variables['description'] = $_POST['description'];
$variables['results_data_page'] = $results_data_page;
?>
Issues:
The first three lines don't seem to do anything.
$multimedia = array(); // never populated
echo implode(',', $_POST['multimedia']);
$multimedia_string = implode(',', $multimedia); // still not populated, so implodes to an empty string.
A couple things here:
$variables['$multimedia_string'] = $_POST['$multimedia_string'];
PHP variables are NOT interpolated in single quoted string. In other words, to translate PHP variables from the variable name $name to the value, in a string, you need to use either double quotes or HEREDOC:
echo "I $emotion you very much.";
$html = <<<EOT
<table>
<tr>
<td>We $emotion camping.</td>
</tr>
</table>
EOT;
So '$multimedia_string' is simply a string containing a dollar sign and the text "multimedia_string".
The other thing is it appears there is no $_POST var with that name or whatever you intended $multimedia_string to translate to.

PHP MYSQL filling an array with variables and change the field names

I'm new to PHP and MySQL. I need to fill an array and I want to change the field names and I can't achieve it.
My code:
$querystr = "SELECT DISTINCT descr_bien,ubicacion,marca,modelo,ano,DescrMoneda,valor FROM bienes,Moneda WHERE bienes.IdMoneda = Moneda.IdMoneda AND bienes.Idpropuesta = '" . addslashes($Idpropuesta) . "'";
$result3 = mysql_query($querystr,$dbConn);
while($hrow = mysql_fetch_assoc($result3)){
$descr_bien = $grow['descr_bien'];
$ubicacion = $grow['ubicacion'];
$marca = $grow['marca'];
$modelo = $grow['modelo'];
$ano = $grow['ano'];
$DescrMoneda = $grow['DescrMoneda'];
$valor = number_format($grow['valor'],2,",",".");
$data = array(array('Descripción'=>$descr_bien,'ubicacion'=>$ubicacion,'marca'=>$marca,'modelo'=>$modelo,'Año'=>$ano,'DescrMoneda'=>$DescrMoneda,'valor'=>$valor),array($hrow));
}
$pdf->ezTable($data,$cols,'Bienes:',array('gridlines'=> EZ_GRIDLINE_DEFAULT,'shadeHeadingCol'=>array(0.6,0.6,0.5),'showBgCol'=>1,'width'=>500,'cols'=>array('valor'=>array('justification'=>'right'))));
Okay first of all I am going to assume you have managed to set up $dcConn to get your database connection. If not go look at http://php.net/manual/en/function.mysql-connect.php
Next your while statement is storing each value in $hrow but you seem to be assigning everything to grow.
Your next issue is that $data will be overwritten for every row in your result.
From what I understand you will be wanting something along the lines of
$querystr = "SELECT DISTINCT descr_bien,ubicacion,marca,modelo,ano,DescrMoneda,valor FROM bienes,Moneda WHERE bienes.IdMoneda = Moneda.IdMoneda AND bienes.Idpropuesta = '" . addslashes($Idpropuesta) . "'";
$result3 = mysql_query($querystr,$dbConn);
while($hrow = mysql_fetch_assoc($result3)){
$descr_bien = $hrow['descr_bien'];
$ubicacion = $hrow['ubicacion'];
$marca = $hrow['marca'];
$modelo = $hrow['modelo'];
$ano = $hrow['ano'];
$DescrMoneda = $hrow['DescrMoneda'];
$valor = number_format($grow['valor'],2,",",".");
$data[] = array('Descripción'=>$descr_bien,'ubicacion'=>$ubicacion,'marca'=>$marca,'modelo'=>$modelo,'Año'=>$ano,'DescrMoneda'=>$DescrMoneda,'valor'=>$valor));
}
I do not know about the last line at all so left it out.
One other suggestion that using the PDO library to access the mysql database would usually be a better idea unless this all that the php will ever need to do.
I hope this helps

HTML id's to one single php variable?

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 .

Categories