replace string in php? - php

This question is a bit basic and have been covered many times but I'm not sure why my code doesn't do anything. it doesn't update string at all.
this is my code:
$fineImage = "users_fav/".$_GET['id']."/$newname";
$icon = "<img src='images/icon.png' height='70' width='70' />";
$sql = "UPDATE $lchat SET user_message = replace(user_message, '$icon', '$fineImage')";
$query = mysqli_query($db_conx, $sql);
the problem is that if I change the '$icon', '$fineImage' to something like 'david', 'mark'. it works fine and it will replace the david with mark...!
so why doesn't it work the way i do it?

It's likely that your call to MySQL's REPLACE(input, before, after) is failing to find before in its input, so is returning input unmodified.
Why could this be? Several reasons:
user_message doesn't contain what you think it contains. For example, are the < and > tags entitized (that is, coded with < and the like)?
you're replacing a full <img..> tag with your $fine_image. Is $fineimage also an <img ...> tag?
your before parameter contains embedded single quote characters. That could conspire to make your SQL string invalid.

Try this:-
$sql = "UPDATE {$lchat} SET `user_message` = replace(`user_message`, '{$icon}', '{$fineImage}')";
Make sure you have $lchat, $icon, $fineImage defined. :)

Related

php - get character count between two points encased in quotes

Ok this is going to be weird but I need it
I am trying to get the character count for a huge line of code between some particular quotes ". Basically I need to be able to get everything between the 3rd quote in the beginning and the 5th quote at the end.
So here is an example
a:2:{s:10:"categories";s:5758:"...........";s:5:"posts";s:6:"a:0:{}";}
I need to know what the character count is of all the periods. There is actually code in place of those periods.
Since there are 11 periods then my character count will be 11. The only consistent thing is the quotes in this so I need to base off that.
Any help would be awesome.
Here is my code. I am basically creating the code and adding some custom labels. I tried serializing the code first before I unserialize it but that didn't seem to work.
<?
$thisisit .= 'a:2:{s:10:"categories";s:5481:"a:40:{';
include('connect.php');
$sql = "SELECT * FROM wp_terms ORDER BY term_id ASC LIMIT 40";
$result = mysql_query($sql);
$count = 0;
while($row = mysql_fetch_array($result)) {
$name = $row['name'];
$charactercount = strlen($name);
$term_id = $row['term_id'];
$thisisit .= 'i:'.$count.';a:2:{s:11:"filter_name";s:20:"add_keyword_category";s:11:"filter_args";a:7:{s:12:"filter_value";s:'.$charactercount.':"'.strtolower($name).'";s:19:"filter_search_title";s:1:"1";s:21:"filter_search_excerpt";i:0;s:21:"filter_search_content";s:1:"1";s:21:"faf_filter_categories";a:1:{i:4;s:3:"'.$term_id.'";}s:17:"filter_match_word";i:0;s:17:"filter_match_case";i:0;}}';
//echo "<br><br>";
$count++;
}
$thisisit .= '}";s:5:"posts";s:6:"a:0:{}";}';
$array = unserialize($thisisit);
echo strlen($array['categories']);
?>
Actually this data looks serialized. The correct solution would be to use php function unserialize.
Then, given your structure, to know the length of that element:
strlen(unserialize($data)['categories']);
If you run old php, you need to store the result in a temporary variable:
$array = unserialize($data);
echo strlen($array['categories']);
If your serialized data is corrupted (as in "not received from proper execution of serialize"), as it seems from your example, we can return to your original task:
get everything between the 3rd quote in the beginning and the 5th quote at the end
The simplest way to achieve that is:
implode("'", array_slice(explode("'", $data), 3, -5));

Retrieve all data from SQL array LIKE a given value

I'm trying to retrieve all the data id from a database where their tags(array) is like a given value.
This is what I have done so far...
$new_string = 'nice phone';
$construct = mysql_query("SELECT tag_array, name, id FROM details
WHERE tag_array LIKE $new_string%")
or die("<p>died 20: $construct<br>" . mysql_error());
while($getThis = mysql_fetch_array($construct)){
echo $getThis['id'].'<br />';
echo stripslashes($getThis['name']).'<br />';
}
It doesn't work ATALL.
Could you please point me to the right direction?
I'm really struggling!!
You should put $new_string in quotes.
NOTE It is very bad practice and you should always escape all variables you are passing to SQL. You should really read up on SQL injection and other security issues.
Also if you want to match $new_string anywhere in tag_array (which you most likely want), you need to add dollar sign in front of it too. You can read up more at MySQL reference manual.
So in the end:
"SELECT tag_array, name, id FROM details WHERE tag_array LIKE '%" . mysql_real_escape_string($new_string) . "%'"
You should sanitise the data before putting it in the query like:
$new_string = "blah...; DROP TABLE tag_array; #";
$sql = mysql_real_escape_string($new_string);
$sql = "SELECT tag_array, name, id FROM details WHERE tag_array LIKE %'$sql'%"
This is not enough though it just helps preventing sql inject, consider using regular expressions to clean the data. If you don't yet know about regexp check out this site: regexp info. It helped me mutch.

PHP mysql - ...AND column='anything'...?

Is there any way to check if a column is "anything"? The reason is that i have a searchfunction that get's an ID from the URL, and then it passes it through the sql algorithm and shows the result. But if that URL "function" (?) isn't filled in, it just searches for:
...AND column=''...
and that doesn't return any results at all. I've tried using a "%", but that doesn't do anything.
Any ideas?
Here's the query:
mysql_query("SELECT * FROM filer
WHERE real_name LIKE '%$searchString%'
AND public='1' AND ikon='$tab'
OR filinfo LIKE '%$searchString%'
AND public='1'
AND ikon='$tab'
ORDER BY rank DESC, kommentarer DESC");
The problem is "ikon=''"...
and ikon like '%' would check for the column containing "anything". Note that like can also be used for comparing to literal strings with no wildcards, so, if you change that portion of SQL to use like then you could pre-set the variable to '%' and be all set.
However, as someone else mentioned below, beware of SQL injection attacks. I always strongly suggest that people use mysqli and prepared queries instead of relying on mysql_real_escape_string().
You can dynamically create your query, e.g.:
$query = "SELECT * FROM table WHERE foo='bar'";
if(isset($_GET['id'])) {
$query .= " AND column='" . mysql_real_escape_string($_GET['id']) . "'";
}
Update: Updated code to be closer to the OP's question.
Try using this:
AND ('$tab' = '' OR ikon = '$tab')
If the empty string is given then the condition will always succeed.
Alternatively, from PHP you could build two different queries depending on whether $id is empty or not.
Run your query if search string is provided by wrapping it in if-else condition:
$id = (int) $_GET['id'];
if ($id)
{
// run query
}
else
{
// echo oops
}
There is noway to check if a column is "anything"
The way to include all values into query result is exclude this field from the query.
But you can always build a query dynamically.
Just a small example:
$w=array();
if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";
if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where='';
$query="select * from table $where";
For your query it's very easy:
$ikon="";
if ($id) $ikon = "AND ikon='$tab'";
mysql_query("SELECT * FROM filer
WHERE (real_name LIKE '%$searchString%'
OR filinfo LIKE '%$searchString%')
AND public='1'
$ikon
ORDER BY rank DESC, kommentarer DESC");
I hope you have all your strings already escaped
I take it that you are adding the values in from variables. The variable is coming and you need to do something with it - too late to hardcode a 'OR 1 = 1' section in there. You need to understand that LIKE isn't what it sounds like (partial matching only) - it does exact matches too. There is no need for 'field = anything' as:
{field LIKE '%'} will give you everything
{field LIKE 'specific_value'} will ONLY give you that value - it is not partial matching like it sounds like it would be.
Using 'specific_value%' or '%specific_value' will start doing partial matching. Therefore LIKE should do all you need for when you have a variable incoming that may be a '%' to get everything or a specific value that you want to match exactly. This is how search filtering behaviour would usually happen I expect.

Search entire table? PHP MySQL

I have made the following search script but can only search one table column when querying the database:
$query = "select * from explore where site_name like '%".$searchterm."%'";
I would like to know how I can search the entire table(explore). Also, I would need to fix this line of code:
echo "$num_found. ".($row['site_name'])." <br />";
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Thanks for any help, here is the entire script if needed:
<?php
// Set variables from form.
$searchterm = $_POST['searchterm'];
trim ($searchterm);
// Check if search term was entered.
if (!$serachterm)
{
echo "Please enter a search term.";
}
// Add slashes to search term.
if (!get_magic_quotes_gpc())
{
$searchterm = addcslashes($searchterm);
}
// Connects to database.
# $dbconn = new mysqli('localhost', 'root', 'root', 'ajax_demo');
if (mysqli_connect_errno())
{
echo "Could not connect to database. Please try again later.";
exit;
}
// Query the database.
$query = "select * from explore where site_name like '%".$searchterm."%'";
$result = $dbconn->query($query);
// Number of rows found.
$num_results = $result->num_rows;
echo "Found: ".$num_results."</p>";
// Loops through results.
for ($i=0; $i <$num_results; $i++)
{
$num_found = $i + 1;
$row = $result->fetch_assoc();
echo "$num_found. ".($row['site_name'])." <br />";
}
// Escape database.
$result->free();
$dbconn->close();
?>
Contrary to other answers, I think you want to use "OR" in your query, not "AND":
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
Replace other_column with the name of a second column. You can keep repeating the part I added for each of your columns.
Note: this is assuming that your variable $searchterm has already been escaped for the database, for example with $mysqli->real_escape_string($searchterm);. Always ensure that is the case, or better yet use parameterised queries.
Similarly when outputting your variables like $row['site_name'] always make sure you escape them for HTML, for example using htmlspecialchars($row['site_name']).
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Make sure that both forms use the same method (post in your example). The <form> tag should have the attribute method="post".
Also, what is wrong with the line of code you mentioned? Is there an error? It should work as far as I can tell.
A UNION query will provide results in a more optimized fashion than simply using OR. Please note that utilizing LIKE in such a manner will not allow you to utilize any indexes you may have on your table. You can use the following to provide a more optimized query at the expense of losing a few possible results:
$query = "SELECT * FROM explore WHERE site_name LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE other_field LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE third_field LIKE '".$searchterm."%'";
This query is probably as fast as you're going to get without using FULLTEXT searching. The downside, however, is that you can only match strings beginning with the searchterm.
To search other columns of table you need to add conditions to your sql
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
But if you don't know that I would strongly advise going through some sql tutorial...
Also I didn't see anything wrong with this line
echo "$num_found. ".($row['site_name'])." <br />";
What error message are you getting?
Just add 'AND column = "condition"' to the WHERE clause of your query.
Be careful with adding lots of LIKE % conditions as these can be very slow especially if using a front wild card. This causes the RDBMS to search every row. You can optimize if you use an index on the column and only a trailing wildcard.
You are searching the whole table, just limiting the results to those where the site_name like '%".$searchterm."%'. If you want to search everything from that table, you need to remove the WHERE clause
Here's the corrected line. You had a few too many quotes in it.
echo $num_found.".".($row['site_name'])." <br />";
Regarding displaying the message, you have a typo in your code:
// Check if search term was entered.
if (!$serachterm)
should be:
// Check if search term was entered.
if (!$searchterm)
In the code you have written, !$serachterm always evaluates to true because you never declared a variable $seracherm (note the typo).
your code is very bugy for sql injection first do
do this
$searchterm = htmlspecialchars($searchterm);
trim($searchterm);
next
$query = mysql_real_escape_string($query);
finaly your search looks like this
$query = "select * from explore where site_name like '%$searchterm%';

On MouseOver doTooltip in phpmysql

HI Please help to fix this code , i use TITLE
in this code but its not work
<?
$sql = "select * from wallpaper order by wallpaperid desc limit 20";
$result = mysql_query($sql, $db) or die(mysql_error());
if(mysql_num_rows($result)) {
while($myrow = mysql_fetch_array($result)) {
$title = substr($myrow['title'] ,0,31);
$wurl = ereg_replace(" ", "-", $myrow['title']);
$html = '<dt>%s..</dt>';
printf($html, $wurl, $myrow["wallpaperid"], $myrow["wallpapername"], $myrow["title"], $category);
} }
?>
plsease someone help me to fix this
Second code not work onmouseOver TIP
First of all, this is purely a front-end (that is, Javascript/HTML) problem. It has nothing to do with PHP. You haven't actually provided enough information to help pinpoint the issue. It would be much more helpful to see your "doTooltip" and "hideTip" javascript functions.
That said, I notice that you're attempting to use variables $siteurl, $wallpapername, and $wallpaperid variables in your link string. You cannot use PHP variables in a string delimited with ' (single quotes).
Try this:
$html = '<dt>%s..</dt>';
But I suspect that this isn't related to the problem you're actually trying to solve. I'd recommend that you revise your question. Leave out the PHP this time and only show the final output generated by your script. Good luck!

Categories