i was using a input tag for entering the address in the form.
Input form code :
<input type="text" name="address">
and the search query for searching the addresses, worked without any problem
Search form code:
<input type="hidden" name="category_address" value="address"/>
<select name='criteria_address'">
<option selected="selected"> </option>
<?php
$order = "SELECT DISTINCT address FROM lh_clients ORDER BY clientname" or die (mysql_error());
$result = mysql_query($order);
while($data = mysql_fetch_array($result))
{
echo ("<option> $data[address] </option>");
}
?>
Search Result Display code :
if(isset($_POST['criteria_address']))
{
$category_address = $_POST['category_address'];
$criteria_address = $_POST['criteria_address'];
$query = "SELECT * FROM lh_clients WHERE $category_address LIKE '%".$criteria_address."%'";
echo "<tr><td colspan='8'>$num_rows Results Found</td></tr>";
while($data = mysql_fetch_array($result))
{
echo("<tr>
<td>$data[clientname]</td>
<td>$data[clienttype]</td>
<td>$data[address]</td>
<td>$data[contacts]</td>
<td>$data[sensitivity]</td>
<td>$data[acountmanager]</td>
<td>$data[responsibleexecutive]</td>
</tr>");
}
But now when i replacing the input tag and using tag instead of it
textarea code :
<textarea name="address"></textarea>
The Search code doesn't work. The tag works fine, it pop up data from the address column but doesn't providing any search result according to that address.
By the way, when i give input something with out entering newline it works.
If any one can understand my problem please reply.
Thanks a lot in advance.
if you put a newline in your searchword, you only gettings rows with that have that newline stored in the database.
1.
if an adress is stored in the database like
"street 1, 123 45 town",
and you try to search it by writing
"street 1
123 45 town"
they not going to match, you may want to replace newlines with % to allow other seperators.
2.
if you adress is stored in the database like street 1, and your search for
"street 1
"
then you may want to use trim() on the searchword to get rid of extra newlines
3.
to avoid carage return problem, you can use REPLACE
SELECT *
FROM lh_clients
WHERE
REPLACE(adress, '\r', '') LIKE CONCAT('%', REPLACE(:adress, '\r', ''), '%');
where :adress should be bind/replaced with the input variable
Related
The below code is returning rows of checkboxes (the right number per the mySQL table) and with no error. The problem is that it is not grabbing the column values ((as per: ".$row['Zone'].": ".$row['RowNumber']. ))to place beside said checkboxes.
<?php
include'connect.php'
?>
<form method="post" action="chooseDate.php">
<?php
$sql = "
SELECT s.RowNumber, s.Zone,
FROM Seat AS s
LEFT JOIN Booking AS b, ON s.RowNumber = b.RowNumber,
AND b.PerfDate = ?,
AND b.PerfTime = ?,
WHERE b.RowNumber IS NULL,
GROUP BY s.RowNumber
";
$date = "$_POST[Date]";
$time = "$_POST[Time]";
$handle = $conn->prepare($sql);
$handle->execute(array($date, $time));
$res = $handle->fetchAll();
foreach($res as $row) {
echo "<input name='Seat' type='checkbox' value='".$row['Zone'].":
".$row['RowNumber']."'><br>";
}
?>
<input class="mybutton" type="submit" value="Choose Seat"/>
</form>
I have run queries using identical methods and they display the results as expected. The only difference here is that the query is LEFT JOIN. The results display in shell. This is a sample of the results and the expected output of one checkbox.
|**RowNumber**|**Zone**|
|-------------|--------|
|Z20 |box 4 |
Where am I going wrong? Thanks in advance.
Have you looked at the HTML output? You put the text inside the input element. The closing > is after the text.
You could fix that simply by just moving the > to the front, but I think it's bettter to generate a <label> element after the checkbox or surrounding the checkbox. If you give the checkbox an id, and the label a for attribute pointing to that id, the text is clickable too, which make an awesome UX. :)
So I suggest changing the for loop like this:
$idcounter = 0;
foreach($res as $row) {
$id = 'Seat' . ($idcounter++);
echo "<input name='Seat' type='checkbox' id='$id'><label for='$id'>".$row['Zone'].":".$row['RowNumber']."</label><br>";
}
Note that I removed the value attribute. I'm not sure if you would need it, but maybe you need both: the value and the label. If so you can put back that attribute like you had before, as long as you make sure to close the input element before opening the label.
How do I modify my $select function to allow searching with a database when the customer types in the search text and clicks "Search"? I'd also like to be able to type in the form field, and PHP automatically updates the page with the form data dynamically and to be able to define the field to search upon in the database!
This is letting me view my customers table:
$select = $db->query("SELECT * FROM customers ORDER BY id DESC");
<?php
if (!$select->num_rows) {
echo '<p>', 'No records', '</p>';
}else{
?>
<table border="1" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<?php
while ($row = $select->fetch_object()) {
?>
<tr>
<td><?php echo $row->FName;?></td>
<td><?php echo $row->LName;?></td>
First of all, you might try putting your opening <?php before rather than after the first line of code... :-)
Then you simply modify your code to get the values from your HTML form - I will assume that your search term is named q kind of like this:
Search: <input type="text" name="q" /> <input type="submit" name="search" />
Then your PHP script doing the searching will change the query to something like this:
$select = $db->query("SELECT * FROM customers WHERE FName LIKE '%$_REQUEST[q]%' OR LName LIKE '%$_REQUEST[q]%' ORDER BY id DESC");
If you are entered "Sam" that will end up with a query that looks like this:
$select = $db->query("SELECT * FROM customers WHERE FName LIKE '%Sam%' OR LName LIKE '%Sam%' ORDER BY id DESC");
Do note that I am showing you the simplest version by simply constructing the query. In fact you should NEVER do this with user-supplied data. Instead, you should prepare and then bind and then execute your statement. This is not just filler at the end of the answer - it's really important. But while you are testing you may want to see how it works just be forming a string as above.
To answer your "BONUS POINTS" - you can update the current page by simply including your search form on the same page as the PHP script which displays the results. Then you only process your PHP code if the submit button has been pressed. Your whole script (in a very simple form) might look like this:
Search: <input type="text" name="q" /> <input type="submit" name="search" />
<?php
if (isset($_REQUEST['search'])) {
# do your query
# loop through the results, printing them off in appropriate HTML
}
To answer your "BONUS BONUS" points, you would probably set up a pull-down ("select" in HTML) where the values of the options were the actual field names and the display was a human-readable form of that. If your select had the name "field_name" then you would modify your query like this:
$select = $db->query("SELECT * FROM customers WHERE $_REQUEST[field_name] LIKE '%$_REQUEST[q]%' ORDER BY id DESC");
Do note that you cannot prepare/bind to a column name, so you will just have to be very careful to validate that field very exactly (probably checking that it exists in a list of acceptable values).
I have not found a solution to prevent this. I am using PHP to self populate my option fields so I don't have to manually add them all in. I have four select fields and three out of the four work perfect but the fourth one.
On the company field it will populate one blank field and then it populates the rest just fine. I have a solution for this that will remove this space but I was informed that it is not the best practice. Anyone think they know a better and more correct way of achieving this?
PHP Select Field
<label for="company">Company</label><br />
<select id="company" name="users" onChange="showUser(this.value)">
<?php include 'datalogin.php'; // Populates the Company select field
$result = mysqli_query($con, "SELECT DISTINCT Company FROM `roster` ORDER BY Company ASC;");
echo '<option value="">' . 'Select a Company' .'</option>';
while ($row = mysqli_fetch_array($result)) {
if ($row['Company'] == NULL) { //The empty if is to remove the blank space in the select field
}
else {
echo '<option value="'.urlencode($row['Company']).'">'.htmlspecialchars($row['Company'],ENT_QUOTES).'</option>';
}
}
?>
</select>
Ideally I was told you should use "!" to tell the if statement to echo if it is not null but it still produces the blank space:
if ($row['Company'] !== NULL) {
echo '<option value="'.urlencode($row['Company']).'">'.htmlspecialchars($row['Company'],ENT_QUOTES).'</option>';
}
This is what I mean by the blank space:
(Pretend it is a select field)
[Select a field]
[ ]
[Cleveland ]
[Columbus ]
[Toldeo ]
Live Agent Search Site
SELECT DISTINCT Company
FROM `roster`
WHERE LENGTH(Company) > 0
ORDER BY Company ASC;
I really would like some help on this as I'm pulling hair out!!!
I have two fields, one being an input box & the other being a drop down list which search the database and display the results, however I cannot seem to figure it out...here is what I have so far...
This is the actual search form:
<form id="myform" name="myform" action="<?php echo $_SERVER['PHP_SELF']?>" method="get"><br />
<div class="T1"><br /><p></div> <input name="term" type="text" value="<? php echo $_GET['searched']; ?>" size="10" maxlength="4" placeholder="e.g. BS1"/>
<select>
<option value="">I feel like...</option>
<option value="">Anything</option>
<option value="Indian">Indian</option>
<option value="Chinese">Chinese</option>
<option value="Thai">Thai</option>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
And this is the PHP code:
<?php
if (isset($_GET['submit'])){
mysql_connect ("host", "user","password") or die (mysql_error());
mysql_select_db ("database");
$term = $_GET['term'];
$term = $_GET['option value'];
}
else
$sql = mysql_query("select pagetitle from Restaurant where extra like '%$term%' and showing like '1'");
$sql = mysql_query("select cuisine from Restaurant where cuisine like 'option value' and showing like '1'");
echo Restaurants in $term and Cuisine $option value:";
}
while ($row = #mysql_fetch_array($sql)){
echo ''.$row['pagetitle'];
echo '<br/>';
}
}
?>
The database has a table called Restaurant with two coloumns, one called 'Extra' which contains the postcode & the other called 'Cuisine' which containts the cuisine.
I would like it to return a list of restaurants that match both 'Extra' and 'Cuisine'
Any help will be greatly appretiated.
Echoing $_SERVER['PHP_SELF'] or $_GET['searched'] anywhere in your script (even in the form action) will open your site up to XSS attacks. Do not do this unless you sanitize them first.
For all new projects, it is recommended to use prepared statements for mysql queries. You can do this with either mysqli or PDO. Your code is just asking for SQL injection by the looks of what you are trying to do.
You are missing a bracket in your code and you have some extra ones at the end. Also after echo you're missing a quotation mark. I'm not sure what's going on there. Try to get those fixed.
What is with the # before mysql_fetch_array() ? There are really very few cases where # should ever be used in PHP. It is usually an indicator that there is some sort of error somewhere in your code that should be fixed instead of suppressed.
Your needs a name attribute if you want to be able to use it in PHP.
In your SQL query, you should not be using LIKE when you should be using equals. Also, you should not quote integers.
Why are you echoing an empty string like echo ''.$somevar; ? Just echo the variable.
I'm not sure what "showing" is for but I assume is a record that can be displayed. The first thing to do is update your query:
$sql = mysql_query("select pagetitle, cuisine from Restaurant where (extra like '%$term%') and (showing like '1') and (cuisine like 'option value')");
You also need to check if the user did not enter an option or selected 'anything' in which case the query needs to be changed a little:
$sql = mysql_query("select pagetitle, cuisine from Restaurant where (extra like '%$term%') and (showing like '1') and (cuisine like 'option value' or 'option value' = '')");
Can any one please help me? I am new to php, currently I am trying to use $_POST['item'] to obtain a string (consists of many words) from a dropdown box and then process it. However, when I use $_POST['item'], only first word is returned, the rest of words are missing.
I have a dropdown box, something like:
echo "<form action='process_form.php' method='post'>";
echo "Select an item<br />";
echo "<select name='item' id='item'>";
...
...
...
each item in the dropdown box is a string that has product names like:
dressmaker mannequin size 12
torso mannequin in white color
...
User will then select an item from the dropdown box. When I used $_POST['item'] to obtain this string, I get the first word "dressmaker", all the rests were missing.
How do I get the whole string?
Many thanks in advance.
I am not sure exactly what you are doing but I would do something like this. For this example I assume that the values "dressmaker mannequin size 12" will correspond to the values of the columns in the database to which I will refer to as "colA, colB, colC, and colD", and in addition I assume you have an "ID" column in your database.
Here is the code I would use to generate the select drop-down list:
//$query is the variable storing the result of the mysql_query();
//assumption is that the result-set is non-empty
echo '<select name="item" id="item">\n'; //\n - new line character
//run through the loop to generate the items inside the list
while ($result = mysql_fetch_assoc($query)) {
//note the id - it will be used to find data in the
//database after the POST is complete
//couple of temp variables (not necessary but makes code cleaner)
$database_id = $result["ID"];
$colA = $result["colA"]; //ex:dressmaker
$colB = $result["colB"]; //ex:mannequin
$colC = $result["colC"]; //ex:size
$colD = $result["colD"]; //ex:12
//add option to the select drop-down
echo "<option value=\"$database_id\">$colA $colB $colC $colD</option>\n";
}
echo "</select>";
Now to retrieve the data from the POST. I am including the code Drewdin suggested.
//form was submitted already
//assumption is that the database connection is established
$item_id = mysql_real_escape_string(trim($_POST["item"]));
//Now get the info from the database for this id
//table is "table"
$string = "SELECT * FROM table WHERE ID = $item_id";
$query = mysql_query($string) or die("Could not complete the query: $string");
//assumption here is that the result set is non-empty
$result = mysql_fetch_assoc($query);
$colA = $result["colA"]; //ex:dressmaker
$colB = $result["colB"]; //ex:mannequin
$colC = $result["colC"]; //ex:size
$colD = $result["colD"]; //ex:12
//now you can use the values of colA-D to compute whatever you want
Hope this helps. Using database ids is nice for security plus it makes things more manageable.
Regarding using this blog. You can post comments to the answers people post. If you want however to add something to your question, you can edit your original question and just make sure its obvious what was added.
When the issue is resolved and if any answer helped and you liked it, you can pick it as the final answer by clicking the check mark next to it.
Best of luck
without seeing your select options i think this might help you
if (isset($_POST['submit'])) {
// Grab the output of the select list
$Select_Output = mysqli_real_escape_string( $dbc, trim($_POST['item']));
//What ever else you want to do here...
}
I also would use Miki725's post to make sure your select list is setup correctly
This is how the php gets the values from the HTML select item:
<select name="item" id="item">
<option value="this is option 1">option 1</option>
<option value="this is option 2">option 2</option>
<option value="this is option 4">option 3</option>
...
</select>
Basically you would do something like:
$var = $_POST['item'];
The $var will be the whatever was entered into the "value" of the option tag. So just make sure you have the proper values entered into the value fields.
Hope that helps.