Can anybody help, i'm trying to build a search using php that searches a text field in mysql.
I would like users to be able to enter a must have criteria, an or criteria and a not criteria, as well as being able to search for strings, so for example:
("This phrase" OR "That phrase") AND word
At present i'm using the example below to generate a search string:
$all = $row['and_search'] ;
$any = $row['or_search'] ;
$none = $row['not_search'];
if((!$all) || ($all == "")) { $all = ""; } else { $all = "$all"; }
if((!$any) || ($any == "")) { $any = ""; }
if((!$none) || ($none == "")) { $none = ""; } else { $none = "$none"; }
The above works brilliantly for only single words, but not searches such as the example above.
Any ideas how I can change achieve this?
Strip $all, $any and $none by whitespace into arrays. Than join them like
$newAll = '("' . join('" OR "', split(' ', $all)) . '")';
Related
First thing first, i'm new to php.
I'm trying to check if two variables are both empty, and if so merge them togheter to display only one result, but if one of them is not empty, than i have to display is value.
I currently have:
$customerNotesWC = "";
$DYSPrintableOrderNotes = "test note";
Here's the code i tried so far:
function displayCustomerOrderNotes($customerNotesWC,$DYSPrintableOrderNotes){
if ($customerNotesWC == "") {
$customerNotesWC = "(none)";
}
if ($DYSPrintableOrderNotes ==""){
$DYSPrintableOrderNotes = "(none)";
}
if ($DYSPrintableOrderNotes == "(none)" && $customerNotesWC == "(none)"){
$NotesToDisplay = "(none)";
}
else {
$NotesToDisplay = $customerNotesWC . "<br/>" . $DYSPrintableOrderNotes;
}
}
Unfortunately this doesn't work, as the results is the following:
(none)
Pre-sale order note
I know that there must be a better way to achieve this, and any suggestions will be really appreciated.
Thanks a lot
In order to get your desired functionality of only printing "(none)" when both values are blank, the simplest thing to do to fix your code is remove the code that's setting either value to "(none)" and change your main if-statement to check for "":
function displayCustomerOrderNotes($customerNotesWC,$DYSPrintableOrderNotes){
if ($DYSPrintableOrderNotes == "" && $customerNotesWC == ""){
$NotesToDisplay = "(none)";
}
else {
$NotesToDisplay = $customerNotesWC . "<br/>" . $DYSPrintableOrderNotes;
}
//shouldn't there be an echo $NotesToDisplay; or return $NotesToDisplay; ? or something?
}
I am trying to validate a form. I have my code as follows:
if(isset($_POST['data'])) {
$id = $this->input->post('id');
$action = $this->input->post('action');
$table = $this->input->post('table');
$data = $this->input->post('data');
$out = array();
$out['id'] = $id;
$out['error'] = '';
$out['fieldErrors'] = '';
$out['data'] = array();
$out['row'] = $data;
if($action=="create" && $data['display_name'] === '') {
if (empty($data['display_name']))
{
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}
}
}
Now this is working fine if there is no data inserted in the form, but if there is a space (whitespace) it doesn't work.
Any suggestion?
There are a few options to solve this:
Replace all whitespaces with nothing:
if (strlen(preg_replace('/\s/', '', $data['display_name'])) == 0)
{
Use trim to remove leading and trailing whitespaces:
if (strlen(trim($data['display_name'])) == 0)
{
Use str_replace() to get rid of invalid characters:
if (strlen(str_replace(array(' ', "\t"), array('', ''), $data['display_name'])) == 0)
{
Use regular expression to validate a name:
if (!preg_match('/^([A-Za-z0-9-_]+)$/', $data['display_name']))
{
=== checks for type as well along with value comparison, using trim function on variable containing values would give you expected results.
Try this. I have used the ctype_space function below to check for whitespaces
if($action=="create" && ($data['display_name'] === '' || ctype_space($data['display_name']))) {
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}
Just use trim function and check if its empty string:
if ($action=="create") {
if (trim($data['display_name']) == '') {
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}
}
I have a form that requires the user to only fill out at least 1 (out of four) fields. They can then submit and get a search result based off of their input.
The problem is, I can't get a character to set my variables to that will match any database value. Here is my code for some context;
if (isset($_POST['buildname']) ||
isset($_POST['weapon']) ||
isset($_POST['category']) ||
isset($_POST['id']))
{
if ($_POST['buildname'] == "")
{
$buildname = ".*";
}
if ($_POST['weapon'] == "")
{
$weapon = ".*";
}
if ($_POST['category'] == "")
{
$category = ".*";
}
if ($_POST['id'] == "")
{
$id = ".*";
}
$buildname = sanitizeString($_POST['buildname']);
$weapon = ($_POST['weapon']);
$category = ($_POST['category']);
$id = ($_POST['id']);
$searchstring = "SELECT buildname,weapon,category,id,author FROM weapons " .
"WHERE buildname='$buildname' AND weapon='$weapon' AND category='$category' AND id='$id'";
As you can see, the code looks at if one of the variables is set, then submits a form. If a variable isn't set, it assigns a character of ".*" (which I thought would match anything). It then queries the database to match any rows. I get no results unless I enter EVERY field with a correct entry.
Any ideas?
Thanks!
I would not use %, instead do something like this
if (isset($_POST['buildname']) || isset($_POST['weapon']) || isset($_POST['category']) || isset($_POST['id'])){
$sqlArray = array();
if(isset($_POST['buildname'])){
$sqlArray[] = "buildname='" . mysqli_real_escape_string($connection,$_POST['buildname']) . "'";
}
if(isset($_POST['weapon'])){
$sqlArray[] = "weapon='" . mysqli_real_escape_string($connection,$_POST['weapon']) . "'";
}
if(isset($_POST['category'])){
$sqlArray[] = "category='" . mysqli_real_escape_string($connection,$_POST['category']) . "'";
}
if(isset($_POST['id'])){
$sqlArray[] = "id='" . mysqli_real_escape_string($connection,$_POST['id']) . "'";
}
$searchstring = "SELECT buildname,weapon,category,id,author FROM weapons " .
"WHERE " . implode(' AND ', $sqlArray);
}
The wildcard character for MySQL is: %
The query you are executing, you "thought would match anything" wont. The statement uses no regular expressions.
WHERE buildname='$buildname' AND weapon='$weapon'
Which is essentially saying you need to have the following fields equal their string value of:
WHERE buildname='.*' AND weapon='.*'
I doubt you have any building with a name of .*.
It would be better to not filter on that field. basically remove the WHERE cause criteria if the variable is not defined.
You can do this dynamically, buliding the SQL statement only when you need to filter by that field.
if (isset($_POST['somevalue']) && ! empty($_POST['somevalue'])) {
$where .= 'column_name = ?';
$values[] = sanitizeString($_POST['somevalue]);
}
I've also used positional parameters which assumes you will be using the PDO or MySQLi libraries for querying.
No, you are using = operator, that only compares 2 values. In your case it will search for '.*' - and fail. If you want to ignore the fields, that were not filled, just don't put them into the query: no need for regexps. So, if the weapon and category are missing, your query should be like this
$searchstring = 'SELECT buildname,weapon,category,id,author FROM weapons WHERE ';
$fields = array('buildname', 'weapon', 'category', 'id');
$data = array();
foreach($fields as $value)
{
if (isset($_POST[$value]) && ($_POST[$value] != "") )
{
$data[] = sanitizeString($_POST[$value]);
}
}
$n = count($data);
if($n > 0)
{
$searchstring .= implode(' AND ', $data);
//do MySQL request and output result
}
Don't overcomplicate simple things. Also your code is vulnerable to SQL injection as some fields are not escaped.
You can do it like this:
$fields = array('buildname', 'weapon', 'category', 'id');
$sql = 'SELECT buildname, weapon, category, id, author FROM weapons';
$prefix = ' WHERE ';
foreach ($fields as $field) {
if (isset($_POST[$field]) && strlen($_POST[$field])>1) {
$sql .= $prefix . $field . '=\''
. sanitizeString($_POST[$field]) . '\'';
$prefix = ' AND ';
}
}
if ($prefix == ' AND ') {
// send the query
}
Notice: if you want to perform search with incomplete values, you could use LIKE instead of =, example:
$sql .= $prefix . $field . ' LIKE \'%' . sanitizeString($_POST[$field]) . '%\'';
But keep in mind that LIKE is slower than =
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression matching for entire string
On my form page, I am trying to make it only accept alphanumeric characters for my username and password and require that they be from 6 to 15 characters. When I type in invalid data, it will insert it into the database rather than throw the user error that I defined in my CheckAlNum function.
functions.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
Form.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
I've tried playing around with the nesting of the if-else statements of the checkAlNum function and also the regex (although I'm pretty sure the regex is right). Maybe I'm just missing something really silly?
function checkAlNum($whichField)
{
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST[$whichField])) {
return true;
}
else {
$message = '<p>Username and password can only be numbers or letters, 6-15 characters long</p>';
return user_error($message);
}
}
Without the ^ and $ anchors, your regex only checks whether there are alphanumerics anywhere in the field, not that the whole thing is alphanumeric. And changing + to {6,15} implements the length check here, so you can remove that extra check in your code.
I think the second if statement is incorrect. It should be like this:
if ( !( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 )) ) ) {
// ... do something
}
This is due to De Morgan Rule which states
A AND B = !( !A OR !B )
In any case, I would not do my checks this way, strucurally you will end up with too many nested if statements that are hard to maintain and make your code look unpretty. Try avoiding nested conditions in your code.
Barmar's answer is the best. But if you want to keep your if statement to check string length, you need to remove the count() as you are already checking the length using strlen().
if ( (!(strlen($whichField) >= 6)) OR (!(strlen($whichField) <= 15 ))) {
Good day guys,
I've made a sweet favorites function with php mysql and ajax, and its working great. Now I want to show 'favorite' when favorite = 0 and show 'unfavorite' when favorite = 1
if ($favorites == 0) {
$favorite = 'Favorite';
}
if ($favorites == 1) {
$unfavorite = 'unFavorite';
}
and echo it in the row as :
<div id="favorites">' .($favorite). ' ' .($unfavorite). '</div>
The problem is: when favorite = 0, both $favorite and $unfavorite are being shown. When favorite = 1 only $unfavorite is being shown correctly. Of course it should be $favorite OR $unfavorite. I assume the problem is clear and simple to you, please assist :)
Thanks in advance
It's easier to use just one variable:
$text = ''
if ($favorites == 0) {
$text = 'Favorite';
} else {
$text = 'unFavorite';
}
...
echo $text;
If you want to check $favorite, you are using the wrong variable in your control statement. Also, it is better coding practice to use elseif rather than if for that second if. One more thing: it's easier to manage one resulting variable.
$output = "";
if ($favorite == 0) {
$output = 'Favorite';
}
elseif ($favorite == 1) {
$output = 'unFavorite';
}
...
echo $output; // Or whatever you want to do with your output
Is $favorites an integer?
Anyway try using three equal signs (===) or else instead of the second if:
if ( $favorites === 0 )
{
// ...
}
else // or if ($favorites === 1)
{
// ...
}
You're making a toggle, so you only need one variable:
if(empty($favourites)){
$fav_toggle = 'Favorite';
} else {
$fav_toggle = 'unFavorite';
}
echo $fav_toggle;
Same code is working on me if I assigned $favorites = 0; or $favorites = 1;
You can also use if else
$favorites = 1;
if ($favorites == 0) {
$favorite = 'Favorite';
}
else if ($favorites == 1) {
$unfavorite = 'unFavorite';
}