I want my form input not to act upon an empty search.
I don't want it to even go to the results page and show an error message.
SO
how can I have it so nothing happens when clicking the submit/pressing enter OR pressing space bar then enter?
Can this be done with javascript?
HTML:
<form action="search.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
PHP:
<?php
$conn = mysql_connect("", "", "")
or die (mysql_error());
mysql_select_db("testable");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
$term = addcslashes($term,'%_');
$term = "%" . $_POST["term"] . "%";
if (!mysql_select_db("weezycouk_641290_db2")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
**if (isset($_POST['term']) && ($_POST['term'] !== '')) {
$term = $_POST['term'];
$safe_term = mysql_real_escape_string($term);
$sql = "SELECT FName,LName,Phone
FROM testable
WHERE FName LIKE '%". mysql_real_escape_string($term) ."%'";
$result = mysql_query($sql);
}**
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br><br><div class="data1">';
echo htmlentities($row["FName"]);
echo '</div><br><div class="data2">';
echo htmlentities($row["LName"]);
echo '</div><br><div class="data3">';
echo htmlentities($row["Phone"]);
echo '</div>';
}
mysql_free_result($result);
?>
Preventing the form from being submitted via JS is a quick fix, but you still need to handle the possibility that someone could STILL submit a blank search:
if (isset($_POST['term']) && ($_POST['term'] !== '')) {
$term = $_POST['term'];
$safe_term = mysql_real_escape_string($term);
$sql = "...."
blah blah blah
}
note the use of mysql_real_escape_string(). It is THE safe method for strings in mysql queries. addslashes is a hideously broken piece of crap and should NEVER be used for SQL injection prevention.
您可以在JS中检查长度并中止它是空白的
Yes, you can do that using javascript. Add a javascript function to handle on click event of submit button.
<input type="submit" name="submit" value="Submit" onclick="submitForm(event)" />
Inside that javascript function, check whether textbox is empty or not
function submitForm(event){
var val = document.getElementsByName('term')[0].value;
if (val==null || val.trim()==""){
//document.getElementsByTagName('form')[0].submit();
event.preventDefault();
return false;
}
else {
return true;
}
}
If empty, prevent default event and return false => prevent submission if not empty, return true => submit the form.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.