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.
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.
When i echo "$time"; - The output is 2015-07-27 18:17:47
But i need to output as "2015-07-27 18:17:47".
I have been trying various string concatenations such as : echo "."$time"."; But couldn't get the desired output? What is the best way to do it?
Try this concatenation
echo '"' . $time . '"';
or use printf() like so
printf('"%s"', $time);
Just escape them:
echo "\"$time\"";
You could also use single around the double quotes:
echo '"' . $time . '"';
See here for more info on escape sequences when using double quotes.
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 want to create an HTML Message to send an email in PHP.
$message = $mess0 . "</br>" . $mess1 . "</br>" . $mess2 . "</br>" . $mes1 . "</br></br>" . $mes2 . "</br>" . $mes23 . "</br></br>" . $mes3 . "</br></br>" . $mes4 . "</br>" . $mes5 . "</br>" . $mes6 . "</br>" . $mes7 . "</br>" . $mes8 . "</br>" . $mes9 . "</br></br>" . $mes10 ;
$message = <html><body><p>$message</p></body></html>;
Here are some variables.
I am getting the following error.
Parse error: syntax error, unexpected '<' in /home/thevowaa/public_html/iphoneapp/webservice/file.php on line 214
Add HTML tags between double quotes.
$message = "<html><body><p>".$message."</p></body></html>";
Where are the double quotes see below
$message = "<html><body><p>$message</p></body></html>";
There are two possible ways to hold HTML in PHP variable. You can use single quote or double quotes. You also need to put a dot(.) before and after single/double quotes. Your PHP string could be constructed in following two ways:
$message = '<html><body><p>'.$message.'</p></body></html>';
or like this,
$message = "<html><body><p>".$message."</p></body></html>";
Also, use of single quotes(') is encouraged in PHP coding because it's doesn't clash with javascript or css double quotes(") when constructing html pages using PHP.
For more information on usage of quotes in PHP, check out this stackoverflow answer
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]);
}