I have multiple inputs (never being the same, because it's a dynamic add/remove jquery script, and it is all dependent on how many "tracks" the user wants to enter). I WILL NEVER KNOW HOW MANY WILL BE THERE. Below is an example of if a user chooses to add four "tracks" to their "mixtape".
<input size="32" class="mixtapetrack" type="textbox" id="track[1]" name="track[]" >
<input size="32" class="mixtapetrack" type="textbox" id="track[2]" name="track[]" >
<input size="32" class="mixtapetrack" type="textbox" id="track[3]" name="track[]" >
<input size="32" class="mixtapetrack" type="textbox" id="track[4]" name="track[]" >
When the form is submited (PHP POSTED), I want to take all of the inputs and combine them into one array, but sepparating them all by "^^^".
This is what I have so far, for rendering out the inputs (NOT WORKING).
$trackVAR = $_POST['track'];
$allmixtapetracks = "";
foreach ($trackVAR as $value) {
$allmixtapetracks .= '' . $value . '^';
}
And This is what i'm using to insert into my table (WORKS, tested it without the variable and entered absoloute data)
$sql = mysql_query("INSERT INTO mixtapes (title, songs, posted_by_id, description, date)
VALUES('$mixtapetitle','$allmixtapetracks','$posted_by_id','$mixtapedescription', now())")
or die (mysql_error());
In the end I want it to look like this inside of the songs row
Title of first song haha ^^^ Title of second song!!! ^^^ The
Title Of the third! ^^^ And The Title OF the Fourth
Use implode()
echo implode($trackVAR, " ^^^ ");
Replace your following code:
$trackVAR = $_POST['track'];
$allmixtapetracks = "";
foreach ($trackVAR as $value) {
$allmixtapetracks .= '' . $value . '^';
}
with this:
$allmixtapetracks=implode('^^^',$_POST['track']);
Related
I have been searching this for the last couple of hours and there are a few very similar questions and answers but none are quite working for my situation. What I'm trying to do is insert a list of songs set to the same value for two columns, one per row, and with a couple of options set via radio buttons. The latter is the reason why I can't just write all of the songs in a textarea and split them.
This is what the form looks like (obviously not fully designed)
There are only three there now while I get it working, in reality an unlimited amount may be added via javascript.
And the code:
<form action="" method="post">
<label>Session ID</label>
<input type="text" name="session-id"><br>
<label>Songs</label><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="update-date" value="<?php echo date(" Y-m-d H:i:s ");?>" hidden readonly><br>
<input type="submit" name="submit" value="Submit">
</form>
The desired result, assuming the ID has been set and a unique song entered for each of the them, and whatever variety on the radio buttons, would be three table rows. session-id and update-date would all be the same value, the rest would be unique based on entry.
This is what I currently have, but it only inserts the last of the three songs.
for ($i=0; $i < count($_POST['song-key']); $i++ ) {
$sessionkey = mysqli_real_escape_string($connection, $_POST["session-key"]);
$songkey = mysqli_real_escape_string($connection, $_POST["song-key"][$i]);
$partial = mysqli_real_escape_string($connection, isset($_POST['is-partial'][$i])) ? 1 : 0;
$jam = mysqli_real_escape_string($connection, isset($_POST['is-jam'][$i])) ? 1 : 0;
$updated = mysqli_real_escape_string($connection, $_POST["update-date"]);
$sql = "INSERT INTO session_songs (session_key, song_key, is_partial, is_jam, last_updated)
VALUES ('$sessionkey', '$songkey', '$partial', '$jam', '$updated')";
}
What do I need to change to ensure all three (or more) are entered?
If you alter your input names, you can get a more useful $_POST array.
<input type="text" name="songs[0][key]">
<input type="checkbox" name="songs[0][is-partial]">
<input type="checkbox" name="songs[0][is-jam]"><br>
<input type="text" name="songs[1][key]">
<input type="checkbox" name="songs[1][is-partial]">
<input type="checkbox" name="songs[1][is-jam]"><br>
<input type="text" name="songs[2][key]">
<input type="checkbox" name="songs[2][is-partial]">
<input type="checkbox" name="songs[2][is-jam]"><br>
With specified keys, the checkbox type inputs will match up properly with the text inputs, where they way you have it now, they will not*, because only checked checkboxes are submitted to PHP. (Try only checking "is-partial" in the second and "is-jam" in the third row, and then var_dump($_POST), and you'll see that they both have index 0.)
If your form is structured like that, you can insert your records using a foreach loop instead of a for loop.
foreach ($_POST['songs'] as $song) {
$key = $song['key'];
$partial = isset($song['is-partial']) ? 1 : 0;
$jam = isset($song['is-jam']) ? 1 : 0;
// do the insert inside the loop rather than just building the SQL
}
The reason you're currently only getting the last one is that you're defining the SQL string inside the loop, but without executing the statement in the loop, you'll only get the values from the last iteration of the loop. Move your query execution inside the loop and you should get all three rows.
*unless they are all checked
I have searched across the entire web and I cant seem to find a solution. I am pretty much searching a database for individuals. I can use last name for instance and then if two people have the same last name they both will print on my page. I want to be able to select the individual I would want ( or am for instance ) and click next ( a hyperlink to a page with blank forms ) which is where I would like the info of the individual I selected ( and what was printed on the page ) in the forms pre filled. It allows a more user friendly approach then having to re type the data and also avoid miss spelling of company name or drivers license for example. I have put my code up many times but here it is again.this is the code for the finding and printing of the search results. no radio button yet, as i am trying to figure that out.
<div id="results" style="width:750px;height:225px; text-align: center">
<?php
$host = "localhost"; //server
$db = ""; //database name
$user = ""; //databases user name
$pwd = ""; //password
mysql_connect($host, $user, $pwd) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$searchTerm = trim($_GET['searchname']);
// Check if $searchTerm is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
else
{
//$sql = "SELECT * FROM contractor WHERE CONCAT(FIRSTNAME,' ',LASTNAME,' ',
ARRIVAL) like '%$searchTerm%' GROUP BY FIRSTNAME";
$sql= "SELECT * FROM contractor WHERE CONCAT(FIRSTNAME,' ',LASTNAME,' ', ARRIVAL)
like '%$searchTerm%'";
$query = mysql_query($sql);
$count=mysql_num_rows($query);
//array_unique($count);
if(($count)>=1)
{
$output = "";
while($row = mysql_fetch_array($query))
{
$output .= "First Name: " . $row['FIRSTNAME'] . "<br />";
$output .= "Last Name: " . $row['LASTNAME'] . "<br />";
$output .= "Arrival: " . $row['ARRIVAL'] . "<br />";
}
echo $output;
//echo array_unique($output);
}
else
echo "There was no matching record for the name " . $searchTerm;
}
?>
</div>
this is the code for my form field which of course is a empty form that is just being submitted to the database after submission.
<form action="insert_submit.php" method="post" style="margin-left:35px;">
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" />
Last Name: <input type = "text" name="LASTNAME" id="LASTNAME"/>
Purpose: <input type = "text" name="PURPOSE" id="PURPOSE"/>
<br>
</br>
Company: <input type = "text" name="COMPANY" id="COMPANY" />
DL #: <input type = "text" name="DRIVERL" id="DRIVERL" />
<br>
</br>
<input type="radio" name="STATUS" id="STATUS" value="Checked In">Log In
<br></br>
<input type="radio" name="STATUS" id="STATUS" value="Checked Out">Log Out
<br></br>
<input type="submit" value="Submit" >
<br>
</br>
</form>
so your output line would be something like (clean up to suit your formatting)
$output .= '<a href="'.$_SERVER['PHP_SELF'].'?userid='.$row['UNIQUEID'].'">
First Name: '.$row['FIRSTNAME'].'<br />
Last Name: '.$row['LASTNAME'].'<br />
Arrival: '.$row['ARRIVAL'].</a><br />';
and you build into the page a condition that if you have the UNIQUEID coming in to look up and fill out the form such as
Company: <input type = "text" name="COMPANY" id="COMPANY" value="<?PHP echo $row['COMPANY']; ?>" />
edit to suit your database of course
sample code formatting
if(something){
do something
}else{
while(){
} # end while
} # easy to see this matches the if/else set of brackets
additional information for prepopulating
easiest would probably be on the same page. look for the userid coming into the page
if(!isset($_GET['userid'])){
# meaning we do not have a userid from a url that we generated above
# insert all your code to generate the links
}else{
# meaning we *have* a userid from a url that we generated above
# do your database query based on the userid such as
$sql='select * from mytable where userid=?';
$result=sqlsrv_query($db,$sql,array($_GET['userid']),array('Scrollable'=>'static'));
# or use mysqli, pdo or whatever... just watch for sql injection
$row=sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC));
# assuming we will not have more than one element returned
?>
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" value="<?PHP echo $row['firstName']; ?>"/>
and so forth... that should get you started
So basically what you need is in the first page a lis of identical names, or ideally one name, like:
content, content, content,
FirstName, LastName
FirstName, LastName
And than if you click on either of them, than the user is redirected to another page, containing all the details of the selected person, in a form. If I am getting you right.
I would not use checkbos on the first page, simply make the person's name a hyperlink like:
http://domain.com/userdetails?userid=666
So you pass on the user id to the second page. The php code on the second page can thank draw user details from the database and populate the form.
For that purpose you can either generate the form in an echo line-by-line manner, or use DomDocument tofind and fill the relevant value fields.
Second page form generation:
you select the row with the id, than fetch it into an array, named $array.
$array = mysql_fetch_array($query); //this query selected the row for the user with the id
echo '<form method="POST">'."\n";
echo '<input name="firstname" type="text" value="'.$array['firstname'].'">'."\n";
echo '<input name="lastname" type="text" value="'.$array['lastname'].'">'."\n";
echo '</form>';
I hope you get the idea now.
this is going to be my second post, I am very confused and need some assistance. first I will explain what I would want it to do and then post my code. I am first search a database using first name, last name, or a date to print the results.
I first need help in only printing a repeating name once. It is printing every possible case and I would like it to match the fields (except arrival, reason, or even company (these can change ) )
Next once the results print on my search page, I would like radio buttons to be next to each set of data. for instance, if there are two people with the last name brown, i would like the first name, last name, and DL# to have ONE radio button next to it. resulting in two total buttons. this is where i am having trouble. once the selected radio is pressed and the next button (hyperlink) is pressed, i will then direct the user to a set of forms where the selected data ( firstname, lastname, dl#, company) is pre filled in the spots.
so all in all i need help limiting the prints of repeating individuals, and also i need assistance with saving data after a search function using a radio button to then print and pre populate the forms on the following page. my code currently for the search function is:
<h3>Search By First Name, Last Name, or Arrival Date (20XX-MO-DY)</h3>
<form action="searchpage.php" method="GET">
<label>Search:
<input type="text" name="searchname" id="searchname" />
</label>
<input type="submit" value="Search" />
</form>
My searchpage is :
<?php
$host = "localhost"; //server
$db = "practice_table"; //database name
$user = "root"; //databases user name
$pwd = ""; //password
mysql_connect($host, $user, $pwd) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$searchTerm = trim($_GET['searchname']);
// Check if $searchTerm is empty
if ($searchTerm == "") {
echo "Enter name you are searching for.";
exit();
} else {
$sql = "SELECT * FROM contractor WHERE CONCAT(FIRSTNAME,' ',LASTNAME,' ', ARRIVAL) like
'%$searchTerm%'";
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if (($count) >= 1) {
$output = "";
while ($row = mysql_fetch_array($query)) {
$output .= "First Name: " . $row['FIRSTNAME'] . "<br />";
$output .= "Last Name: " . $row['LASTNAME'] . "<br />";
$output .= "Arrival: " . $row['ARRIVAL'] . "<br />";
}
echo $output;
} else {
echo "There was no matching record for the name " . $searchTerm;
}
}
?>
this code above is where all the results print and I would like to regulate the repeating cases, also where the radio button per individual should be.
finally this is the form page the hyperlink goes to where I would like to pre poppulate the code.
Welcome Back Contractor. Please fill the following information in again below for today's visit.
First Name:
<input type="text" name="FIRSTNAME" id="FIRSTNAME" value="<?php echo $_POST['radio']; ?>"/>
Last Name:
<input type="text" name="LASTNAME" id="LASTNAME" value="<?php echo $_POST['radio']; ?>"/>
<form action="insert_submit.php" method="post" style="margin-left:35px;">
First Name: <input type="text" name="FIRSTNAME" id="FIRSTNAME"/>
Last Name: <input type="text" name="LASTNAME" id="LASTNAME"/>
Purpose: <input type="text" name="PURPOSE" id="PURPOSE"/>
<br />
Company:
<input type="text" name="COMPANY" id="COMPANY"/>
DL #:
<input type="text" name="DRIVERL" id="DRIVERL"/>
<input type="radio" name="STATUS" id="STATUS" value="CHECKED IN">Log In
<br/>
<input type="radio" name="STATUS" id="STATUS" value="CHECKED OUT">Log Out
<br/>
<input type="submit" value="Submit">
<br/>
</form>
I appreciate any help. i hope I was just complicating things and can easily solve my last few issues. thank!
To remove duplicates from your results add DISTINCT or a GROUP BY clause to your SQL statment, eg:
SELECT DISTINCT FIRSTNAME, LASTNAME, PURPOSE FROM ...
or
SELECT DISTINCT FIRSTNAME, LASTNAME, PURPOSE
FROM ...
WHERE ...
GROUP BY DISTINCT FIRSTNAME, LASTNAME, PURPOSE
To add an arrival date while still only printing one row per person add MAX(ARRIVAL) to the SELECT clause:
SELECT DISTINCT FIRSTNAME, LASTNAME, PURPOSE, MAX(ARRIVAL)
FROM ...
WHERE ...
GROUP BY DISTINCT FIRSTNAME, LASTNAME, PURPOSE
Iam writing a program where i have a form with two fields and a 'PLUS BUTTON' upon clicking it two more fields will appear. By clicking PLUS Button again two more fields will generate and it continues as many times we click the PLUS BUTTON. Here's my program.
<form action="project_values/action_nowproject.php" method="post"enctype="multipart/form-data"><div id="item"><input type="text" name="add_qty" id="add_vender" class="ttexbox" required="required"><input type="text" name="add_name" class="ttexbox"><input onClick="addRowv(this.form);" type="button"style="cursor:pointer" class="addround" /></div></form>
in Javascript
<script type="text/javascript"> var rowNum = 0; function addRowv(frm) { rowNum ++;
var row = '<p id="rowNum'+rowNum+'"><span class="ftext">Item quantity:</span> <input type="text" name="m_name[]" value="'+frm.add_qty.value+'"><br> <span class="ftext">Item name: </span><input type="text" name="mi_name[]" value="'+frm.add_name.value+'"><br><br /> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRowsv').append(row); frm.add_qty.value = ''; frm.add_name.value = ''; } function removeRow(rnum) { jQuery('#rowNum'+rnum).remove(); } </script>
Now I have to fetch the values of extra fields appeared by clicking the plus button and send them to database.
How to fetch the values multiple array's genereated? heres my sql query insert statement.
$mp = "INSERT INTO pm_manr(name,item_nm)VALUES ('$add_qty','$item_name')";
$updata = mysql_query($mp);
How to get values in $add_qty,$item_name ? Some one pls help me.
Lets asume you have something like this:
line 1 <input name="foo[]" /> <input name="bar[]" />
line 2 <input name="foo[]" /> <input name="bar[]" />
line Y <input name="foo[]" /> <input name="bar[]" />
line Z <input name="foo[]" /> <input name="bar[]" />
You can loop trough them both by using the key from a foreach on the other values:
foreach($_POST['foo'] as $key =>$value){
echo $_POST['foo'][$key]; // the same as echo $value
echo $_POST['bar'][$key]; // the corresponding value of $_POST['bar']
// This is where you add your query
}
Use array_combine() which creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.
Try this:
$arr = array_combine($_POST['m_name'],$_POST['mi_name']); // combines both arrays
foreach($arr as $key => $value){
$mp = "INSERT INTO pm_manr(name,item_nm)VALUES ('$key','$value')";
$updata = mysql_query($mp);
}
I receive two arrays from a form. In the .php file, I need to insert the values of each array into a column of the table.
- use the foreach loop to access the elements of one array and complete the insertion for only one column. When I do the same thing for the next array, I find that the corresponding first column elements are null in each row while for the first array, the corresponding second column elements are null. Is there anyway to avoid this and insert the array elements one after the other?
- I understand that foreach cannot be applied to two arrays so is there any other way I can access both the arrays simultaneously for insertion into a table?
Thanks.
You can use a foreach loop:
foreach($_POST['someField_1'] as $key => $value)
{
$fieldOne = $value;
$fieldTwo = $_POST['someField_2'][$key];
}
Obviously change the _POST variables to whatever you've named the fields.
As long as your field names are named something like: name="someField_1[]" and name="someField_2[]" You can use the foreach loop in this way.
EDIT
Take this HTML for your input form:
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
So that form allows you to enter forenames and surnames for up to 3 people. Each field has the exact same name: forename[] and surname[]
To retrieve each of the values, you would use this PHP:
foreach($_POST['forename'] as $key => $forename)
{
echo 'Forename: ' . $forename;
echo ' ';
echo 'Surname: ' . $_POST['surname'][$key] . '<br />';
}
This works because when you submit a field like forename[], with square brackets at the end, PHP will automatically convert this to an array. $key is a number which starts at 0, and goes on for however many fields there are.
PHP uses the $key to retrieve the correct fields. You could also write your HTML like this:
Forename: <input type="text" name="forename[0]"> Surname: <input type="text" name="surname[0]">
Forename: <input type="text" name="forename[1]"> Surname: <input type="text" name="surname[1]">
Forename: <input type="text" name="forename[2]"> Surname: <input type="text" name="surname[2]">
You see I've put a number between the square brackets? PHP will detect this and loop through the arrays.
You could even use a for loop:
for($i = 0; $i<count($_POST['forename']); $i++)
{
echo 'Forename: ' . $_POST['forename'][$i];
echo 'Surname: ' . $_POST['surname'][$i];
}