Sorry for that "Let me google that for you"-Question, but I can't find an answer.
I want to delete specfic elements from columns in my database. So I search with the following code for them: (it works fine)
$sql = "SELECT list_id, list_domains
FROM list
WHERE list_domains REGEXP '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#'";
$result = $db->prepare( $sql );
$result->execute();
$result->bind_result( $list_id, $list_domains );
$result->store_result();
Now I want to delete / replace the found elements inside these columns. So I use the following code:
$sql = "UPDATE list
SET list_domains = REPLACE(list_domains, '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#', '')
WHERE list_domains REGEXP '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#'";
$result = $db->prepare( $sql );
$result->execute();
$result->store_result();
Does not work. I also tried
REPLACE(list_domains, REGEXP '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#', '')
or
REGEXP_REPLACE(list_domains, '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#', '')
but these lines only produce errors.
How does it work to delete / replace specfic regular expressions with MySQLi?
Thanks for every suggestion!
REPLACE() doesn't allow regular expression searching.
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
If you want to manipulate strings with regex, SELECT the rows, do the manipulation in your own code, then issue an UPDATE statement to update the value, specifying the final value.
Related
Let me explain fast what i want to do!
I want to show similar rows from my database by a PHP term.
I have a table called "games" and a column called "title" that titles are looks like "Rockstar - GTA V".
So i want to remove all words after dash and use new string as keyword to search in database.
My CMS use this code to show post title inside the loop:
$_smarty_tpl->tpl_vars['game']->value['title']
I just found a code to convert "Rockstar - GTA V" to "Rockstar":
<?php $mygame = strstr($_smarty_tpl->tpl_vars['game']->value['title'], '-', true); echo($mygame); ?>
When i put this code in my "Single template file", it work fine and trim the title as i want and it work good in every game's single page.
So i want to make a section in single page to display all games made by that company (i mean that trimmed word from title). I tried some codes and nothing! This is what i tried:
<?php
$connect = mysqli_connect("localhost", "dbname", "dbpass", "dbuser");
$connect->set_charset('utf8mb4');
mysqli_set_charset($link, 'utf8mb4');
$gamecompany = strstr($_smarty_tpl->tpl_vars['game']->value['title'], '-', true);
$query = 'SELECT * FROM games WHERE title = "'.$gamecompany.'" ORDER BY game_id ASC LIMIT 50';
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '<div class="list">';
while($row = mysqli_fetch_array($result))
{
$output .= '<li class="game">'.$row["title"].'</li>';
}
$output .= '</div>';
echo $output;
}
else
{
echo 'Nothing Found';
}
?>
So i used $gamecompany to trim and get a game's company and use it as a keyword in query. But everytime it just show "Nothing Found". When i have some games with keyword "Rockstar" in my database But it won't display that and just pass the conditions statement and can't show nothing.
Tried another keywords (Directly in my code) but won't work!
And one note: My titles are in "Arabic" language and it should be UTF8. Is this my problem? or just a wrong coding?
Using LIKE you can find all occurences with 'Rockstar', but to be safe, convert it to lower case and remove any extra spaces that might occur. Also, lets protect ourselves from SQL attacks with a prepared statement.
$gamecompany = strtolower(trim(strstr($_smarty_tpl->tpl_vars['game']->value['title'], '-', true))); // put it in lower case, trim any excess white space
$query = 'SELECT * FROM games WHERE LOWER(title) LIKE ? ORDER BY game_id ASC LIMIT 50';
$stmt = $conn->prepare($query);
$value = "%$gamecompany%"; // The % allows us to find any titles that have our search string in them
$stmt->bind_param("s", $value);
$stmt->execute();
$result = $stmt->get_result();
For you requirement
title = "'.$gamecompany.'"
is not going to work. You'll need to either use likewise search or full-text search
Likewise
title like '$gamecompany'
Full-Text - For full-text to work, you'll need to have full-text index for that column
MATCH (title) AGAINST (:gamecompany IN NATURAL LANGUAGE MODE)
You can create Full-text index like this
ALTER TABLE games ADD FULLTEXT(title)
Try using the LIKE keyword inside the query , and for the Arabic part make sure both the web app and the database uses the same encoding , i once had this problem and when both of them followed the same encode it worked out.
I am attempting to find results that resemble queries in a search for example, when someone searches "tes" I want "Test McTestFace" to come up.
I have attempted to use both LIKE and MATCH AGAINST methods and, neither seem to work. When using MATCH AGAINST, nothing comes up whereas when using LIKE, only direct matches come up.
My code for MATCH AGAINST:
if (isset($_POST['submit']))
{
$query = $db->prepare("SELECT * FROM accounts WHERE MATCH (name) AGAINST (:query)");
$query->execute(array('query' => $_POST['query']));
$result = $query->fetch();
}
print_r($result);
My code for LIKE:
if (isset($_POST['submit']))
{
$query = $db->prepare("SELECT * FROM accounts WHERE name LIKE :query");
$query->execute(array('query' => $_POST['query']));
$result = $query->fetch();
}
print_r($result);
Sorry and thank you.
If using LIKE you need to wrap the query with the wildcard % to make it work.
From the docs:
With LIKE you can use the following two wildcard characters in the pattern:
% matches any number of characters, even zero characters.
_ matches exactly one character.
i.e.
$query->execute(array('query' => '%' . $_POST['query'] . '%'));
To match against wildcards, you need to use '%'.$_POST['query'].'%'. (for LIKE).
I have been using the PHP function strpos to find results containing the characters of a string from a DB:
User Types: Hel
Results: Hello, Hell, Helli, Hella
I have it basically query the entire table:
$result = mysql_query("SELECT * FROM Events");
And then ran a while statement to see which of the results contain the characters of the input:
while($row = mysql_fetch_array($result))
{
$pos = strpos($row['Title'], $q);
if ($pos === false) {
} else {
echo $row['Title'];
}
}
And to find the number of results, I was using:
$n = $n++
Inside of the while statement.
I know you can use:
$num_rows = mysql_num_rows($result);
To find the number of results if you are only selecting those values from the database, but do I have to use this while statement to find the number of results that match the strpos function? Or can I put the strpos in to the Select From query?
Any help is greatly appreciated,
Taylor
This seems highly inefficient. Why wouldn't you simply let the database do the searching for you?
$result = mysql_query("SELECT * FROM Events WHERE Title LIKE '" . addslashes($q) . "%'");
Then just loop through the results.
You could update your SQL to something like
SELECT *
FROM Events
WHERE Title LIKE '{your_string}%'
Make sure to filter for sql injection though.
You can use the LIKE statement:
SELECT * FROM Events WHERE field1 LIKE '%something%'
Where the special % characters say "Anything of any length"; so we're searching for something (or nothing), then the string, then something (or nothing.) For example, searching for %f% will match foo, off, and affirmative.
Just as general advice, I recommend that you use php's MySQLi class; it's an improved version (hence the i), and provides prepared statements, so you won't have to worry too much about SQL injections.
$cities = "Amsterdam|Rotterdam|Den Haag"
$results = mysql_query("SELECT * FROM messages WHERE content REGEXP '$cities'");
The above code works great, but if $cities is empty, nothing is selected. I'd like to select all rows if $cities has no value. How can I achieve that? Thanks!
You will need to use a conditional in your php, which removes the where clause when your $cities variable is empty. Alternatively, you can use a regex that matches everything like /^/, but it's not particularly elegant.
you should check to see if the $cities is empty. If it is you can replace it with .* (match everything) or remove the from clause from the query (would increase performance)
$results = mysql_query("SELECT * FROM messages".
(empty($cities)? "":" WHERE content REGEXP '$cities'"));
Or probably
$results = mysql_query("SELECT * FROM messages WHERE '$cities' = '' OR content REGEXP '$cities'");
Basically i want to add wildcards to the the col value when searching...
Usually I do this the other way around like this:
WHERE cakes.cake_name LIKE '%$cake_search%'
however now i want it to match the inverse:
the user searches for 'treacle
sponge', i want this to match a row
where the cake_name column =
'sponge'.
is this possible?
WHERE '$cake_search' LIKE concat('%',cakes.cake_name, '%')
should work. It will need a full table scan but so will the inverse query. Have you looked into full text search for MySQL? It will likely make this sort of query more efficient.
Why not using MATCH?
MATCH(`cake_name`) AGAINST ('treacle sponge')
You would have to split the user supplied input on the space character and dynamically construct your query to check the column for those values:
$input = "treacle sponge";
$input_words = explode(' ', $input);
$sql_where = "WHERE cakes.cake_name IN('" . implode("','", $input_words) . "')"; // generates: WHERE cakes.cake_name IN('treacle','sponge')
In order to prevent SQL-Injection, I suggest using prepared statements.
$prepStmt = $conn->prepare('SELECT ... WHERE cakes.cake_name LIKE :cake_search
');
if($prepStmt->execute(array('cake_search'=>"%$cake_search%"))) {
...
}
Or, using full text search:
$prepStmt = $conn->prepare('SELECT ... WHERE MATCH (`cake_name`) AGAINST (:cake_search IN BOOLEAN MODE)');
if($prepStmt->execute(array('cake_search'=>$cake_search_words))) {
...
}
See JSON specialchars JSON php 5.2.13 for a complete example.. ;)