Jump to content

replacing a character


dennismonsewicz

Recommended Posts

I have this code:

 

$sql = mysql_query("SELECT * FROM board") or die(mysql_error());
			while($row = mysql_fetch_array($sql)) {
				$arr[] = $row;
				$img = "images/x.jpg";
				$replace = str_replace("x", $img, $arr);
				}

			echo $replace;

 

I am trying to search for X within the array and replace it with an image. But all I am getting echoed out is the word Array. Any help?

Link to comment
https://forums.phpfreaks.com/topic/120558-replacing-a-character/
Share on other sites

didn't work :(

 

updated code:

 

$sql = mysql_query("SELECT * FROM board") or die(mysql_error());
			while($row = mysql_fetch_array($sql)) {
				$arr[] = $row;
				$img = "images/x.jpg";
				$replace = str_replace("x", $img, $arr);
				echo $replace;
				}

You code makes no sense.

 

You iterrate through each record in the result set (as an array) and add it to another array - creating a mutidimensional array. Then you attempt to search for "x" in the multidimentional array $arr and replace it with the variable $img (which always contains "images/x.jpg").

 

Also in the loop you are always redefining the value of $replace, so when you echo the value you will only get the value from the last iterration through the loop.

 

To be honest I have no clue what you are trying to accomplish. Explain what results you are getting from your query and how you want to display those results.

You will need to specify the field from your database you want to search. something like this

 

$img = "images/x.jpg";
$sql = mysql_query("SELECT * FROM board") or die(mysql_error());
			while($row = mysql_fetch_array($sql)) 
{
				$x = $row['name of the field from the database'];

				$replace = str_replace("x", $img, $x);
				echo $replace;
				}

If adam291086's doesn't work you could try this if your DB is small and there too that many rows.  Basically it's searching each row manually...

 

$img = "images/x.jpg";
$sql = mysql_query("SELECT * FROM board") or die(mysql_error());
			while($row = mysql_fetch_array($sql)) 
{

                                        $replace = str_replace("x", $img, $row['row1']);
                                        $replace = str_replace("x", $img, $row['row2']);
                                        $replace = str_replace("x", $img, $row['row3']);
				$replace = str_replace("x", $img, $row['row4']);

				print_r($replace);
}

 

This generally isn't good practice but if you're only using this script once with a small DB I don't see a problem with it.  Hope this helps.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.