Php ampersand seems not the same as mysql ampersand - php

Mysql query is
SELECT `IdDP`, `DescriptionOrName` FROM `table` WHERE `DescriptionOrName` = ?;
Instead of ? i use php value, received from another file (with ajax send value to current php file). If in Google Chrome click inspect, then i see such value gr art & print. And this value with ajax send to php file. But i get nothing from mysql.
If i use this
SELECT `IdDP`, `DescriptionOrName` FROM `table` WHERE `DescriptionOrName` = "gr art & print";
then all works.
All works also if i manually type gr art & print as php variable.
Compared from mysql selected gr art & print with php variable (received with ajax). Like
if( trim($val_select_ids_for_clicked_name['DescriptionOrName']) == trim(str_replace("&","&",$_POST['data_to_send']['clicked_name'])) ){
echo 'mysql == to php<br/>';
}
else{
echo 'mysql != to php<br/>';
}
And result is that mysql != to php
Seems finally found solution. For ? must use php like str_replace("&","&",trim($_POST['data_to_send']['clicked_name'])). In other words to replace & with &.
So does it mean that ajax (jquery) takes html value of & (html value is &) and sends & to php....? Are there more characters like this?

Related

How to call R script from PHP?

I have a bunch of R scripts that do some calculations and return a result. I am planning of building a PHP website that the user can actually submit a form where the data gets passed to my R script, processed and then return the result to the PHP and update the interface.
The plan is to have a database so when a user submits a form, the data gets stored in the database so R can read, process the input and then insert the result in the database so PHP can grab it. However, there are 2 problems:
How do my R script knows that certain values have been stored in the database so it can grab those values and do the processing?
When my R script finishes processing the data and insert it to mysql db, how do I get PHP to understand that at this moment PHP needs to query the database and grab the value?
Let's say my R script is like the following:
range<-1:20
m<-mean(range)
s<-sum(range)
print(m)
print(s)
As you can see the input at this case would be 1 and 20 to define the range, and the output is to show the values of m and s on my webpage.
Any idea how to accomplish that?
thanks!
shell_exec() or exec() are likely your best choices in PHP. This answer explains the difference.
echo shell_exec("Rscript my_script.R {$_GET['range']}");
I'm no r expert, but it's been done :
/ poorman.php
echo "
";
echo "Number values to generate:
";
echo "Submit";
echo ""
;
if(isset($_GET['N']))
{
$N = $_GET['N'];
// execute R script from shell
// this will save a plot at temp.png to the filesystem
exec("Rscript my_rscript.R $N");
// return image tag
$nocache = rand();
echo("");
}
?>
and the R script…
my_rscript.R
args <- commandArgs(TRUE)
N <- args[1]
x <- rnorm(N,0,1)
png(filename="temp.png", width=500, height=500)
hist(x, col="lightblue")
dev.off()
source

prevent "&" to &. encoding when save to database

I use sql server 2008 and I have PDO connection
$con = new \PDO("sqlsrv:Server={$config['server']};Database={$config['database']}", $config['username'], $config['password']);
$con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$con->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
What I want is, I need to save directory name containing "&" sign without converting to &
eg - directory name - "New & old"
when I save in database it converted to the "New & old". I want to stop this conversion. I what to save it as "New & old"
Here is the data saving code -
$stmt = $this->db->prepare( "SET NOCOUNT ON DECLARE #return_value int
EXEC #return_value = [dbo].[sp_update_t_Rfile2_RF2_Path]
#RF2_RfileID_pk_ind = ?, #RF2_Path = ?
SELECT 'Return Value' = #return_value
");
$return = null;
$stmt->bindParam(1,$fields['RF2_nd'],\PDO::PARAM_STR );
$stmt->bindParam(2,$fields['Path_New'],\PDO::PARAM_STR);
$stmt->execute();
I call to this code using POST request not any Ajax. When I print this $fields['Path_New'] before this code it return "New & old" correctly not happen any encoding at POST.
Database column data type is varchar(265) and I use IIS server for PHP 5.3
I have two systems working on same database one is Access system and other one is PHP web application. Access system not working with &
please help me to stop this encoding "&" to &
Thanks
Finally I found the solution for this, to stop saving & as a & we need to decode the html encoding (UTF-8).
(PHP 4 >= 4.3.0, PHP 5)
html_entity_decode — Convert all HTML entities to their applicable characters
more information - http://php.net/manual/en/function.html-entity-decode.php
Now I can save & without converting to &
My updated code is - #RK_Path = N'".\html_entity_decode($fields['txtRK_Path'])."',
Thanks.
You should use UTF-8 in all pages, php files, and collation database.
Also check this:
https://stackoverflow.com/a/11249695/1919749
Change the collation to UTF-8 in your MYSQL database as well as the encoding in your php script

Using data passed to PHP via .load() to execute database query

I am trying to get an AJAX query to work. Im passing data to a PHP script using:
$(".example").click(function(){
x = this.innerHTML;
$("#example").load("ajax.php",{"data":x});
});
If ajax.php just includes the following (did this as a test), everything is fine; I've passed JS data successfully to PHP.
echo $_POST['data'];
My goal is to query my DB using $_POST['data'] though. As another test, I made sure the DB connection was all ok. The following works:
$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=?");
$example->bind_param('s',$_SESSION['user_id']);
$example->execute();
$example->bind_result($x,$y,$z,$a);
while($example->fetch()){
echo '<h3>'.$x.'</h3>';
echo '<p>'.$y.'</p>';
echo '<p>'.$z.'</p>';
echo '<p>'.$a.'</p>';
}
When I amend the below lines however, nothing is returned from the script.
$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=? AND a=?");
$example->bind_param('ss',$_SESSION['user_id'],$_POST['data']);
The puzzling thing is that the data being passed from JS initially was obtained from the database. When I use alerts, the words are exactly the same as my my DB record.
Any suggestions? Could this be something to do with datatype? do I need to make sure $_POST['data'] is converted to a string somehow?
When I look in firebug, I see the following POST details ('Test Title' is the data used in my query)
Parameters
data Test Title
Source
data=+Test+Title
Do the + signs represent spaces? perhaps I need to trim a space from beginning of data?
This was due to white space. Fixed with the following:
$(".example").click(function(){
y = this.innerHTML;
x = y.trim();
$("#example").load("ajax.php",{"data":x});
});

How do I get PHP to convert a blank field in MySQL to "0"?

I have created a field in MySQL named "pid", which I use in PHP coding at the end of other variable names to indicate which of 7 template designs a user has created. The limit is 7, at which point they are given a message that they have reached their limit.
I have the code working EXCEPT when the field is blank (before user creates the first template). When I hard-code a "0" it works. But, obviously, I need to use the "{pid}" variable to pick up the template sequence in the database.
Here is the PHP:
<?PHP
$pid = {pid};
$total_templates = 7;
if ($total_templates > $pid) {
echo "<a href='create.template.php'><img src='create_template.png'></a>";
} else {
echo "<b style='color: #CC0000'>Your limit of $pid Templates has been reached";
}
?>
How do I get the code to convert a blank field in MySQL to "0" in conjunction with the above code?
If I understand your question, could you not set it to 0 if it is empty()?
$pid={pid};
if(empty($pid))
$pid = 0;
You can also set the default value for that field in mysql. If you are using phpAdmin, go to the table and click the "Change" action and set the default value there. If you need sql command to do this, I can get that for you too.
The best way is to set the default value in mysql to 0. Then you will have no issues.
You could always use intval in order to force it as an integer. See http://php.net/manual/en/function.intval.php.
if ($total_templates > intval($pid))
Although I would just set the default value of the pid field to 0 in MySQL.
You could use the ternary operator to set the $pid value
$pid = ({pid} != '' ? {pid} : '0');
If there is a real value on $pid it'll display it, else it'll display 0, I haven't tested this code.
A better approach would be to set a default value for that field in your SQL.
For more info about the ternary operator

PHP: If statements unintentionally causing multiple MySQL columns to update?

I have a form on a page containing:
a text entry box named teachername
a text entry box named day (in the format YYYY-MM-DD)
a selection box named "resource" with the options [Library 1 or Library 2]
a selection box with the values [1,2,3 and 4] named block.
My mysql database has the fields:
- Teacher
Library1block1
Library1block2
Library1block3
etc.
The data from the html page is passed onto a php page meant to match the resource and block with the correct mysql field, and update the field so that the data from the text entry box "teachername" is inserted into it.
if ($_POST['resource']="Library 1" and $_POST['block']="1")
{mysql_query(
"UPDATE Resources
SET Teacher='yes', Library1block1='$_POST[teachername]'
WHERE Date='$_POST[day]'");}
if ($_POST['resource']="Library 1" and $_POST['block']="2")
{mysql_query(
"UPDATE Resources
SET Teacher='yes', Library1block2='$_POST[teachername]'
WHERE Date='$_POST[day]'");}
Expected:
- Enter "Mr. Smith" into teachername text entry field, select "Library 1" and "1" within the selection menu, and enter "2012-03-16" in the text entry field named day
Data is stored and passed along to the php script
an if statement updates the database record containing the field matched by the "resource"
field and "block" field (library1b1, library1b2, etc) for the date entered in the day text field
the field is updated, and the subsequent if statements check to match up the entered data with the correct mysql field
Result:
All fields (not just the specified field) are updated according to the first if statement.
EX: Entering in "Mr. Smith" for teachername, selecting "Library 1", selecting "1" for the block, and entering "2012-03-16" for the date does not update only the Library1block1 field, but it also updates the Library1block2 and library2block1 fields.
The mysql statement, when entered directly into a mysql terminal, updates the singular field correctly, but the usage of this php code results in multiple updated rows.
Help please?
You are making a common mistake of using the assignment operator (=) rather than the equality operator (==). On lines that look like this:
if($_POST['resource']="Library 1")
Change them to use the comparison operator:
if($_POST['resource'] == "Library 1")
The folks who have given answers have done a good job, but I would like to add one little trick that I like to use sometimes (depending on the language, etc.)
Usually you will write an if statement as something like
if ( $var == 1 ) { do_stuff( $var ) }; //or whatever
This following simple little trick has made this potential mistake almost impossible for me to make (esp. with php).
Just switch the two around.
So instead of the usual:
if ( $var == 1 ) { do_stuff( $var ) }; //or whatever
Try this instead whenever you can:
if ( 1 == $var ) { do_stuff( $var ) }; //or whatever
I'm pretty sure php 5.2+ hasn't changed to the point that it no longer works, but even if you make the mortal mistake of using a single equals sign it should still work because you can't assign a value to a constant (numbers are constant values, right?).
I believe this relies on php's behavior of always processing code from left to right:
if ( 1 = $var ) { do_stuff( $var ) }; //or whatever
And you're golden! Since I started doing this over 5 years ago I have never run into this problem again. 1 is always 1, no matter what you do. This is a good way of thinking through your conditionals, loops, etc. in php.
The beauty of this is in its mind smacking simplicity. "$var" can be lots of things, but the number 1 is always the number 1. I'm sure this doesn't work for all languages, but for php, it's one I use a lot, and it's apparently a good habit anyway to structure your code this way.
You should use two equal signs like this in you if statements to compare values:
$_POST['resource']=="Library 1"
This will check if $_POST['resource'] equals (==) Library 1
A single equal sign assigns Library 1 to $_POST['resource']
You may check Comparison Operators on php.net for more information:
http://php.net/manual/en/language.operators.comparison.php
Edit:
You should also use mysql_real_escape_string() for user input value such as $_POST:
if ($_POST['resource'] == "Library 1" and $_POST['block'] == "2")
{
mysql_query(
"UPDATE Resources
SET
Teacher='yes',
Library1block1='".mysql_real_escape_string($_POST['teachername'])."'
WHERE
Date='".mysql_real_escape_string($_POST['day'])."'"
);
}

Categories