how to remove space in a sentence in mysql - php

can someone help me on how to remove spaces in my sql.
for exmaple
let say i type in "I am a good boy"... i want it to save in my mysql table column as "iamagoodboy" removing all spaces of anything i send.. where in this code below can i do this, thanks very much
$sql = 'INSERT INTO messages (username,usernameto, message_content, message_time) VALUES ("' . $username . '", "' . $messageTo . '", "' . $message . '", ' . $time . ')';
$result = mysql_query($sql, $cn) or
die(mysql_error($cn));

str_replace(' ', '', $message);
Should work fine for you in PHP. As a general rule, don't put that sort of functionality on the Database, no reason to put the load on that server - do it on the web server instead.
So your code would look like this (assuming you are taking the spaces out of $message):
$sql = 'INSERT INTO messages (username,usernameto, message_content, message_time) VALUES ("' . $username . '", "' . $messageTo . '", "' . str_replace(' ', '', $message) . '", ' . $time . ')';
A better solution, though, might be to use preg_replace('/\s+/', '', $string); which will strip all whitespace (tabs, linebreaks, etc). Depends on what exactly you want to accomplish.

Use str_replace:
$string = str_replace(' ', '', $string);
or remove all whitespace
$string = preg_replace('/\s+/', '', $string);
source: How to strip all spaces out of a string in php?

You can replace characters using SQL ->
SELECT REPLACE(caption,'\"','\'') FROM ...

u can try this
'".str_replace(' ', '', $messageTo)."'
and same for other

$sql = 'INSERT INTO messages " .
. "(username,usernameto,message_content,message_time) " .
. "VALUES ("'.$username.'","'.$messageTo.'",REPLACE("'.$message.','' '','''')",'.$time .')';
$result = mysql_query($sql, $cn) or die(mysql_error($cn));

Related

Unable to delete record from Solr if any white space there in PHP

$cat = 'tv - Episode';
$user_id = 1;
$delsolrobj = new SolrFunctions();
$delsolrobj->deleteSolrQuery("cat: ".$cat." AND sku:" . $user_id . " AND content_id:" . $_REQUEST['movie_id'] . " AND stream_id:" . $epData->id);
I have posted my solr delete PHP code. Above code I am getting this error message in my page.
'400' Status: Bad Request
I am sure that problem coming from $cat because there are some spaces.
I Googled found one solution they are saying to put your category within braces. I have done with this code:
$delsolrobj->deleteSolrQuery("cat: (".$cat.") AND sku:" . $user_id . " AND content_id:" . $_REQUEST['movie_id'] . " AND stream_id:" . $epData->id);
Now in my above line code working fine without any error message. But my record not delete from Solr.
please help me.
Try this query: (You can also use quotes when space is there)
$delsolrobj->deleteSolrQuery("cat:'".$cat."' AND sku:" . $user_id . " AND content_id:" . $_REQUEST['movie_id'] . " AND stream_id:" . $epData->id);
You have to escape the values properly, so that even if there is spaces or quotes, you don't run a badly generated query (i.e. if a category suddenly had ' OR -cat:foo or something similar in it).
If you're not using a Solr library (which should have an escape function available, you can use the ad hoc version:
function escapeSolrValue($string)
{
$match = array('\\', '+', '-', '&', '|', '!', '(', ')', '{', '}', '[', ']', '^', '~', '*', '?', ':', '"', ';', ' ');
$replace = array('\\\\', '\\+', '\\-', '\\&', '\\|', '\\!', '\\(', '\\)', '\\{', '\\}', '\\[', '\\]', '\\^', '\\~', '\\*', '\\?', '\\:', '\\"', '\\;', '\\ ');
$string = str_replace($match, $replace, $string);
return $string;
}

PHP - Replace apostrophe

I am currently developing a website with a list of names. Some of the names include apostrophes ' and I want to link them to a website using their name.
I want to link to the a url like:
example.com/ (their name)
And by doing that, I first replace " " with "+". So the links looks like: example.com/john+doe
But if the name is John'Doe it turns the url into just example.com/john
And skips the lastname.
How can I fix this? I tried changing ', \' etc, to html codes, to ', and more, but nothing seems to work.
Here is my current code:
$name = $row['name'];
$new_name = str_replace(
array("'", "'"),
array(" ", "+"),
$name
);
echo "<td>" . $name . " <a href='http://www.example.com/name=" . $new_name . "' target='_blank'></a>" . "</td>";
What I want it to look like:
John Doe Johnson ----> http://www.example.com/name=John+Doe+Johnson
John'Doe Johnson ----> http://www.example.com/name=John'Doe+Johnson
It changes the spaces to +, but how can I fix the apostrophes? Anyone knows?
You should be using PHP's function urlencode, php.net/manual/en/function.urlencode.php.
<?php
$name = $row['name'];
//$urlname = urlencode('John\'Doe Johnson');
$urlname = urlencode($name);
echo "<td>$name<a href='http://www.example.com/name=$urlname' target='_blank'>$name</a></td>";
Output:
<td>John%27Doe+Johnson <a href='http://www.example.com/name=John%27Doe+Johnson' target='_blank'></a></td>
echo urlencode("John'Doe Johnson");
return
John%27Doe+Johnson

PHP MySQL Search Form Select Field and Search Term, Delimiter In Where Clause

I want to allow a user to search a table by selecting a field name from a dropdown list, then entering the term to search for in that field. The problem I'm having is that some fields are strings and some are numbers. When I construct the WHERE clause from the $_GET variables, I don't know how to delimit the search term because I can't come up with a good way to determine if the field selected by the user is numeric or string.
This is the search form:
<form action="<?php $_SERVER['PHP_SELF'] ?>">
<label for="search_field">Search:</label>
<select name="search_field">
<?php
$fields = $res->fetch_fields();
foreach($fields AS $f) {
echo '<option value="' . $f->name . '">' . $f->name . '</option>\n';
}
?>
</select>
<label for="search_for">For:</label>
<input type="text" name="search_for" />
<input type="submit" value="Search" />
</form>
The php file processes the search variables like this:
if(isset($_GET['search_field']) and isset($_GET['search_for'])) {
$sql_where = "AND " . $_GET['search_field'] . ' = ' . $_GET['search_for'] . ' ';
}
$sql = $sql . $sql_where;
The query works fine for numeric fields, but not string fields. I could put quotes around the search_for term, but then numeric fields wouldn't work. There has got to be a way to do this. Any ideas? Thanks.
Just use is_numeric function to determine if its an number or string:
if(isset($_GET['search_field']) and isset($_GET['search_for'])) {
if(is_numeric($_GET['search_for']))
$sql_where = 'AND ' . $_GET['search_field'] . ' = . $_GET['search_for'] . ';
else{
$sql_where = 'AND ' . $_GET['search_field'] . ' = ' . '.$_GET['search_for'] . ' ';
}
}
You can check if $_GET['search_for'] is numeric in php using is_numeric
if(isset($_GET['search_field']) and isset($_GET['search_for'])) {
$sql_where = "AND " . $_GET['search_field'] . ' = ' .
(is_numeric($_GET['search_for']) ? $_GET['search_for'] : '"' .
$_GET['search_for'] . '"' ) . ' ';
}
Also if you always delimit the search_for with quotes it will work with numeric values you can try it. I just wanted to show you the is_numeric function as well
You know your code has security problems, don't you?
But to solve your problem just do
$search_for = is_numeric($_GET['search_for'])?$_GET['search_for']:"'".addslashes($_GET['search_for'])."'";
$sql_where = 'AND `' . $_GET['search_field'] . '` = ' . $search_for . ' ';

Can I use str_replace twice in one string?

<?php
echo "I'm currently listening to</a> <a href='http://last.fm/artist/" . str_replace(" ","+",$artist) . "/_/" . str_replace(" ","+",$currenttrack) . "'>" . $currenttrack . "</a>";
?>
Above is my code. I'm trying to use str_replace() again on $artist and $currenttrack like:
str_replace("'","%27",$artist) and str_replace("'","%27",$currenttrack)
because the apostrophe doesn't go through correctly and messes with my code, but when I use it first with the spaces, it's already passed and won't change again.
What can I do?
If you want to do multiple replacements on the same string, you can pass arrays to str_replace:
str_replace(array(" ", "'"), array("+", "%27"), $artist)
However, when creating URL parameters, you shouldn't do the replacements yourself. You should use urlencode, and it will do all the necessary encodings.
Try this. It also makes your code more readable. Also, your anchor tags aren't formatted correctly.
$artist = str_replace(' ', '+', $artist);
$track = str_replace(' ', '%27', $currenttrack);
echo 'I\'m currently listening to ' . $track . '';
If I understood your question correctly, you are trying to replace spaces by + and ' by %27 in the two strings. To achieve this, you have to apply str_replace() on the result of the first operation. If $input is the original string, use:
$intermediate = str_replace(" ", "+", $input);
$result = str_replace("'", "%27", $intermediate);
There is a built in function to do the same you are trying to do: urlencode
$currenttrack = $artist = "X' xx WWW' w";
$url = "http://last.fm/artist/" . $artist . "/_/" . $currenttrack;
echo urlencode($url); // http%3A%2F%2Flast.fm%2Fartist%2FX%27+xx+WWW%27+w%2F_%2FX%27+xx+WWW%27+w

how to ignore a ' char in php

I want to have a string with the char ' in it, without having it closing the string:
$title = "google";
$link = "www.google.com";
$val_str = "'" . $title . "'," . $link . "'";
$query = "INSERT INTO MY_TABLE (title,link) . VALUES (" . $val_str . ")";
so that $val_str will have: 'google', 'www.google.com'
in it.
how can i do it?
You can use a backslash to escape the ' character in your string:
echo 'Hello: "I\'ll be back"';
Escape it with a \.
i.e. \'google.com\'
You could just do this:
$query = "INSERT INTO MY_TABLE (title,link) VALUES ('$title', '$link')";
If $title and $link is not under your control, then you need to escape them.

Categories