PHP form array value with white space - php

I'm having a problem to pass the value of an associative array position for the value field on a form.
$sql = mysqli_query(
$conn,
"SELECT veiculos_codvei,
revisao.ordemServico,
descricao,
qtd,
precoUnt,
precoTotal
FROM revisao
INNER JOIN itensRevisao ON revisao.ordemServico = itensRevisao.ordemServico
WHERE codRevisao='{$codRevisao}'
");
$array = array();
// retorna consulta sql num array associativo
while ($row = mysqli_fetch_assoc($sql)) {
$array[] = $row;
}
print_r($array[0]['descricao'])
}
return "Óleo 15W40"
then I pass it to input form like this
<input type="text" class="form-control" name="descricao[]" id="descricao" placeholder="Pastilha do Freio" <?php if (isset($array[0]['descricao']) and ! empty($array[0]['descricao'])) echo "value=".$array[0]['descricao']."";?>>
but the value of input is just "Óleo", from google chrome console I can see its the right value but seems to be a concatenation problem.
<input type="text" class="form-control" name="descricao[]" id="descricao" placeholder="Pastilha do Freio" value="Óleo" 15w40="">

you do not have quotes around the value attribute (i.e you have value=Óleo 15W40 instead of value="Óleo 15W40"), the quotes you see are automaticaly added by the browser to fix the broken XML, use the following:
<input
type="text"
class="form-control"
name="descricao[]"
id="descricao"
placeholder="Pastilha do Freio"
<?php if (isset($array[0]['descricao']) and !empty($array[0]['descricao'])) echo "value=\"".$array[0]['descricao']."\"";?>
>

I figured out, I copied this input from another part of the project and I believe there were a reason to put the value tag inside of IF, although this may be wrong anyway.
Putting value outside the IF resolves the problem.
<input type="text" class="form-control" name="descricao[]" id="descricao" placeholder="Pastilha do Freio" value="<?php if (isset($array[0]['descricao']) and ! empty($array[0]['descricao'])) echo $array[0]['descricao'];?>">

Related

How to insert 2 inputs values simultaneously using HTML Arrays & PHP POST?

I am trying to pass 2 arrays in a MYSQL table using HTML array, I want to insert both values in the same row at the same time of the loop, of course nested loop isn't going to work, the first input value passed successfully, but the second input inserts wrong & unrelated values. I am sure it's because the for loop logic is incomplete, but I can't seem to adjust properly. any help will be appreciated.
HTML (...html code inside PHP then this, $row['id'] is the value that shall be passed to POST):
<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';
<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';
<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';
PHP (after successful POST of $comment as input(1) & $decision as input(2) and working queries):
for ($i=0;$i<count($comment);$i++){
$query = "INSERT INTO table (otherid,col1,col2) VALUES ('$otherid','$comment[$i]','$decision[$i]')";
$result = $dbc->query($query);
}
You are getting only the last decision, because you did not use square brackets in the field name, as you did with the comments field. name="decision" needs to be name="decision[]". Only then will PHP create an array out of multiple passed parameters of the same name; without square brackets, they simply overwrite each other.
The duplicate IDs are only of client-side importance - selecting from those lists, will likely not populate the correct input field, but it has little to do with what actually gets submitted, if you filled those fields by hand. But you should be able to make thos IDs dynamic, for example by appending the row ID.
<datalist id="decision-123">, with a matching list="decision-123" on the input field.

how to set array data for the textbox in php

**I have home.php file and superLec.php file. user can enter studentUniversityId and click on the submit button. particular data i want to show studentName textbox and lecturerName textbox. I want to pass data as a array. How to set array data for textbox value.Please any one help me. **.
home.php
<?php
session_start();
include_once 'include/class.supervisor.php';
$supervisor = new Supervisor();
if (isset($_POST['submit'])) {
extract($_POST);
$autofill = $supervisor->check_auto_fill($studentUniversityId);
/* if ($autofill) {
// Registration Success
header("location:homeLecturer.php");
} else {
// Registration Failed
echo 'Wrong username or password';
}*/
}
?>
<form action="" method="post">
<label for="studentID">Student ID</label>
<input type="text" name="studentUniversityId" id="studentID" placeholder="studentID">
<!--input type="submit" id="autoFill" name="autoFill" value="Auto Fill"><br><br>
<input class="btn" type="submit" name="submit" value="Auto Fill"-->
<label for="studentName">Student Name</label>
<input type="text" id="studentName" name="studentName" value = "<?php echo print_r($autofill);?>" placeholder="Student Name"><br><br>
<label for="lecturerName">Supervisor Name</label>
<input type="text" id="lecturerName" name="lecturerName" value = "<?php echo ($lecturerName) ;?>" placeholder="Supervisor Name"><br><br>
<input type="submit" id="submit" name="submit" value="submit">
</form>
**This is my php file. I want pass array values for the home.php file. can any one help me pls. **
superLe.php
public function check_auto_fill($studentUniversityId){
$query = "SELECT supervisor.lecturerName, supervisee.studentName, supervisee.studentUniversityId FROM supervisee, supervisor WHERE supervisee.lecturerId = supervisor.lecturerId AND supervisee.studentUniversityId = '$studentUniversityId' ";
$result = $this->db->query($query) or die($this->db->error);
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
$arr = array("lecturerName", "studentName", "studentName");
return $arr;
}
You have to use JQuery function to set value of form elements.
Post studentUniversityId via ajax get data in response and populate the data to form element.
To create a response with array, you need to extract the fetched data from query and put them into the output array.
I suggest you to use a key/value array.
public function check_auto_fill($studentUniversityId){
$query = "SELECT supervisor.lecturerName, supervisee.studentName, supervisee.studentUniversityId FROM supervisee, supervisor WHERE supervisee.lecturerId = supervisor.lecturerId AND supervisee.studentUniversityId = '$studentUniversityId' ";
$result = $this->db->query($query) or die($this->db->error);
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
$arr = array(
'lecturerName' => $supervisor_data[0]['lecturerName'], //the "0" index depends of the query structure, but as I can see, this is a right way
'studentName' => $supervisor_data[0]['studentName'],
)
//$arr = array("lecturerName", "studentName", "studentName");
return $arr;
}
After that in your home.php you can simple extract the data from array and put the elements in the right fields as exampled:
<label for="studentName">Student Name</label>
<input type="text" id="studentName" name="studentName" value = "<?php echo $autofill['studentName']; ?>" placeholder="Student Name"><br><br>
<label for="lecturerName">Supervisor Name</label>
<input type="text" id="lecturerName" name="lecturerName" value = "<?php echo $autofill['lecturerName']; ?>" placeholder="Supervisor Name"><br><br>
Hope it help you.
Marco
From what I see and understand (please excuse if I don't), you want to populate the text fields studentName and lecturerName with their respective values. To me, you code looks correct except one thing. You need to drop the line
$arr = array("lecturerName", "studentName", "studentName");
from superLe.php. The line
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
already returns an associative array, which you can use in the variable $autofill in file home.php as $autofill['studentName'] or $autofill['lecturerName'].

PHP - Insert elemens into an array

I'm working on a formular, but for the moment I just want to insert into an array my elements (I have books and authors).
I can display my books with author (name + surname) with the foreach, but I can't add more elements.
Here is the code with the form.
<H1>Exercice 2</H1>
<form method="POST">
<label for"code" >Number :</label>
<input id="code" name="code" type="number" />
<label for"title">Title :</label>
<input id="title" name="title" type="text" />
<label for"author" >Author :</label>
<input id="author" name="author" type="text" />
<button type="input" type="submit">Ok</button>
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = array();
$book['code'] = 123;
$book['title'] = "Legendes";
$book['author'] = array("David", "Gemmel");
foreach($book as $value){
$book['key'] = $value;
var_dump($book);
if (is_array($value)) {
foreach($value as $otherValue) {
echo($otherValue);
}
} else {
echo($value);
}
}
I did some searcch, but I don't think it works, it's using the array_push() method with the POST, but I don't know where I can manipulate my form into the array.
If you want some details, I'll be happy to do that =) I'm working on it, if i have some news, you will know =)
Have a nice day =)
1) Assignments are in reverse. Correct way:
$myVar = $myValue
2) You need to set the name attribute in your inputs in order to be sent:
<input id="code" type="number" name="code" />
Then you can access them like:
$_POST['code']
3) To add an element by key in an array, use:
$array['key'] = $value;
Your Exercise 2 have some mistakes :
First, your HTML inputs must have the name attribute to be retrieved by post:
<h1>Exercice 2</h1>
<form method="post">
<label>
<input name="code" type="number" />
</label>
<button type="submit">Ok</button>
</form>
With PHP, you can access to any input value using the name:
$code = $_POST['code'];
Now, I think you want to "add" several books using this HTML form without a storage system. The problem is you can not do this if for every a new request since all the elements you have in your array will be deleted each time you run a new post request. To keep this information you need to use some persistent storage system as a database or others.
Since you seem to want to keep the information for each book together, you need to use a multidimensional array - hence, you'll need to redo the whole thing. Here's a suggestion:
Form:
<h2>Exercice 2</h2>
<form method="post">
<label for"code">Number :</label>
<input id="code" name="code" type="number">
<label for"title">Title :</label>
<input id="title" name="title" type="text">
<label for"author-firstname">Author First Name:</label>
<input id="author-firstname" name="author-firstname" type="text">
<label for "author-lastname">Author Last Name:</label>
<input id="author-lastname" name="author-lastname" type="text">
<input type="submit" name="submit_book" value="Ok">
</form>
Fixed the name-problems, changed the heading (you never, ever use H1 for a form, H1 is strictly used for the site-wide heading/logo/name of site). Also changed the button into a simple input type="submit".
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = []; // changed this to modern PHP version array assignment
$book[0]['code'] = 123;
$book[0]['title'] = "Legendes";
$book[0]['author-firstname'] = "David";
$book[0]['author-lastname'] = "Gemmel"; // no reason to assign a separate array for first and last name, just use two array-keys
for ($c = 0; $c <= count($book); $c++) { //changed this to a for, counting the amount of entries in the $book array
echo 'Title: '.$book[$c]['title'];
echo 'Author: '.$book[$c]['author-firstname'].' '.$book[$c]['author-lastname'];
} // the content should probably be wrapped in a container of some sort, probably a <li> (and then a <ul>-list declared before the for-loop)
Now. None of this has anything to do with putting stuff INTO the array. That would be something like this (there isn't even a point of assigning the $_POST-variables for the code you posted. But, you can do something like this:
if (isset($_POST['submit_book'])) {
$title = $_POST['title'];
$code = $_POST['code'];
$author-firstname = $_POST['author-firstname'];
$author-lastname = $_POST['author-lastname'];
// however, if all you're doing is putting this into the array, no need to assigne the $_POST to variables, you can just do this:
$temp_array = ['code'=>$_POST['code'],'title'=>$_POST['title'],'author-firstname'=>$_POST['author-firstname'],'author-lastname'=>$_POST['author-lastname']];
$book[] = $temp_array;
}
So, that would replace the assigned variables at the beginning of your code.

Prevent empty array records from being submitted in to MYSQL database using php

I want to prevent the empty records in an array from being submitted to the MYSQL database:
HTML part:
<input type="text" name="m_name[]" value="name"/>
<input type="text" name="m_lastname[]" value="lastname"/>
<input type="text" name="m_name[]" value="second_name"/>
<input type="text" name="m_lastname[]" value="second_lastname"/>
<input type="text" name="m_name[]" value=""/>
<input type="text" name="m_lastname[]" value=""/>
and this is the PHP and MySQL part:
if(!empty($_POST['m_name'])) $m_name = array_map('mysql_real_escape_string', $_POST['m_name']);
if(!empty($_POST['m_lastname'])) $m_lastname = array_map('mysql_real_escape_string', $_POST['m_lastname']);
for($l=0; $l < count($m_name); $l++){
mysql_query("INSERT INTO `group_members` SET
`m_name` ='".$m_name[$l]."',
`m_lastname` ='".$m_lastname[$l]."'"
);
}
The problem is that all the 6 inputs, whether those which does not include any values are being submitted to the database. What am I doing wrong?!
I think that the problem is that in case that the $m_name is not empty but $m_lastname is empty then the for loop will be executed and the field m_lastname from tablegroup_members will be empty after insertion.
Since nobody answered the question, I finally got how to do it and I will share it because somebody will encounter my problem and get in this question by chance:
Simply use array_filter(), which conveniently handles all this for you:
$m_name = array_filter(array_map('mysql_real_escape_string', $_POST['m_name']));
$m_lastname = array_filter(array_map('mysql_real_escape_string', $_POST['m_lastname']));

hidden array returns OK but text array is empty html to PHP

Form:
<form method="POST" action="edit_work.php">
<input type="hidden" name="wid[]" size="1" value="<?php echo "$wid1" ?>" >
<input type="text" name="course[]" size="15" value="<?php echo "$course1" ?>" >
PHP:
extract($_POST);
for($i=0;$i<$count;$i++) {
echo $wid[$i];
echo $course[$i];
}
gives the wid values OK but not the text entered for the course names.
I have been through all forums for 2 days now. Any help? Thanks.
If you want your PHP to retrieve your data from the form, can't you name your text input "course", then get it inside your PHP with $_POST['course'] ?
What is your $count ?
Using brackets with your name attribute inside your input tag may be dangerous.
If you're using a list of inputs maybe you can define a text format like name="course#" where # is your index and then access it form your $_POST variable using $_POST['course'.$index]
You don't need to extract($_POST) in that case.

Categories