Simple Find and Replace Script PHP/MySQL

I've been plugging away at this simple script and think it's time I try and get some help. I am trying to make a PHP script to communicate with my database. I want to be able to write an array with all the words to find and all the words to replace them with. Example:

array (find_word1,replace_word1,find_word2,replace_word2....etc)

I also want to be able to specify the table to look in, I will change this manually as well.

I will manually fill out all the words but I want to make it dynamic so it doesn't break if my array length changes.

I have tried many things and here is what I have so far:

    <?php

//set up variables and enter your credentials here
$dbname = "name"; 
$dbhost = "localhost";
$dbpass = "password";
$dbuser = "user";
$tbl_name = "Chairs";
//set up your master array! Array goes in this or
$mstr_array = array(
                "find1", "replace1",
                "find2", "replace2");

//connect to database
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die('no connection:'  . mysql_error());
$db = mysql_select_db($dbname) or die ('cant select db: ' . mysql_error());

// reteive each column
$sql = "SHOW COLUMNS FROM `{$tbl_name}`";
$res = mysql_query($sql) or  die ('could not get columns: ' . mysql_error());
$find = 0;
$replace = 1;

while ($col = mysql_fetch_array($res)) {

        $sql = "UPDATE `{$tbl_name}` SET `{$col[0]}` = REPLACE(`{$col[0]}`, '{$mstr_array[$find]}' , '{$mstr_array[$replace]}')";
        $find = $find + 2;
        $replace = $replace + 2;
}

?> 

Any help would be greatly appreciated! Thanks

Answers


The first thing that ups to my mind is that instead of using:

$mstr_array = array(
                "find1", "replace1",
                "find2", "replace2");

use:

$mstr_keys = array('find1', 'find2', ....);
$mstr_values = array('replace1', 'replace2', ....);

and then on the query you can simply use:

$count = 0;
$sql = "UPDATE `{$tbl_name}` SET `{$col[0]}` = REPLACE(`{$col[0]}`, '{$mstr_keys[$count]}' , '{$mstr_values[$count]}')";
$count++;

I hope it's what you were looking for...


Need Your Help

C++: Pointer pointing to multi-dimensional array: “incompatible to the parameter of type”

c++ pointers multidimensional-array

I am programming a game where I have a class called Wizard and another class called Judge.

wxPython, Getting input from TextCtrl box to send to Notepad

python windows wxpython

I am trying to create a simple invoice program for a school project. I have the basic layout of my program.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.