removing unwanted characters from string in php - php

I'm using a database to store variables of user names and then access them using php. A form with post method is used to invoke a php file which access the database, retrieves all the user names and then compares them with the entered values. The user names are stored in $row['name'] variable and the name is stored in $photographer variable.
The problem is that there are some characters attached in string of variable $row['name'] when being accessed from db which I can't get rid of.
I thought using these variables directly might be causing some problems so I saved their values in other two variables. But the problem didn't go away.
Below is the php code:
//pin check module
$connection = mysqli_connect("localhost","root","","members") or die(mysqli_error($connection));
$select_query_pin = "SELECT name, pin FROM members";
$select_query_pin_result = mysqli_query($connection, $select_query_pin) or die (mysqli_error($connection));
$total = mysqli_num_rows($select_query_pin_result);
$pin = $_POST['pin'];
$title = explode(",",$_POST['title']);
$url = explode(",",$_POST['url']);
$photographer = $_POST['photographer'];
$genere = explode(",",$_POST['genere']);
$entry = sizeof($title);
while ($total) {
--$total;
$row = mysqli_fetch_array($select_query_pin_result);
$name_sample = $row['name'];
$test_sample = $photographer;
// chop($name_sample);
// chop($test_sample);
preg_replace( "/\r|\n/", "", $name_sample );
// for ($i = 0; $i < strlen($name_sample); $i++) {
// if ($name_sample[$i] == " ")
// echo 'true';
// }
var_dump($name_sample,$test_sample);
if ($name_sample === $test_sample)
echo 'true<br>';
else
echo "false<br>";}
As you can see, I tried using the chop and preg_replace methods but it didn't work. When I check the strings using var_dump, it gives unequal lengths for equal strings. The html view of above code is this:html output
Is there a way to deal with it?

Related

Comparing Data Before and After Form Submission

I have a form page in which many of the elements are saved to different tables and different rows in my db. In order to minimize db calls I would like to compare the data before and after form submission, then I can write a function which will only update data that has been changed. To accomplish this I am saving the array that I used to build the form in a session file:
$this->session->set_tempdata('form_values_'.$item['id'],json_encode($item), 86400);
On form submission I retrieve this data and compare it to the $_POST:
$pre_post = json_decode($_SESSION['form_values_'.$_POST['id']], true);
Everything works great except in a few textareas where there is a "." in my test data. For some reason these fields come back as not equal even though I'm not changing the data.
It is definitely the period that is causing the problem, when I remove it it works fine. On the other hand there are other textareas that have periods that are not causing problems.
I thought it might be codeigniter's XSS filtering, but I removed that and it made no difference.
Originally i was using serialize to encode the array for storage, but I switched to json_encode and again it made no difference.
Here is the code I am using to compare the values:
$pre_post = json_decode($_SESSION['form_values_'.$_POST['id']], true);
$post = $this->security->xss_clean($_POST);
foreach ($post as $key => $value) {
if( !isset($pre_post[$key]) || trim($value)!=trim($pre_post[$key]) ){
$post_post[$key] = $value;
}
}
Any ideas?
Try this code may be it help you
$select = "SELECT * FROM ".$table_name." WHERE ".$field_name ." = '".$value."'";
$result_latest = mysql_query($select) or trigger_error(mysql_error());
while($row = mysql_fetch_array($result_latest,MYSQL_ASSOC))
{
$data_new = array_intersect_key($row,$data);
foreach($data_new as $k=>$v)
{
if(strcmp($row[$k],$data[$k]) != 0)
{
$string .= '`'.$k.'` = "'.$data[$k].'" ,';
}
}
}
$string = rtrim($string, ",");
if($string != NULL){
$update_sql = "UPDATE ".$table_name." SET ".$string." WHERE ".$field_name." = "."'".$value."'";
$query = $CI->db->query($update_sql);
}

extracting values from Mysql query

i am confused about how to extract values from a query, and place them into specific variable, when i don't know before hand what the name of the value will be.
it might be easier to show you what i mean.
the images below are the returned values, grouped by heading i.e Total_responded, Percent_responded etc.
so the first row will have under the column Responce the value Poached with a Percent_responded of 16.66667.
however the next row will have under column Responce $scrambled with a Percent_responded of 83.333333
i now want to place each of these values into individual variables like:
$poached , $poachedPercentage, $scrambled, $scrambledPercentage etc
i attempted to do it below, but produced the wrong figures. this is also not a cost effective way to do it. so, i would really appricaite some advice on how to extract the values
$getPollResult = results();
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce = safe_output(round($row['RESPONCE']));
$percentage = safe_output(round($row['Percent_responded']));
if($responce = 'Poached')
{
$percentageOne = $percentage;
$poached = $responce;
}
if ($responce = 'Scrambled')
{
$percentageTwo = $percentage;
$scrambled = $responce;
}
// echo " $percentagePoached $percentageScrambled ";die();
}
Use
$responce = trim($row['RESPONCE']);
Instead Of
$responce = safe_output(round($row['RESPONCE']));
Also, Change in if condition = to ==.
you can use "variable variables" (PHP Docs) to achieve that:
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce_name = trim($row['RESPONCE']);
$percentage_name = $responce_name . "Percentage";
$percentage = safe_output(round($row['Percent_responded'])); //don't know what safe_output() does
$$percentage_name = $percentage; //notice the double "$" here
}
your PHP variables will then look like this:
$PoachedPercentage = 17;
$ScrambledPercentage = 83;
// and so on....

How to identify list of variables_x from url in PHP, using one parameter?

I have a members site where users are given up to 7 web page templates to display their products on. Each template has the same field names, differentiated by _1, _2... _7 at the end of each.
For example:
// Template 1 would have the following list of variables
product_name_1
product_descript_1
product_color_1
product_price_1
// Template 2 would have the following list of variables
product_name_2
product_descript_2
product_color_2
product_price_2
// through Template 7
I am able to display any variables for a specific user within a web page, by use of a query string identifying their user_id in the url, ie
http://domain.com/folder/page.php?id=78
I then $_Get any variable by simply identifying it in the PHP file, ie
$product_name_1
$product_descript_1
$product_color_1
$product_price_1
My problem is that the url must identify WHICH template, since each template identifies a specific product, ie _1, _2, ..._7. How do I use a parameter in the url, such as
http://domain.com/folder/page.php?id=78&parameter=_7
...to identify all variables ending with _7, which would appear in the web page? The parameter used in the url would identify the variables to be used in the web page, whether _1, _2, etc.
UPDATE
I have tried the various answers with only partial success, ie "Array_x" is displayed when using any particular variable along with the suggested code. There may be a conflict with the rest of the code I'm using in page.php, as follows:
$db_connection = new mysqli("", "", "");
if ($db_connection->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
$prop_address=array(
"_1"=>"prop_address_1",
"_2"=>"prop_address_2",
"_3"=>"prop_address_3"
//Through to Temp 7
);
$prop_address{$_GET['parameter']}=$row->prop_address;
echo " $prop_address{$_GET['parameter']} ";
"Array_x" displays (where x=1, 2, 3, etc is used as the parameter in url, ie http://domain.com/page.php?id=72&parameter=1), instead of the actual value held in the database table for $product_name{$_GET['parameter']}. For some reason, the code is not picking up the value of the variable from the database table.
Would it be possible to use arrays so...
$product_name=array(
"1"=>"Product name for template 1",
"2"=>"Product name for template 2"
//Through to Temp 7
);
echo $product_name[$_GET["parameter"]];
You could then do the same for the other variables.
You could fill each array by doing something like:
$row = mysql_fetch_object($query);
$product_name[$_GET['parameter']]=$row->product_name;
echo $product_name[$_GET['parameter']];
I may be missing something...
$_GET['parameter'] = '_2';
$product_name{$_GET['parameter']} = 'string';
echo $product_name_2; // string
or
$_GET['parameter'] = '_2';
$var = 'product_name'.$_GET['parameter'];
$$var = 'string';
echo $product_name_2; // string
Personally, I would use array's for this type of behavior.
Update:
Although the above works and tested ok, it is a lot more work than anyone would probably desired.
In lieu of simplicity, I would suggest the approach via array's.
$templates = array(2 => array(
'product_name' => "value",
'product_descript' => "value",
'product_color' => "value",
'product_price' => "value",
);
foreach($templates[substr($_GET['parameter'],1)] as $var => $val){
$variable = $var.$_GET['parameter'];
$$variable = $val;
}
The above is backwards compatible, it uses substr to remove the leading _ from your parameter.
I couldn't get any of the answers given to work. I found an example given by a user for php variable variables in the PHP manual here and found it to work. I incorporated it into my code as follows:
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
for( $i = 1; $i < 8; $i++ )
{
$product_name[$_GET['parameter']] = "product_name_" . $i;
$product_descript[$_GET['parameter']] = "product_descript_" . $i;
$product_color[$_GET['parameter']] = "product_color_" . $i;
$product_price[$_GET['parameter']] = "product_price_" . $i;
}
${$product_name[1]} = "$row->product_name_1";
${$product_name[2]} = "$row->product_name_2";
${$product_name[3]} = "$row->product_name_3";
${$product_name[4]} = "$row->product_name_4";
${$product_name[5]} = "$row->product_name_5";
${$product_name[6]} = "$row->product_name_6";
${$product_name[7]} = "$row->product_name_7";
// List 7 variables and values for each field name
echo "${$prop_name[$_GET['par']]}";
The only problem is that mysql injection is possible with this code. If anyone could suggest a solution, I would greatly appreciate it.

Script to match names submitted via a form with MySQL database breaks when name contains apostrophe

I have script that enters names into a MySQL database, using mysql_real_escape_string so that apostrophes are handled correctly. The trouble I am experiencing is with the script below that checks to see if names entered using another form correspond to names already in my database and if names are found updates the row.
When I try to enter a name with an apostrophe into the form processed by this script, I get an error message stating that the name wasn't found, and the name in the error message contains a backslash before the apostrophe, which is obviously the issue.
So the question is, how can I amend the script below so that it will work with names with apostrophes?
Thanks,
Nick
$row_count = count($_POST['name']);
if ($row_count > 0) {
mysql_select_db($database, $connection);
$name = array();
$workshop = array();
$not_found = array();
for($i = 0; $i < $row_count; $i++) {
// variable sanitation...
$name[$i] = mysql_real_escape_string(ucwords($_POST['name'][$i]));
$workshop[$i] = mysql_real_escape_string($_POST['workshop'][$i]);
}
$names = "('".implode("','",$name)."')";
$not_in = Array();
// lets say all names doesn't exist in `conference`
foreach($name as $value) {
// names in array are keys, not values
$not_in[$value] = true;
}
$query = mysql_query("SELECT Name FROM conference WHERE Name IN $names");
while(list($dbname) = #mysql_fetch_row($query)) {
// delete those name from $not_in who exists
unset($not_in[$dbname]);
}
// names in $not_in array are keys, not values
$not_in = array_keys($not_in);
if(empty($not_in)) {
// its ok, all names have been found. do the magic.
for($i = 0; $i < $row_count; $i++) {
$sql = "UPDATE conference SET Workshop = '$workshop[$i]' WHERE Name LIKE '$name[$i]'";
mysql_query($sql);
$body .= "Name: " . $name[$i] . " Workshop: " . $workshop[$i] . "\n\n";
}
Hmmm! I think I might have found the issue. The problem might not be with the query but with the PHP code. I'll try to explain below using your example John O'Shea.
for($i = 0; $i < $row_count; $i++) {
// variable sanitation...
$name[$i] = mysql_real_escape_string(ucwords($_POST['name'][$i]));
$workshop[$i] = mysql_real_escape_string($_POST['workshop'][$i]);
}
$names = "('".implode("','",$name)."')";
$not_in = Array();
// lets say all names doesn't exist in `conference`
foreach($name as $value) {
// names in array are keys, not values
$not_in[$value] = true;
}
After the above code, Array $not_in will contain escaped keys because $name already contains values escaped using mysql_real_escape_string(). Hence, for example:
$not_in[John] = true;
$not_in[John O\'Shea] = true;
$query = mysql_query("SELECT Name FROM conference WHERE Name IN $names");
while(list($dbname) = #mysql_fetch_row($query)) {
// delete those name from $not_in who exists
unset($not_in[$dbname]);
}
Now $dbname in the above code contains unescaped values retrieved from the DB, for example John O'Shea without the backslashes. Since this is not what $not_in contains, the unset() will not work. This means that all apostrophe values remain in the $not_in array.
So the fix is to keep unescaped values in $not_in.
Hope this makes sense!
========== EDIT: In response to how to keep unescaped values in $not_in:
The idea is to do escaping just where it is needed. Here are the changes that you may do to your code:
Rewrite the first for() as below:
for($i = 0; $i < $row_count; $i++) {
// variable sanitation...
//$name[$i] = mysql_real_escape_string(ucwords($_POST['name'][$i]));
$name[$i] = ucwords($_POST['name'][$i]);
$workshop[$i] = mysql_real_escape_string($_POST['workshop'][$i]);
}
$names = "('" . mysql_real_escape_string(implode("','",$name)) . "')";
And rewrite the UPDATE statement as:
$sql = "UPDATE conference SET Workshop = '$workshop[$i]' WHERE Name LIKE '" . mysql_real_escape_string($name[$i]) . "'";
By the way, According to your code, the UPDATE will not run if there is one name that does not exist in the database. Is it absolutely necessary to run the UPDATE only if all the $_POST['name'] are found in the database? If not, you can significantly reduce the amount of code.
I haven't tested the above changes but I think they should work. Let me know if you get any issues.
========== EDIT 2: Code snippet for updating records that exist and generating errors for records that did not
Hey Nick, I think only writing the below code should do the trick:
$row_count = count($_POST['name']);
if ($row_count > 0) {
mysql_select_db($database, $connection);
for ($i = 0; $i < $row_count; $i++) {
mysql_query("UPDATE conference SET Workshop = '" . mysql_real_escape_string($_POST['workshop'][$i]) . "' WHERE Name LIKE '" . mysql_real_escape_string($_POST['name'][$i]) . "'");
$affectedRows = mysql_affected_rows();
if ($affectedRows == 0) {
echo '<br>Name did not exist - ' . $_POST['name'][$i];
}
}
}
Hope this helps!

parse_str problems

I’m sorting a list and using Ajax to update a database. I need help parsing the string. This is the query string that I need to parse:
images_list[]=32&images_list[]=95&images_list[]=97&images_list[]=96&images_list[]=102&images_list[]=103&images_list[]=99&images_list[]=101&images_list[]=98&john=hi
I have put john=hi to test to see if the string is actually being sent via Ajax to the processor.php file. I am able to get the variable john=hi from the URL, so the query string is being sent perfectly fine. This is my code so far, but I can't seem to access the data I need, it appears as if nothing is there:
<?php
// Connect to the database
require_once('connect.php');
parse_str($_GET['images_list']);
for ($i = 0; $i < count($images_list); $i++) {
$id = $images_list[$i];
mysql_query("UPDATE images SET ranking = '$i' WHERE id = '$id'");
echo $images_list[$i];
}
?>
$_GET['images_list'] is an array of integers. There's nothing to parse there. PHP already did it for use. So, skip the parse_str part and easily use $_GET['images_list'] instead of $images_list.
Whole code:
<?php
//Connect to DB
require_once('connect.php');
foreach ($_GET['images_list'] as $i => $id) {
mysql_query("UPDATE images SET ranking = " .
mysql_real_escape_string($i) .
" WHERE id = " .
mysql_real_escape_string($id));
echo $id;
}
?>

Categories