I want search names using my search module with ignoring white spaces .
Ex: if i want to search a name like "A B Zilva"
i want to disply the results on dropdown even if i type the name like "AB Zilva".
currently search without space is not working
$db = JFactory::getDbo();
$searchp=$_GET["term"];
$searchp = str_replace(' ','%%', trim($searchp));
//$searchp= preg_split('/ /', $searchp);
$query = $db -> getQuery(true);
$query="SELECT * FROM content where title like '%".$searchp."%'AND categories_id=82 order by title ASC ";
$db -> setQuery($query);
// Load the results as a list of associated arrays.
$results = $db -> loadAssocList();
$json=array();
foreach ($results as $json_result) {
$json[] = array('value' => $json_result["title"], 'label' => $json_result["title"]);
}
Please advice .
update :
jQuery.extend( jQuery.ui.autocomplete.prototype, {
_renderItem: function( ul, item ) {
var term = this.element.val(),
regex = new RegExp( '(' + term + ')', 'gi' );
html = item.label.replace( regex , "<b>$&</b>" );
return jQuery( "<li></li>" )
.data( "item.autocomplete", item )
.append( jQuery("<a></a>").html(html) )
.appendTo( ul );
}
});
The problem with your code is that when you replace space with %%, you get a search like:
WHERE title like '%AB%%Zilva%'
but this won't match when the title is A B Zilva. You need to remove spaces from both the search string and the column in the database. Do it like this:
$searchp = str_replace(' ', '', $searchp);
and then change the SQL to:
WHERE REPLACE(title, ' ', '') LIKE '%$searchp%'
For the Javascript highlighting, I think you need to do this:
var term = this.element.val().replace(/ /g, '').replace(/.(?=.)/g, '$& *'),
This will create a regular expression that allows for spaces between any of the characters in the search string.
Related
I am using a class to generate a string name profile to slug and next use an SQL command to tell me whats the unique value to use in insert command, the problem is the command isn't working properly, sometimes it is possible to return a value which already exist...
Thats the class I am using to generate the slug: (composer require channaveer/slug)
And this the example code:
use Channaveer\Slug\Slug;
$string = "john doe";
$slug = Slug::create($string);
$profile_count_stmt = $pdo->prepare("
SELECT
COUNT(`id`) slug_count
FROM
`advogados_e_escritorios`
WHERE
`slug_perfil` LIKE :slug
");
$profile_count_stmt->execute([
":slug" => "%".$slug."%"
]);
$profile_count = $profile_count_stmt->fetchObject();
if ($profile_count && $profile_count->slug_count > 0) {
$profile_increment = $profile_count->slug_count + 1;
$slug = $slug . '-' . $profile_increment;
}
echo 'Your unique slug: '. $slug;
// Your unique slug: john-doe-5
This is the content of the table when the script run:
Do you know how can I improve the select command to prevent it to return existing slugs from DB?
Ok finally found a solution... Heres the code for who wants to generate unique profile slugs using PHP - PDO and MySQL
$string = "John Doe";
$string = mb_strtolower(preg_replace('/\s+/', '-', $string));
$slug = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
$pdo = Conectar();
$sql = "
SELECT slug_perfil
FROM advogados_e_escritorios
WHERE slug_perfil
LIKE '$slug%'
";
$statement = $pdo->prepare($sql);
if($statement->execute())
{
$total_row = $statement->rowCount();
if($total_row > 0)
{
$result = $statement->fetchAll();
foreach($result as $row)
{
$data[] = $row['slug_perfil'];
}
if(in_array($slug, $data))
{
$count = 0;
while( in_array( ($slug . '-' . ++$count ), $data) );
$slug = $slug . '-' . $count;
}
}
}
echo $slug;
//john-doe-1
You should check if the slug exists or not from your database. If it already exists then you can append some random string like the following
$slug = Slug::create($string);
$slugExists = "DB query to check if the slug exists in your database then you may return the count of rows";
//If the count of rows is more than 0, then add some random string
if($slugExists) {
/** NOTE: you can use primary key - id to append after the slug, but that has to be done after you create the user record. This will help you to achieve the concurrency problem as #YourCommenSense was stating. */
$slug = $slug.time(); //time() function will return time in number of seconds
}
//DB query to insert into database
I have followed the same for my blog articles (StackCoder) too. Even LinkedIn follows the same fashion.
Following is screenshot from LinkedIn URL
I have column in table of database with value: PL TOFLEX NEGRO/PRETO
I search in my website: TOFLEX PRETO
I need output: PL TOFLEX NEGRO/PRETO
Can someone give me correct query to do this?
I try:
public function searchMaterial($nome)
{
$json = [];
$this->load->database();
if(!empty($this->input->get("q"))){
$this->db->like('nomeMaterial', $nome, 'both');
$query = $this->db->select('idMaterial as id,nomeMaterial as text')
->limit(50)
->get("material");
$json = $query->result();
}
echo json_encode($json);
}
but doesn't work.
You have to split your terms before querying your database.
I assume nomeMaterial is the name of your column.
Try this if you want your column contains BOTH terms :
$search = 'TOFLEX PRETO';
$terms = explode(' ',$search); //will return an array with two strings
foreach($terms as $term){
$this->db->like('nomeMaterial', $term);
}
Or try this if you want your columns contains at least one of the terms :
$search = 'TOFLEX PRETO';
$terms = explode(' ',$search); //will return an array with two strings
foreach($terms as $term){
$this->db->or_like('nomeMaterial', $term);
}
CakePHP Version 3.5.5
What I've got:
I've got search functionality on my index pages which allows a user to search by column and value. The user selects the column from a select list and adds text into an input. I pick up this data with the following which works:
$query = $Users->find()
->where(function ($exp, $q) {
return $exp->like($this->request->getData('column'), $this->request->getData('input') . '%');
})
->andWhere([
'status' => $filter,
'cid_1' => $c1
]);
When using the debugKit it reveals the sql as: (Extract only to help explain)
FROM users Users WHERE (role LIKE :c0 AND status = :c1 AND cid_1 = :c2)',
What I'm trying to do is the following:
$testColumn = $this->request->getData('column');
$testInput = $this->request->getData('input');
$query = $Users->find()
->where(function ($exp, $q) {
return $exp->like($testColumn, $testInput . '%');
})
->andWhere([
'status' => $filter,
'cid_1' => $c1
]);
The $testColumn variable is undefined.
Whe using the debugKit it reveals the sql as: (Extract only to help explain)
FROM users Users WHERE ( LIKE :c0 AND status = :c1 AND cid_1 = :c2)',
IE: The role is not being declared before the LIKE.
What I've tried:
1. return $exp->like("$testColumn", "$testInput" . '%');
Result: Exactly the same - Variable is still undefined.
DebugKit: FROM users Users WHERE ( LIKE :c0 AND status = :c1 AND cid_1 = :c2)',
2. return $exp->like("'$testColumn'", "'$testInput'" . '%');
Result: It added '' before LIKE as can be seen below but I still can't get that variable defined.
DebugKit: FROM users Users WHERE ('' LIKE :c0 AND status = :c1 AND cid_1 = :c2)',
My Question:
Is there a way to use a dynamic value to select the search data.
Update:
Is it that I can't assign getData to a variable in this context.
You can't do this:
$testColumn = $this->request->getData('column');
return $exp->like($testColumn, $testInput . '%');
But you can do this:
$testColumn = $this->request->getData('column');
echo 'testColumn is ' . $testColumn . '<br />';
if ($testColumn === 'role') {
echo 'in column passed ' . '<br />';
}
else {
echo 'in column failed ' . '<br />';
}
Thanks. Z.
////////////////////////////////////////////////////////////////////////////////
Alimon Karim as requested.
I'm using post and my url is: https://localhost/app/users/search
Thanks Alimon, it works.
Replace
->where(function ($exp, $q) {
with
->where(function ($exp, $q) use ($testColumn,$testInput) {
I know this might have been asked before but I am trying to protect my search field and drop downs from MySQL injection and am having trouble integrating mysql_real_escape_string into my PHP. I am currently filtering my search results by keywords in 2 drop downs or by a freeform input where the user types in a reference. I've commented below where I am trying to add the escape string but it is breaking my search function. Can anyone advise me on what to do? Thanks for any help
<?php
// SEARCH FROM TEXT INPUT
mysql_select_db($database_connectInfo, $connectInfo);
if (isset($_POST['searchByRef']))
{
$searchword = $_POST['searchByRef'];
//ESCAPE STRING HERE
$searchword = mysql_real_escape_string($connectInfo, $searchword);
$query_dbname = "SELECT * FROM dbname WHERE `ref` LIKE '%".$searchword."%'";
}
else
// SEARCH FROM DROPDOWN MENUS
if (isset($_REQUEST['submit']))
{
$drop1 = $_POST['search1'];
$drop2 = $_POST['search2'];
//ESCAPE STRING HERE
$drop1 = mysql_real_escape_string($connectInfo, $drop1);
$drop2 = mysql_real_escape_string($connectInfo, $drop2);
$query_dbname = 'SELECT * FROM dbname WHERE 1=1' . ($drop1 ? ' AND `colour` LIKE "%' . $drop1 . '%"' : '') . ($drop2 ? ' AND `style` LIKE "%' . $drop2 . '%"' : ' ORDER BY id DESC');
}
else
{
$query_dbname = "SELECT * FROM dbname ORDER BY ref DESC";
}
$dbname = mysql_query($query_dbname, $connectInfo) or die(mysql_error());
$row_dbname = mysql_fetch_assoc($dbname);
$totalRows_all = mysql_num_rows($dbname);
?>
Don't use mysql_escape_string.. instead use mysqli or PDO with prepared statements.
http://www.php.net/manual/en/book.pdo.php
For more info on WHY see this:
Why mysql_real_escape_string() did not prevent hack?
I've a MySql table where I put some value: id, name of opportunity, category of opportunity, commission etc etc. Now I need to create (automatically) a shortcode that call these value win an array, so for example if i write [opportunity id="1"] wordpress display banner of the opportunity in the database that have id=1.
This is my code
function opportunity_banner_shortcode($atts) {
extract(shortcode_atts(array("id" => ''), $atts));
global $table_prefix, $wpdb, $user_level;
$table_name = $table_prefix . "opportunities";
$finds = $wpdb->get_results("SELECT * FROM {$table_name}", ARRAY_A);
if(sizeof($finds)){
foreach($finds as $find)
return "<a href='" . $find["opp_link"].
"'><img src='" . $find["opp_banner_preview"]."'></a> ";
}
}
add_shortcode('opportunity', 'opportunity_banner_shortcode');
Thanks to all
Maybe the query should be
$finds = $wpdb->get_results("SELECT * FROM {$table_name} WHERE id={$id}",
ARRAY_A);