PHP bad word replacement comment system - php

I'm trying to create a comment system using php that replaces a commenters bad words with ****. I'm using sql and have a database with two columns, one with the bad word and one with the replacement word (which is the ****). So far, I am able to identify when a user types in a determined bad word and retrieve the replacement word for it, however I am unable to replace that bad word with the replacement word. I tried to do $element = $goodWord after $goodWord = $row['replaceWord'] to say that the new identified bad word should be replaced, however it does nothing. I'm not exactly sure how to set an element within an array in php to a new value. Any suggestions?
code:
if(!empty($_GET["field1_name"])) {
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '$element' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element = $goodWord
}
}
}

if(!empty($_GET["field1_name"])) {
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
$newComment = '';
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '$element' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element = $goodWord
}
$newComment = $newComment." ".$element; // append $element back to back to create modified comment
}
// now update the $newComment back to your comment Table
}

Related

Prevent text from being interpreted as a number

I have a PHP/SQL app that processes invoices. Recently, I had an invoice number come in that is not being processed as text, rather as a large exponential number when I do an insert/update on associated SQL tables. For example, take an invoice number that looks like this: 123E456. PHP will try to convert this to an extremely large number due to the 'E' being bookended by numbers.
I am leaning towards this being a PHP issue because when I look at the SQL being sent to the server, it is being scripted without quotes, 123E456 rather than '123E456'.
I have tried multiple ways to try and force it to be text, but nothing seems to work.
If I put single quotes around the string, I get double single quotes in the SQL.
strval() also does not work
the issue might be in the SQL interpreter, but not entirely sure
Right now, I am instructing my clerks to put a space between the E and the numbers, which works for now. But, I am hoping to address this specific issue in the code rather than have the clerk remember to manage it on their end.
Can anyone help with how to force this as being text in the SQL clause?
OK, the code is rather my own style and is based on retrieving a dummy record (the table has 178 columns) and then populating the values into the elements that need updated. It then creates the SQL from the array and does the update. Most of this is just pre-processing to get the values needed. The database being used is Oracle.
function processF0411Z1($id, $user){
include_once $_SERVER['DOCUMENT_ROOT'].'/truck/inc/base.inc.php';
$b = '\' \'';
$z = 0;
$co = get_route_company($id);
$usrsql='SELECT `userID` from `user` where `id` = ' . $user;
$usr = openRecordset_Fetch_Assoc($usrsql);
if($usr[0]==1)$userid = $usr[1]['userID'];
else $userid = $_SESSION['username'];
$jul = date2jul(getdate());
$tjul= getJulTime(getdate());
$sql = "SELECT a.`id`, a.`carrierInvoice`, a.`carrierNbr`, a.`ivd`, a.`dgl`, b.`bol`, b.`obj_acct`, b.`allocation` FROM `route13` a inner join `route131` b on(a.`id` = b.`id`)WHERE a.`id`=".$id;
$myArr = openRecordset_Fetch_Assoc($sql);
if(isset($myArr) && $myArr[0]>0){
$carr = $myArr[1]['carrierNbr'];
$carrsql = 'select `CarrierName` from `Carriers` where `CarrierNbr` = '. $carr;
$carr_res = openRecordset_Fetch_Assoc($carrsql);
if($carr_res[0]==1)$carrName = $carr_res[1]['CarrierName'];
else $carrName = $carr;
// get the next number in the EDI Batch sequence
$nn = getJDEZFileNN();
// get the base associated array of the F0411Z1 table
$msSQL = 'SELECT * FROM PRODDTA.F59411Z1 WHERE VLEDUS=\'TRUCK\' AND VLEDBT=1';
$F0411Z1 = oracle_fetch_array($msSQL);
for($i=1;$i<=$myArr[0];$i++){
// test to see if this record exists
$tsql = "select * from PRODDTA.F0411Z1 where VLEDUS = '".strtoupper($user)."' and VLEDBT = ".$nn[1]['NNN006']." and VLEDLN = " .$i*1000;
$tres = oracle_fetch_array($tsql);
if($tres[0]>0){
$dsql = "delete from PRODDTA.F0411Z1 where VLEDUS = '".strtoupper($user)."' and VLEDBT = ".$nn[1]['NNN006']." and VLEDLN = " .$i*1000;
$count = oracle_update($dsql);
if($count === $tres[0]){
$count = $count;
}
}
$an8_sql = 'SELECT aban85 FROM PRODDTA.F0101 WHERE aban8='.$myArr[$i]['carrierNbr'];
$aban85 = oracle_fetch_array($an8_sql);
$dp = date_parse($myArr[$i]['ivd']);
$dp1 = getDate(mktime(0,0,0,$dp['month'],$dp['day'],$dp['year']));
$ivd = date2jul($dp1);//date('Y-M-d',mktime(0,0,0,$dp['month'],$dp['day'],$dp['year'])));
$dp = date_parse($myArr[$i]['dgl']);
$dp1 = getDate(mktime(0,0,0,$dp['month'],$dp['day'],$dp['year']));
$inv_no = strval($myArr[$i]['carrierInvoice']);
// index: ("VLEDUS", "VLEDBT", "VLEDTN", "VLEDLN")
$gld = date2jul($dp1);//date('Y-M-d',mktime(0,0,0,$dp['month'],$dp['day'],$dp['year'])));
$F0411Z1[1]['VLEDUS'] = '\''.strtoupper($user).'\'';//$_SESSION['userid'];
$F0411Z1[1]['VLEDLN'] = $i*1000;
$F0411Z1[1]['VLEDBT'] = $nn[1]['NNN006'];
$F0411Z1[1]['VLAN8'] = $myArr[$i]['carrierNbr'];
$F0411Z1[1]['VLPYE'] = $aban85[1]['ABAN85'];//$myArr[$i]['carrierNbr'];
$F0411Z1[1]['VLDIVJ'] = $ivd;//$myArr[$i]['ivd'];
//$F0411Z1[1]['VLDSVJ'] = $jul;
$F0411Z1[1]['VLDGJ'] = $gld;
$F0411Z1[1]['VLCO'] = $co;
$F0411Z1[1]['VLKCO'] = $co;
$F0411Z1[1]['VLAG'] = round(($myArr[$i]['allocation']*100),0);
$F0411Z1[1]['VLAAP'] = round(($myArr[$i]['allocation']*100),0);
$F0411Z1[1]['VLVINV'] = $inv_no;// <-- This element is the issue
$F0411Z1[1]['VLRMK'] = (strlen($carrName)>30?substr($carrName,0,29):$carrName);
$F0411Z1[1]['VLGLBA'] = '00573714';
$F0411Z1[1]['VLMCU'] = '1';
$F0411Z1[1]['VLTORG'] = $userid;//$_SESSION['userid'];
$F0411Z1[1]['VLUSER'] = $userid;//$_SESSION['userid'];
$F0411Z1[1]['VLPID'] = 'TRUCK';
$F0411Z1[1]['VLUPMJ'] = $jul;
$F0411Z1[1]['VLUPMT'] = $tjul;
$F0411Z1[1]['VLJOBN'] = 'TRUCK';
$F0411Z1[1]['VLURAB'] = $id;
$F0411Z1[1]['VLURRF'] = $myArr[$i]['bol'];
$z=1;
for($x=1;$x<=$F0411Z1[0];$x++){
$val1 = $F0411Z1[$x];
// first element of array is the counter, skip it
if($val1 != 1){
foreach($F0411Z1[1] as $val){
if($z==1){
$stmt = 'VALUES('.$val;
$z=99;
}
else{
if(!is_numeric($val))$val = '\''.$val.'\'';
$stmt .= ','.$val;
}
}
$stmt .= ')';
//$msSQL = 'INSERT INTO PS_PRODUCTION.PRODDTA.F0411Z1 '.$stmt;
$msSQL = 'INSERT INTO PRODDTA.F0411Z1 '.$stmt;
$count = oracle_update($msSQL);
if($count != 1) return 36;
}
}
}
}
else return 36;
return 0;
}
You can use the strval() method to cast the number as a string.
$number = 123E456;
$string = strval($number);
Or just force it to cast as a string
$string = (string) $number;

Sql in php not working might be encoding?

My SQL code works when i do it phpmyadmin but when i run it in my php script it does not return anything i think it might be the encoding(was utf8) so i changed it to ansi but no difference. Might one of you be able to see if there is anything wrong with it?
(it's a script to remove images from a Wordpress post)
The code:
$query = "SELECT * FROM `wp_posts` where post_content like'%<img%\>'" or die("Error in the consult.." . mysqli_error($link));//THIS IS THE QUERY THAT DOES NOT WORK
$result = $link->query($query);
/*function filter($toFilter)
{
$pattern = "/<img.*?>/";
$filtered = "";
if(preg_match($pattern,$toFilter))
{
$filtered = preg_replace($pattern,'',$toFilter);
}
return (string)$filtered;
}
*/
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$toFilter = $row['post_content'];
$toFilter = (string)$toFilter;
$pattern = "/<img.*?>/";
$filtered = "";
if(preg_match($pattern,$toFilter))
{
$filtered = preg_replace($pattern,'',$toFilter);
}
$filtered = (string)$filtered;
$link->query("update wp_posts set post_content = $filtered where ID = $id;");
echo 'this works';
}
you have to escape this slash in '%<img%\>' (unless your point is to escape the >?)
Images don't have closing tags (http://www.w3.org/TR/html401/struct/objects.html#edef-IMG) so you might as well look for the starting tag
Stay with utf8
$pattern = "/<img.*?>/"; could be simply $pattern = "/<img.*>/";. the * means 0 or more, while the ? means optional so it's pretty much redundant

Posting Data To Mysql with IDs

I have a form with some input texts. It's counted with the name + an id. Like:
megnevezes_1
megnevezes_2
My form has also a counted id tag, called tid_1 and go on.
When I post my form i made a hidden input called darab, which counts how many id's I have.
Then I do the mysql query:
for($k=1; $k=$darab; $k++){
$command = <<<HTML
UPDATE
$dbtablename_template_tetelek
SET
vamtarifa_szj = '$vamtarifa_szj_$k',
megnevezes = '$megnevezes_$k',
me_egyseg = '$me_egyseg_$k',
mennyiseg = '$mennyiseg_$k',
afa = '$afa_$k',
egyseg_ar = 'str_replace(".","",$egyseg_ar_$k)'
WHERE template_id = '$tid_$k'
HTML;
mysql_query($command,$kapcsolat) or die(mysql_error(). $command);
}
But theres something wrong with it. How to attach to my strings the $k string with _? And how to make the str replace in the query?
Try this..
for($k=1; $k=$darab; $k++){
$blah = $egyseg_ar . '_' . $k;
$replace = str_replace(".", "", $blah);
$command = <<<HTML
UPDATE
$dbtablename_template_tetelek
SET
vamtarifa_szj = '$vamtarifa_szj_$k',
megnevezes = '$megnevezes_$k',
me_egyseg = '$me_egyseg_$k',
mennyiseg = '$mennyiseg_$k',
afa = '$afa_$k',
egyseg_ar = $replace
WHERE template_id = '$tid_$k'
HTML;
mysql_query($command,$kapcsolat) or die(mysql_error(). $command);
}
You should let PHP know precisely what it needs to parse. To help it you can use curly brackets like in '{$var1}_{$var2}'
So e.g. mennyiseg = '$mennyiseg_$k' might need to be mennyiseg = '{$mennyiseg}_{$k}' if you already have a variable named $mennyiseg in your code above the loop.

php regular expression matches and replacement

again.
I'm trying to go through a database table and replace all instances of old BBCode (ie: [i:fs8d979]) and replace it with simple BBCode ([i]). However, I'm getting very confusing results.
$root_path = './';
include($root_path.'includes/common.php');
$posts = array();
$sql = 'SELECT post_id, post_text FROM posts';
$db->query($sql);
while($row = $db->fetch_assoc())
{
$posts[]['id'] = $row['post_id'];
$posts[]['text'] = $row['post_text'];
}
foreach($posts as $post)
{
$regex = "/\[(\D)(\:[a-zA-Z0-9_]{1,})\]/";
if(preg_match($regex, $post['text'], $matches))
{
$string = preg_replace('/'.$matches[2].'/', '', $post['text']);
$sql = 'UPDATE posts SET post_text = "'.$string.'" WHERE post_id = '.$post['id'];
$db->query($sql);
echo $post['id'].'--Matched and replaced<br />';
}
else
{
echo $post['id'].'--No Match<br />';
}
}
echo 'done';
when i run this script, I get output like this:
1302--No Match
--No Match
1303--No Match
--No Match
17305--No Match
--Matched and replaced
5532--No Match
--No Match
17304--No Match
--No Match
1310--No Match
--No Match
it would appear that the script is attempting to do everything twice, and I'm not sure why. The database fields are not getting updated either.
I've echoed everything out for debugging purposes, and all variables are set and everything looks like it should be working properly.
Any suggestions?
At the point in the code:
while($row = $db->fetch_assoc())
{
$posts[]['id'] = $row['post_id'];
$posts[]['text'] = $row['post_text'];
}
You are creating two entries in the array, one with the id, followed by the text.
I think you want:
while($row = $db->fetch_assoc())
{
$posts[] = array('id' => $row['post_id'], 'text' => $row['post_text']);
}
It would explain why each one is happening twice and nothing is changing.
The debug was showing the wrong value too:
echo $post['id'].'--Matched and replaced<br />';
and the output was
--Matched and replaced which showed no post id.
First: the lines
$posts[]['id'] = $row['post_id'];
$posts[]['text'] = $row['post_text'];
are adding two elements to the $posts array. That is why you are getting two outputs per post.
Second: I don't think the colon : is a special character - it doesn't need to be escaped. So it should look like:
$regex = "/\[(\D)(:[a-zA-Z0-9_]+)\]/";

Codeigniter: Get affected fields in update

There's a way to get which fields were modified after a update query?
I want to keep track what field XXX user modified... any ways using active records?
I needed this exact functionality so I wrote this code. It returns the number of fields that were affected.
FUNCTION STARTS:
function mysql_affected_fields($sql)
{
// Parse SQL update statement
$piece1 = explode( "UPDATE ", $sql);
$piece2 = explode( "SET", $piece1[1]);
$sql_parts['table'] = trim($piece2[0]);
$piece1 = explode( "SET ", $sql);
$piece2 = explode( "WHERE", $piece1[1]);
$sql_parts['set'] = trim($piece2[0]);
$fields = explode (",",$sql_parts['set']);
foreach($fields as $field)
{
$field_parts = explode("=",$field);
$field_name = trim($field_parts[0]) ;
$field_value = trim($field_parts[1]) ;
$field_value =str_replace("'","",$field_value);
$sql_parts['field'][$field_name] = $field_value;
}
$piece1 = explode( "WHERE ", $sql);
$piece2 = explode( ";", $piece1[1]);
$sql_parts['where'] = trim($piece2[0]);
// Get original field values
$select = "SELECT * FROM ".$sql_parts['table']." WHERE ".$sql_parts['where'];
$result_latest = mysql_query($select) or trigger_error(mysql_error());
while($row = mysql_fetch_array($result_latest,MYSQL_ASSOC))
{
foreach($row as $k=>$v)
{
if ($sql_parts['field'][$k] == $v)
{
}
else
{
$different++;
}
}
}
return $different;
}
There is no way using active record to get this easily, but if you are only supporting one specific database type (let's say MySQL) you could always use Triggers?
Or, Adam is about right. If you have a WHERE criteria for your UPDATE you can SELECT it before you do the UPDATE then loop through the old and new versions comparing.
This is exactly the sort of work Triggers were created for, but of course that puts too much reliance on the DB which makes this less portable yada yada yada.
solution
instructions:
SELECT row, that user wants to modify
UPDATE it
Compute differences between selected and update it
Store the differences somewhere (or mail it, show it, whatever)
simple

Categories