I'm having issues with apostrophes in GET arrays. I can't seem to escape single quotes. I've trawled through similar SO topics for over a day now with no luck. I think this may be something to do with my connection to the database as if I make a plain unconnected php page both addslashes and str_replace successfully escape single quotes in GET variables (mysqli_real_escape_string doesn't since there is no database connection).
PHP 5.2.17
Mysql 5.5.23
Magic_quotes is off
The connection:
DEFINE ('database', 'dbname');
DEFINE ('user', 'dbusername');
DEFINE ('pass', 'dbpassword');
DEFINE ('host', 'localhost');
$dbc = #mysqli_connect (host, user, pass, database) OR die ('Could not connect to database: ' . mysqli_connect_error() );
The database appears to be connected, select queries involving GET variables that do not have single quotes in work fine. However, now when a GET containing a single quote is passed, I can't seem to escape it.
print_r($_GET);
echo "<br><br>";
$text = "O'Reilly";
echo "Normal variable called text: " . $text . "<br>
addslashes(): " . addslashes($text) . "<br>
mysqli_real_escape_string(): " . mysqli_real_escape_string($dbc, $text) . "<br>
str_replace(): " . str_replace("'", "\'", $text) . "<br>
<br>";
echo "_GET variable: " . $_GET['breed'] . "<br>
addslashes(): " . addslashes($_GET['breed']) . "<br>
mysqli_real_escape_string(): " . mysqli_real_escape_string($dbc, $_GET['breed']) . "<br>
str_replace(): " . str_replace("'", "\'", $_GET['breed']) . "<br>
<br>";
$_GET['breed'] = "O'Conner";
echo "_GET variable with new value: " . $_GET['breed'] . "<br>
addslashes(): " . addslashes($_GET['breed']) . "<br>
mysqli_real_escape_string(): " . mysqli_real_escape_string($dbc, $_GET['breed']) . "<br>
str_replace(): " . str_replace("'", "\'", $_GET['breed']) . "<br>
<br>";
gives:
Array ( [breed] => Cirneco dell'Etna )
Normal variable called text: O'Reilly
addslashes(): O\'Reilly
mysqli_real_escape_string(): O\'Reilly
str_replace(): O\'Reilly
_GET variable: Cirneco dell'Etna
addslashes(): Cirneco dell'Etna
mysqli_real_escape_string(): Cirneco dell'Etna
str_replace(): Cirneco dell'Etna
_GET variable with new value: O'Conner
addslashes(): O\'Conner
mysqli_real_escape_string(): O\'Conner
str_replace(): O\'Conner
The single quote in Cirneco dell'Etna is definitely a single quote, not ` etc. I also tried urlencode() and urldecode() - it replaced spaces with + but did not escape the single quotes. The GETs need single quotes to make user-friendly URLs - usernames and (in this case) breed names for example; Cirneco dell%39Etna is not intuitive. It's not a complex site at all but single quotes crop up a lot as ownership is a major part of the site, so I'd like to work out what's happening!
I have tried switching to PDO but found it beyond me - I'm a novice programmer and my attempt at PDO was mind-boggling to troubleshoot - I can't tell whether errors in PDO are my typos, or a continuation of this same issue.
Many thanks.
EDIT
The select query (which works as expected for _GET variables without single quotes in) is constructed as follows:
$q = "SELECT breed_name, breed_type from b_breed
where breed_name = '" . $_GET['breed'] . "'
LIMIT 1";
$result = mysqli_query($dbc,$q);
if($result->num_rows == 0)
{
}
else
{
$row_breed = mysqli_fetch_array($result, MYSQLI_ASSOC);
{
echo "<h1>" . $row_breed['breed_name'] . " - " . $row_breed['breed_type'] . "</h1>";
}
}
I have tried including addslashes, mysqli_real_escape_string and str_replace (not at the same time) with the $_GET within the query, to no effect. If I echo $q, the single quote is never escaped.
SELECT breed_name, breed_type from b_breed where breed_name = 'Cirneco dell'Etna' LIMIT 1
Oddly, if I switch the double and single quotes so I have:
$q = 'SELECT breed_name, breed_type from b_breed
where breed_name = "' . $_GET['breed'] . '"
LIMIT 1';
SELECT breed_name, breed_type from b_breed where breed_name = "Cirneco dell'Etna" LIMIT 1
It still returns no rows on the page, although the echoed $q will return rows in PHPMyAdmin.
EDIT Solved!
It was changing the ' in the database to an ASCII character. Adding the following converted it back to ', which could then be escaped:
$_GET['breed'] = htmlspecialchars_decode($_GET['breed'], ENT_QUOTES);
You can check what are You getting from GET
try
$string = $_GET['breed'];
for ($i=0;$i<strlen($string);$i++) {
echo '<br>'.$string[$i].' : '.ord($string[$i]);
}
Related
The SQL field that I try to add is TIME format.
My table looks like this:
table example
The code that I use looks something like this:
<code>
$sql = mysql_query("SELECT sec_to_time(sum(durata)) as durata FROM invoiri WHERE inginer= '" . $inginer."' and data between '" . $data1."' and '" . $data2."'");
$assoc = mysql_fetch_array($sql);
echo "Total time by ".$inginer." in period (".$data1.")-(".$data2.") is: ".$assoc[durata]." hours";}}
</code>
And the output that I get is " 05:33:20 " when it should be " 02:00 "
You almost have the right solution there. The problem is that the durata column is also a TIME column, and SUM() works on integers not TIME.
To get the correct result you can use:
$sql = mysql_query('SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(`durata`))) AS `durata` FROM `invoiri` WHERE inginer= "' . $inginer. '" AND `data` BETWEEN "' . $data1 . '" AND "' . $data2 . '"';
$assoc = mysql_fetch_array($sql);
echo 'Total time by ' . $inginer . ' in period (' . $data1 . ')-(' . $data2 . ') is: ' . $assoc[durata] . ' hours';
Also, a few of other things that you can improve about your code:
Stop using the MySQL extension for PHP. It has been deprecated since PHP 5.5 and completely removed in PHP 7. Instead have a look at MySQLi or PDO.
Don't use " for strings where you don't use string interpolation. You can see how I replaced all of your " (double quote) with ' (single quote). String processing is faster if you use just single quotes as PHP isn't trying to find something to interpolate every time.
Try to have your MySQL code more organized and use backticks for column names, and capitalize all of the MySQL syntax. I have modified your code as an example.
I am currently developing a website with a list of names. Some of the names include apostrophes ' and I want to link them to a website using their name.
I want to link to the a url like:
example.com/ (their name)
And by doing that, I first replace " " with "+". So the links looks like: example.com/john+doe
But if the name is John'Doe it turns the url into just example.com/john
And skips the lastname.
How can I fix this? I tried changing ', \' etc, to html codes, to ', and more, but nothing seems to work.
Here is my current code:
$name = $row['name'];
$new_name = str_replace(
array("'", "'"),
array(" ", "+"),
$name
);
echo "<td>" . $name . " <a href='http://www.example.com/name=" . $new_name . "' target='_blank'></a>" . "</td>";
What I want it to look like:
John Doe Johnson ----> http://www.example.com/name=John+Doe+Johnson
John'Doe Johnson ----> http://www.example.com/name=John'Doe+Johnson
It changes the spaces to +, but how can I fix the apostrophes? Anyone knows?
You should be using PHP's function urlencode, php.net/manual/en/function.urlencode.php.
<?php
$name = $row['name'];
//$urlname = urlencode('John\'Doe Johnson');
$urlname = urlencode($name);
echo "<td>$name<a href='http://www.example.com/name=$urlname' target='_blank'>$name</a></td>";
Output:
<td>John%27Doe+Johnson <a href='http://www.example.com/name=John%27Doe+Johnson' target='_blank'></a></td>
echo urlencode("John'Doe Johnson");
return
John%27Doe+Johnson
So I'm working on an editor for a friend of mine, and I'm getting a strange Syntax error. It's strange because I'm currently creating an NPC editor using the shell of the Item editor I made a while back. That's saying I literally just changed the variables and changed everything that said 'item' to 'npc'. However, I'm getting a syntax error at a random column and I can't find out what the error is. It's in the editing section of the editor(lol). The delete and create parts of the editor work fine.
}else if($state == "edit")
{
$editsql = "UPDATE npcs SET name='" . $name . "', description='" . $description . "', gender=" . $gender . ", size=" . $size . ", dialog='" . $dialog . "', hair_style=" . $hair_style . ", hat=" . $hat . ", top=" . $top . ", bottom=" . $bottom . ", movement_pattern=" . $movement_pattern . ", behavior=" . $behavior . ", range=" . $range . ", uses_special_pokemon=" . $uses_special_pokemon . ", pokemon_1=" . $pokemon_1 . ", pokemon_2=" . $pokemon_2 . ", pokemon_3=" . $pokemon_3 . ", pokemon_4=" . $pokemon_4 . ", pokemon_5=" . $pokemon_5 . ", pokemon_6=" . $pokemon_6 . " WHERE id=" . $id;
this is the error:
Could not edit npc ID 3 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'range=0, uses_special_pokemon=0, pokemon_1=1, pokemon_2=1, pokemon_3=1, pokemon_' at line 1
I can't quite figure out what it's calling out near 'range' and range itself looks fine to me, so I don't see an error at all. It's most likely something completely obvious that I'm just overlooking as usual, but I'm stumped.
You'll want to rename range to range_, because Range is a SQL reserved word. You could enclose it in backticks, which are different than single quotes. ` VS ' ...
If you seperate the query into multiple lines your error message will tell you where it failed closer to where the actual error was. It's a one-liner, so it tells you error exists on line 1. Typically, seperate clauses, i.e.
select xxxx
from yyyy
where xxxx = zzzz
then you'll know it's an error in syntax and in what clause.
I have a PHP echo statement:
echo "stores[".$row['BarID']."] = [". $row['BarName'] . ", " . $row['Address']. ",". $row['City']. "," . $row['State']. " 0". $row['ZipCode']. "," . $row['PhoneNumber']. ",". $row['Lattitude']. ",".$row['Longitude']. "]". ";<br>";
which outputs:
stores[0] = [The Ale 'N 'Wich Pub , 246 Hamilton St ,New Brunswick,NJ 08901,732-745-9496 ,40.4964198,-74.4561079];
BUT I WOULD LIKE THE OUTPUT IN DOUBLE QUOTES SUCH AS:
stores[0]=["The Ale 'N 'Wich Pub", "246 Hamilton St, New Brunswick, NJ 08901", "732-745-9496 Specialty: Sport", "40.4964198", "-74.4561079"];
I Have looked at the PHP String Functions Manual on PHP site but still don't understand how i can implement it. Your help is appreciated.
The keyword you miss is "escaping" (see Wiki). Simplest example:
echo "\"";
would output:
"
EDIT
Basic explanation is - if you want to put double quote in double quote terminated string you MUST escape it, otherwise you got the syntax error.
Example:
echo "foo"bar";
^
+- this terminates your string at that position so remaining bar"
causes syntax error.
To avoid, you need to escape your double quote:
echo "foo\"bar";
^
+- this means the NEXT character should be processed AS IS, w/o applying
any special meaning to it, even if it normally has such. But now, it is
stripped out of its power and it is just bare double quote.
So your (it's part of the string, but you should get the point and do the rest yourself):
echo "stores[".$row['BarID']."] = [". $row['BarName'] . ", " . $row['Address'] .
should be:
echo "stores[".$row['BarID']."] = [\"". $row['BarName'] . "\", \"" . $row['Address']. "\"
and so on.
I wanted to write some variables to a file to include them in another script. But i get these errors while running the script:
Notice: Undefined variable: host in I:\xampp\htdocs\contact\install\writeconfig.php on line 2
Notice: Undefined variable: database in I:\xampp\htdocs\contact\install\writeconfig.php on line 2
Notice: Undefined variable: user in I:\xampp\htdocs\contact\install\writeconfig.php on line 2
Notice: Undefined variable: password in I:\xampp\htdocs\contact\install\writeconfig.php on line 2
HTML form:
<html>
<head>
<title>Contact installatie</title>
</head>
<body>
<h1>Contact installatie</h1>
<h2>Database gegevens:</h2>
<form name="databasesettings" action="writeconfig.php" method="post">
Host: <input type="text" name="host"> <br>
Database: <input type="text" name="database"> <br>
User: <input type="text" name="user"> <br>
Password: <input type="password" name="password"> <br>
<input type="submit" value="Generate config">
</form>
</body>
</html>
And PHP code:
<?php
$config = "$host = " . $_POST["host"] . "\n$database = " . $_POST["database"] . "\n$user = " . $_POST["user"] . "\n$password = " . $_POST["password"];
$configfile=fopen("config.txt","w+");
fwrite($configfile, $config);
fclose($configfile);
?>
Use single quotes for literal strings. Or escape them "\"
Options:
Escape the $ with a backslash \
Use single quotes instead
Examples:
$config = "\$host = " . $_POST["host"] . "\n\$database = " . $_POST["database"] . "\n\$user = " . $_POST["user"] . "\n\$password = " . $_POST["password"];
$config = '$host = ' . $_POST["host"] . "\n" . '$database = " . $_POST["database"] . "\n" . '$user = " . $_POST["user"] . "\n" . '$password = " . $_POST["password"];
When using single quotes special characters like \n will also need special consideration. I just put them in double quotes in my example but you can escape them as well.
You have two options to get around this problem.
Double quoted strings in PHP perform variable name replacement (and more advanced replacements when wrapped with curly braces). You can instead use single quoted strings to be able to use $ within it, like so:
$config = '$host = ' . $_POST["host"] . "\n" . '$database = ' . $_POST["database"] . "\n" . '$user = ' . $_POST["user"] . "\n" . '$password = ' . $_POST["password"];
Note that you will have to put the \ns into double quoted strings, otherwise it won't be replaced properly.
Another alternative is to escape (using \) your $s, like this:
$config = "\$host = " . $_POST["host"] . "\n\$database = " . $_POST["database"] . "\n\$user = " . $_POST["user"] . "\n\$password = " . $_POST["password"];
As a bonus, if you wanted to use the braces as I mentioned above, you could write your string like so:
$config = "\$host = {$_POST['host']}\n\$database = {$_POST['database']}\n\$user = {$_POST['user']}\n\$password = {$_POST['password']}";
That doesn't mean I would recommend you to do so, though :)
The best way to do this is probably using sprintf, which makes it slightly more readable like so:
$config = sprintf("\$host = %s\r\n\$database = %s\r\n\$user = %s\r\n\$password = %s",
$_POST['host'], $_POST['database'], $_POST['user'], $_POST['password']);
When using double quotes ( " ) to wrap a string, PHP will attempt to replace any variable names ($variable) in the string with their values. If you don't want PHP to do that, use single quotes ( ' ) to wrap the string.
For more information, read about string in the PHP manual:
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
http://php.net/manual/en/language.types.string.php#language.types.string.parsing
A side note, PHP won't do any interpreting of strings that use single quotes. So \n will not work in a single quoted string, it will need to be in a double quoted string.
"$var" will try to find variable $var;
Try to read this http://php.net/manual/en/language.types.string.php
When you use the '$' inside double quoted string, php assumes it as a variable and replaces it with it's value. So your options are escaping them using a '\' before it or use a single quoted string.
I recommend using a '\', as you can't always go for the second option.
I'm moving the reply as answer here. May be it'll help others.