multiple values in a single submit - mysql

I've been searching google to find the code, but I can't find it. What I want to do is pretty simple, but I'm not php expert.
I want to insert multiple cities' name in a single press of submit button (if that is possible)
I have created a database with 2 tables: 'cities' and 'states'
and I have populated the states table
so I need two fields or boxes, one is for states, which is drop down 'select' box which already filled with states name, pulled from the database,
the other one is a cities field which a text type field (type="text").
I want to be able to type in multiple cities name, probably separated with ',' a comma,
and with a single press of submit button, all the value will be inserted into mysql cities table and go on to the next state.
I know I need to create some sort of loop, but I have no idea how to do it.

*index.php (html):
<html>
<body>
<form action="save.php" method="POST">
<input type="text" name ="cities" value="">
<input type="text" name ="state" value="">
<input type="submit">
</form>
</body>
*save.php:
<?php
/* -------include you db connection here ----*/
if(isset($_POST['çities']) && $_POST['çities'] !='' && isset($_POST['state']) && $_POST['state'] !=''){
$cities = explode (',', $_POST['çities']);
$n = count($cities);
for($i=0;$i<$n;$i++){
//Insert data
mysql_query("insert into `cities` (city,state) values ('".$cities[$i]."','".$_POST['state']."') or die(mysql_error());
}
}
?>

First you create the input in the form like this:
<input type="text" name="cities"/>
And you then type: New York, New Jersey, San Francisco, Denver, etc.
Then on the .php file that receives the data (i'd guess it's a $_POST variable), so $_POST['cities'] then, you split it and loop:
// split the values by comma
$_POST['cities'] = explode(',',$_POST['cities']);
// loop the values
foreach($_POST['cities'] as $city) {
// trim (delete white space at the end and start for safety)
$city = trim($city);
mysql_query("insert into `cities` ('city','state') values ('".$city.','".$_POST['state']."');
}
And done.

Related

HTML Form data from checkboxes within while loop

I have a really basic Date system on a site which displays the dates from the Database using a While loop, next to each date that is listed is a check box.
I would like the user to be able to select as many dates as they would like and click submit to remove these dates or edit these dates.
I am having trouble figuring out how I would get the data from multiple check-boxes using only one within the while loop which could be used multiple times?
Here is my current code:
<form action="" method="post">
<b>Current Dates:</b> <button type="submit" id="remove_dates" name="remove_dates" class="btn btn-danger btn-sm">Remove Selected</button>
<hr>
<div style="overflow-y: scroll;height:100px">
<?
$sqldate = "SELECT * FROM `foiu51r_calendar` ORDER BY date DESC";
$resultdate = $conn->query($sqldate);
if ($resultdate->num_rows > 0) {
// output data of each row
while($rowdate = $resultdate->fetch_assoc()) {
$date_id = $rowdate['date_id'];
$dates = $rowdate['date'];
?>
<input type="checkbox" id="date_id" name="date_id" value="<? echo $date_id; ?>"> <b><? echo date("d/m/Y", strtotime($dates)); ?></b><br>
<?
}
}
?>
</div>
</form>
if(isset($_POST['remove_dates'])){
$date_id = $_POST['date_id'];
}
I believe if you add this: [], to the name attribute, like this: <input type="checkbox" id="date_id" name="date_id[]" value="<? echo $date_id; ?>">. Then it will be handled as an array, which you can loop through with a foreach loop. and insert it into a database (or whatever you like).
Declare the name as an array, like as follows:
<input type="checkbox" id="date_id" name="date_id[]" value="<? echo $date_id; ?>">.
On submitting it will be handled as an array,
Then, you can loop the values of an array and for each element of an array use the id to remove the dates.

How do I search a table for multiple rows?

So this is my first question on stackoverflow and I've searched for day's but can't find the results I am looking for. I'm not looking for someone to write the code for me as I prefer to figure it out on my own, but I am looking for some assistance on finding how to do it.
My problem is I don't know how to word my search for what I'm looking for and this is what I want to do. I want to be able to search a MySQL database by using keywords such as "U10 Mustangs" where U10 would be data in a row called 'divisions' and Mustangs would be data in a row called 'club', I know I can use the OR statement like this
(`division` LIKE '%".$query."%') OR (`club` LIKE '%".$query."%')
but that only allows me to search by division or club not both. So basically I'm looking for a tutorial to show me how I can search by more than one keyword. I'm sure I'm wording this wrong and that's why I'm unable to find what I want.
I'm new to MySQL and PHP so please be understanding if this makes no sense!
*UPDATE*
here is my search code:
<body>
<?php include 'menu.php';?>
<br/><br/><br/>
<div id="searchcontainer" style="width: 55%; height: 132px;">
<fieldset style="width: 330px"><legend>Search Criteria</legend>
<form action="search.php" method="POST">
<td>Enter Search</td><td> <input type="text" name="query"/></td><td> <input type="submit" name="submit" id="table_button" value="Search" action="search.php"/></td>
<br />
</form>
</fieldset><br/>
<fieldset><legend>Search Results</legend>
<?php
include 'connect/local_connect.php';
$query = $_POST['query'];
// gets value sent over search form
// $min_length = 3;
// you can set minimum length of the query if you want
// if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM players
WHERE (`team_name` LIKE '%".$query."%' AND `division` LIKE '%".$query."%') OR (`last_name` LIKE '%".$query."%') OR (`division` LIKE '%".$query."%') ORDER by id ASC") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `first_name`, `any`
// players is the name of our table
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
}
else{ // if there is no matching rows do following
echo "<font color=red>No Results!</font>";
?><br/><br/>
<?php
}
// else{ // if query length is less than minimum
// echo "Minimum length is ".$min_length;
// }
// Define $color=1
$color="1";
echo '<table width="100%" border="1" align="center" cellpadding="0" cellspacing="0">';
echo '<th>ID</th><th>Club</th><th>Last Name</th><th>First Name</th><th>Division</th>';
while($rows = mysql_fetch_array($raw_results)){
echo "<tr bgcolor='#fff000'>
<td><center>".$rows['id']."</td></center><td><center>".$rows['club']."</center></td><td><center>".$rows['last_name']."</td></center><td><center>".$rows['first_name']."</center></td></td><td><center>".$rows['division']."</center></td></td></tr>";
}
echo '</table>';
mysql_close();
?>
</fieldset>
</div>
</body>
Are yu looking for concat
where CONCAT(`division`,' ',`club`) like '%".$query."%'
I will suggest to create a full text index on division and club like this FULLTEXT (club,division)
and search using query like this
SELECT * FROM db
WHERE MATCH (club,division)
AGAINST ('search');
'...but that only allows me to search by division or club not both...'
You can split your search string in words and then use a condition like this
SELECT *
FROM table1
WHERE (division LIKE '%U10%' AND club LIKE '%Mustang%')
OR (division LIKE '%Mustang%' AND club LIKE '%U10%')
Here is SQLFiddle demo

Is there an HTML 5 way of submitting fields with the same name but different identifiers?

I would like to submit multiple ROWS of field columns using an HTML form with the only difference being the corresponding server side identifier.
Pseudo:
ID(257) -> Name, Color, Price
ID(415) -> Name, Color, Price
I prefer NOT to:
Have each group as its own form and submit via JavaScript.
Concatenate the id and real name and unmerge on the server.
Thanks
You can use the same input name when attaching a [] to it, in PHP this will result in an array on submission:
<?php
print_r($_POST);
?>
<form method="post">
<input type="text" name="name[257]">
<input type="text" name="name[415]">
<input type="submit">
</form>
Result:
Array
(
[name] => Array
(
[257] => first field
[415] => second field
)
)
If you're using PHP as your server side language this is easy. Just name your fields with brackets which is array syntax in PHP:
Pseudo code:
name[1] = 'Name, Color, Price'
name[2] = 'Name, Color, Price'

fill a select html with mysql table rows

I'm writting a web app, I'm doing a html form with javascript to validate the data, I'm using a servlet to insert the data in a DB, but I need, when the form load, fill a select in the html form with the rows of a table in a MySql DB, I think I have to make a query in a ResultSet and then fill the select in the html form with this info, and then use the HttpServletResponse, but I have no idea how to make this
Use PHP to access the database and then put it into the form. Something like this:
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM table_name WHERE id='$id'");
$info = mysql_fetch_array($result))
$name = $info['name'];
$email = $info['email'];
$anotherField = $info['another_field'];
In this, the info array has all of the database data in it of the id. But of course you would change the values and stuff. Change table_name to the table name, and if you are going to do something in the URL like ?id=373384 or something, then this will work. (I would assume you are doing it this way.) But, if it isn't 'id', just change WHERE id='$id' to what is in the database to identify a line.
$info['name']; would be the "name" column in your table. But, you can change 'name' and stuff to what you have in your database.
Here is the form code to pre-fill it with data:
<form>
<input type="text" name="name" value="<?php echo $name ?>" />
<input type="text" name="name" value="<?php echo $email ?>" />
<!--etc...-->
<input type="submit" value="Submit" />
</form>
You would need to change a lot of this, but I'm sure you get the point of it. :)
Note: This is not a simple copy+paste script. You will have to do a lot of charing because I don't know what your table values are and stuff.
If you have any questions, please do ask.

textarea post into mysql not working

I have a textarea in a form that im trying to POST into a mysql database. However, when i insert the values, i get about 5 lines in the database. 4 of them have no information or minimal information and one of the lines is how i want it. How can i get rid of the other four lines? thanks.
EDIT: actually none of the lines have all the right info in the right spots and i have double checked the inset statement to make sure everything lines up.
the code:
<form method='POST' action="index.php">
<textarea id ='answerbox' autocomplete='off' cols="80" rows="5" name='answer'></textarea>
<input type='submit' value='submit'>
<?php
include 'connect.php';
$date=date("Y-m-d");
$time=time();
$answer=['answer'];
$user=$_SESSION['username'];
$id=$_GET['id'];
$put=mysql_query("INSERT INTO solutions VALUES ('','0','$date','$time','$user', '$answer')");
?>
Try:
<?php
if($_POST['answer'] != '')
{
include 'connect.php';
$date=date("Y-m-d");
$time=time();
$answer= $_POST['answer'];
$user=$_SESSION['username'];
$id=$_GET['id'];
$put=mysql_query("INSERT INTO solutions VALUES ('','0','$date','$time','$user', '$answer')");
}
?>
Your textarea is named as "answer" while its ID is "answerbox". You should be able to retrieve its value through $_POST['answer'];