473,396 Members | 1,987 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Interesting Discussion with my PHP Teacher

I'm doing a website development course and during an exercise my teacher
gave me to do at home I was confronted with errors. Surprisingly, those
that did the exercise in class did not receive these errors. I told him
about the errors and we concluded that this was happening due to the
computers in class running php 4.3.2 and my computer is running php 4.3.6.
However I was told the way I solved the problem was uneligant code. He said
I should not code the way I did, even though I based the code from examples
I read from various php websites, because I would have trouble if a form
passed many variables, or if I had to pass variables between files. I
thought the way I was doing it was the correct, neat and tidy way to do it,
but I was told that it was the way new learning php coders do it so they can
understand, and I shouldn't do it that way. The line of code in question is
below.

The Teacher's code:

<?php

//return to input page if not all fields have been entered
//header redirection must appear at the top of the page before any screen
output
if ((!$_POST[product_no]) || (!$_POST[product_name]) || (!$_POST[unit]) ||
(!$_POST[unit_price]) || (!$_POST[enquiry])) {
header('Location: add_record.htm');
exit;
}

//get connection info from include file on hostname, username, password,
and database name
include('connect_info.php');

//connect to MySQL server and store connection info in the variable
$connection
$connection = @mysql_connect($hostname, $username, $password) or
die('Cannot connect to MySQL server.');

//select database and store connection info in the variable $db_selected
$db_selected = @mysql_select_db($db_name, $connection) or die('Cannot
connect to database.');

//construct SQL statement
$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES ('$_POST[product_no]',
'$_POST[product_name]', '$_POST[unit]', '$_POST[unit_price]',
'$_POST[enquiry]')";

//execute SQL statement to insert record
@mysql_query($sql_statement, $connection) or die('Cannot query table.');

?>
----------------------------------------------------------------------------
---------
Errors caused in php 4.3.6 by this code:

Notice: Use of undefined constant product_no - assumed 'product_no' in
C:\Inetpub\wwwroot\class_work\original_do_add_reco rd.php on line 5

Notice: Use of undefined constant product_name - assumed 'product_name' in
C:\Inetpub\wwwroot\class_work\original_do_add_reco rd.php on line 5

Notice: Use of undefined constant unit - assumed 'unit' in
C:\Inetpub\wwwroot\class_work\original_do_add_reco rd.php on line 5

Notice: Use of undefined constant unit_price - assumed 'unit_price' in
C:\Inetpub\wwwroot\class_work\original_do_add_reco rd.php on line 5

Notice: Use of undefined constant enquiry - assumed 'enquiry' in
C:\Inetpub\wwwroot\class_work\original_do_add_reco rd.php on line 5
------------------------------------------------------------------------
My code:
<?php

$product_no = $_POST['product_no']; // This is the part of the
code the teacher didnt like
$product_name = $_POST['product_name'];
$unit = $_POST['unit'];
$unit_price = $_POST['unit_price'];
$enquiry = $_POST['enquiry'];
//return to input page if not all fields have been entered
//header redirection must appear at the top of the page before any screen
output
if (!$product_no || !$product_name || !$unit || !$unit_price || !$enquiry)
{
header('Location: add_record.htm');
exit;
}

//get connection info from include file on hostname, username, password,
and database name
include('connect_info.php');

//connect to MySQL server and store connection info in the variable
$connection
$connection = @mysql_connect($hostname, $username, $password) or
die('Cannot connect to MySQL server.');

//select database and store connection info in the variable $db_selected
$db_selected = @mysql_select_db($db_name, $connection) or die('Cannot
connect to database.');

//construct SQL statement
$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES ('$product_no', '$product_name', '$unit',
'$unit_price', '$enquiry')";

//execute SQL statement to insert record
@mysql_query($sql_statement, $connection) or die('Cannot query table.');

?>
----------------------------------------------------------------------------
-------

So is my code really that bad? How can I get the code to work if my way
really is that bad? I think the reason why the teacher's code is giving me
errors in php 4.3.6 is because the code does not quote in the posted form
values. For example $_POST[product_no] instead of $_POST['product_no'].
This can be easily fixed on line 5 where the error occurs, but I can't fix
it wher the sql statement is constructed because there are too many quotes.
For example:

$sql_statement = "INSERT INTO product_table(product_no, product_name, unit,
unit_price, enquiry) VALUES ('$_POST[product_no]', '$_POST[product_name]',
'$_POST[unit]', '$_POST[unit_price]', '$_POST[enquiry]')";

needs to be:

$sql_statement = "INSERT INTO product_table(product_no, product_name, unit,
unit_price, enquiry) VALUES ('$_POST['product_no']',
'$_POST['product_name']', '$_POST['unit']', '$_POST['unit_price']',
'$_POST['enquiry']')";

which of course will give you a parse error.

I eagerly await everyone's opinions on this :)

--
-Robert Smith
----------------------------------------------------------------------------
---------------------------------
Remove 'nospam.' from my email address if you wish to reply via email.
Jul 17 '05 #1
13 2400
In article <40**********************@news.optusnet.com.au>, Robert Smith wrote:
if ((!$_POST[product_no]) || (!$_POST[product_name]) || (!$_POST[unit]) ||
(!$_POST[unit_price]) || (!$_POST[enquiry])) {
Imho, it's cleaner to use isset($_POST['product_no'])

header('Location: add_record.htm');
This breaks HTTP/1.1, for more info read RFC 2616
http://www.w3.org/Protocols/rfc2616/....html#sec14.30
$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES ('$_POST[product_no]',
'$_POST[product_name]', '$_POST[unit]', '$_POST[unit_price]',
'$_POST[enquiry]')";


Without having magic quotes on (or at least testing if they are on) it
is not a good idea to put these values directly in the database.

--
Tim Van Wassenhove <http://home.mysth.be/~timvw/contact.php>
Jul 17 '05 #2

"Robert Smith" <us***************@nospam.optusnet.com.au> wrote in message
news:40**********************@news.optusnet.com.au ...
I'm doing a website development course and during an exercise my teacher
gave me to do at home I was confronted with errors. Surprisingly, those
that did the exercise in class did not receive these errors. I told him
about the errors and we concluded that this was happening due to the
computers in class running php 4.3.2 and my computer is running php 4.3.6.
However I was told the way I solved the problem was uneligant code. He said I should not code the way I did, even though I based the code from examples I read from various php websites, because I would have trouble if a form
passed many variables, or if I had to pass variables between files. I
thought the way I was doing it was the correct, neat and tidy way to do it, but I was told that it was the way new learning php coders do it so they can understand, and I shouldn't do it that way. The line of code in question is below.

The Teacher's code:

<?php

//return to input page if not all fields have been entered
//header redirection must appear at the top of the page before any screen output
if ((!$_POST[product_no]) || (!$_POST[product_name]) || (!$_POST[unit]) || (!$_POST[unit_price]) || (!$_POST[enquiry])) {
header('Location: add_record.htm');
exit;
}

//get connection info from include file on hostname, username, password,
and database name
include('connect_info.php');

//connect to MySQL server and store connection info in the variable
$connection
$connection = @mysql_connect($hostname, $username, $password) or
die('Cannot connect to MySQL server.');

//select database and store connection info in the variable $db_selected
$db_selected = @mysql_select_db($db_name, $connection) or die('Cannot
connect to database.');

//construct SQL statement
$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES ('$_POST[product_no]',
'$_POST[product_name]', '$_POST[unit]', '$_POST[unit_price]',
'$_POST[enquiry]')";

//execute SQL statement to insert record
@mysql_query($sql_statement, $connection) or die('Cannot query table.');

?>
-------------------------------------------------------------------------- -- ---------
Errors caused in php 4.3.6 by this code:

Notice: Use of undefined constant product_no - assumed 'product_no' in
C:\Inetpub\wwwroot\class_work\original_do_add_reco rd.php on line 5

Notice: Use of undefined constant product_name - assumed 'product_name' in
C:\Inetpub\wwwroot\class_work\original_do_add_reco rd.php on line 5

Notice: Use of undefined constant unit - assumed 'unit' in
C:\Inetpub\wwwroot\class_work\original_do_add_reco rd.php on line 5

Notice: Use of undefined constant unit_price - assumed 'unit_price' in
C:\Inetpub\wwwroot\class_work\original_do_add_reco rd.php on line 5

Notice: Use of undefined constant enquiry - assumed 'enquiry' in
C:\Inetpub\wwwroot\class_work\original_do_add_reco rd.php on line 5
------------------------------------------------------------------------
My code:
<?php

$product_no = $_POST['product_no']; // This is the part of the
code the teacher didnt like
$product_name = $_POST['product_name'];
$unit = $_POST['unit'];
$unit_price = $_POST['unit_price'];
$enquiry = $_POST['enquiry'];
//return to input page if not all fields have been entered
//header redirection must appear at the top of the page before any screen output
if (!$product_no || !$product_name || !$unit || !$unit_price || !$enquiry) {
header('Location: add_record.htm');
exit;
}

//get connection info from include file on hostname, username, password,
and database name
include('connect_info.php');

//connect to MySQL server and store connection info in the variable
$connection
$connection = @mysql_connect($hostname, $username, $password) or
die('Cannot connect to MySQL server.');

//select database and store connection info in the variable $db_selected
$db_selected = @mysql_select_db($db_name, $connection) or die('Cannot
connect to database.');

//construct SQL statement
$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES ('$product_no', '$product_name', '$unit', '$unit_price', '$enquiry')";

//execute SQL statement to insert record
@mysql_query($sql_statement, $connection) or die('Cannot query table.');

?>
-------------------------------------------------------------------------- -- -------

So is my code really that bad? How can I get the code to work if my way
really is that bad? I think the reason why the teacher's code is giving me errors in php 4.3.6 is because the code does not quote in the posted form
values. For example $_POST[product_no] instead of $_POST['product_no'].
This can be easily fixed on line 5 where the error occurs, but I can't fix
it wher the sql statement is constructed because there are too many quotes. For example:

$sql_statement = "INSERT INTO product_table(product_no, product_name, unit, unit_price, enquiry) VALUES ('$_POST[product_no]', '$_POST[product_name]',
'$_POST[unit]', '$_POST[unit_price]', '$_POST[enquiry]')";

needs to be:

$sql_statement = "INSERT INTO product_table(product_no, product_name, unit, unit_price, enquiry) VALUES ('$_POST['product_no']',
'$_POST['product_name']', '$_POST['unit']', '$_POST['unit_price']',
'$_POST['enquiry']')";

which of course will give you a parse error.

I eagerly await everyone's opinions on this :)

--
-Robert Smith


Are you omitting define("product_no","product_no") and such? Why is he using
constants as array keys anyway? Use strings like you are.

Is he objecting fundamentally to recasting array values as variables purely
for clarity?

Your teacher is trying to inflict a coding style on you - coding is half art
and half logic, and your sense of art is in conflict with his. From
experience, take it on board, do what you need to do to pass the course then
change right back to being you - you will learn what's right or wrong, easy
or hard for yourself with practise.

For what it's worth, I think your style is easier to read as a third party
than his and in the learning stages, that's worth a whole extra grade
because you understand it.

Garp
Jul 17 '05 #3
> "Robert Smith" <us***************@nospam.optusnet.com.au> wrote in message
news:40**********************@news.optusnet.com.au ...

<sniiiiiip>

Oops, forgot to trim the quote. Apologies.

Garp
Jul 17 '05 #4
Robert Smith wrote:
The Teacher's code:
I'm not going to comment on the teacher's code :-)
(snip teacher's code)
My code:
My comments are preceded with ##
<?php

$product_no = $_POST['product_no']; // This is the part of the
// code the teacher didnt like
$product_name = $_POST['product_name'];
$unit = $_POST['unit'];
$unit_price = $_POST['unit_price'];
$enquiry = $_POST['enquiry'];

## You already have the variables available,
## no need to create another set just to make it easier
## to write the code.
## For a small script like this one, it isn't that much different
## using $product_name or $_POST['product_name'];
## but as your scripts grow larger, I think it helps to keep the
## variables separate

//return to input page if not all fields have been entered
//header redirection must appear at the top of the page before any screen
//output
if (!$product_no || !$product_name || !$unit || !$unit_price || !$enquiry)
{
header('Location: add_record.htm');
exit;

## some browsers may not follow the redirect;
## allow them to continue anyway (I usually output a
## complete HTML page: html, head, title, body)
exit('Redirected <a href="add_record_htm">here</a>.');

## Oh! and the URL should be a complete one, at least in the
## header() call
## header('Location: http://www.yourserver.com/add_record.htm');

}

//get connection info from include file on hostname, username, password,
//and database name
include('connect_info.php');

## if, for some reason, connect_info.php cannot be read, instead of
## continuing running the script (with a warning) halt with
## a fatal error.
require 'connect_info.php';

## or
## require_once 'connect_info.php';

//connect to MySQL server and store connection info in the variable
//$connection
$connection = @mysql_connect($hostname, $username, $password) or
die('Cannot connect to MySQL server.');

//select database and store connection info in the variable $db_selected
$db_selected = @mysql_select_db($db_name, $connection) or die('Cannot
connect to database.');

//construct SQL statement
$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES ('$product_no', '$product_name', '$unit',
'$unit_price', '$enquiry')";

//execute SQL statement to insert record
@mysql_query($sql_statement, $connection) or die('Cannot query table.');

## ... or die('whatever ' . mysql_error());

## unless you want to hide the errors from your users (which is a good
## idea!), but then it's better to log the error somewhere instead of
## just dying with a constant message

## $resource = mysql_*(...);
## if (!$resource) {
## some_logging_function(mysql_error());
## die('Error message');
## }

?>
----------------------------------------------------------------------------
-------

So is my code really that bad? How can I get the code to work if my way
really is that bad? I think the reason why the teacher's code is giving me
errors in php 4.3.6 is because the code does not quote in the posted form
values. For example $_POST[product_no] instead of $_POST['product_no'].
This can be easily fixed on line 5 where the error occurs, but I can't fix
it wher the sql statement is constructed because there are too many quotes.
For example:

$sql_statement = "INSERT INTO product_table(product_no, product_name, unit,
unit_price, enquiry) VALUES ('$_POST[product_no]', '$_POST[product_name]',
'$_POST[unit]', '$_POST[unit_price]', '$_POST[enquiry]')";

needs to be:

$sql_statement = "INSERT INTO product_table(product_no, product_name, unit,
unit_price, enquiry) VALUES ('$_POST['product_no']',
'$_POST['product_name']', '$_POST['unit']', '$_POST['unit_price']',
'$_POST['enquiry']')";

which of course will give you a parse error.

## Use { } to delimit array variables inside double quotes

$sql_statement = "INSERT INTO product_table(product_no, product_name, unit,
unit_price, enquiry) VALUES ('{$_POST['product_no']}',
'{$_POST['product_name']}', '{$_POST['unit']}', '{$_POST['unit_price']}',
'{$_POST['enquiry']}')";

--
USENET would be a better place if everybody read: : mail address :
http://www.catb.org/~esr/faqs/smart-questions.html : is valid for :
http://www.netmeister.org/news/learn2quote2.html : "text/plain" :
http://www.expita.com/nomime.html : to 10K bytes :
Jul 17 '05 #5
On 2004-05-31, Robert Smith <us***************@nospam.optusnet.com.au> wrote:
if ((!$_POST[product_no]) || (!$_POST[product_name]) || (!$_POST[unit]) ||
(!$_POST[unit_price]) || (!$_POST[enquiry])) {
Please remember that constants are invalid here, but...
$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES ('$_POST[product_no]',
'$_POST[product_name]', '$_POST[unit]', '$_POST[unit_price]',
'$_POST[enquiry]')";


They're perfectly valid in a string context, because...

$_POST values (I would prefer $_REQUEST, though) are hashes with string keys.
Fine that it's fixed in later versions of PHP.
In string contextes however you can't refer to keys with strings as you are
in a string context itself. Thus you can omit the quotes.

Your code should use this version:
$product_no = isset($_POST['product_no'])?$_POST['product_no']:NULL;

This wouldn't even raise notices if fascist error reporting is on. It's then
perfectly safe to use this. Probably he (the teacher) remembers
register_globals, which /is/ unsafe when the variables are not initialised.

Bye,
phil
--
Please send replys (not followups) to the address set in Reply-To.
Philipp Kern - PK2186-RIPE - http://www.philkern.de
Jul 17 '05 #6
On Mon, 31 May 2004 18:47:59 +1000, "Robert Smith"
<us***************@nospam.optusnet.com.au> wrote:
$sql_statement = "INSERT INTO product_table(product_no, product_name, unit,
unit_price, enquiry) VALUES ('$_POST[product_no]', '$_POST[product_name]',
'$_POST[unit]', '$_POST[unit_price]', '$_POST[enquiry]')";

needs to be:

$sql_statement = "INSERT INTO product_table(product_no, product_name, unit,
unit_price, enquiry) VALUES ('$_POST['product_no']',
'$_POST['product_name']', '$_POST['unit']', '$_POST['unit_price']',
'$_POST['enquiry']')";

which of course will give you a parse error.


I personally prefer not to rely on PHP's interpolation and concatenate
the values:

$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES
('".addslashes($_POST["product_no"].',
'".addslashes($_POST["product_name"]."', ...";

It may look a bit uglier, but it means my syntax highlighter correctly
hightlights everything.

--
David ( @priz.co.uk )
Jul 17 '05 #7

"David Mackenzie" <me@privacy.net> wrote in message
news:qs********************************@4ax.com...
On Mon, 31 May 2004 18:47:59 +1000, "Robert Smith"
<us***************@nospam.optusnet.com.au> wrote:
<snip>
I personally prefer not to rely on PHP's interpolation and concatenate
the values:

$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES
('".addslashes($_POST["product_no"].',
'".addslashes($_POST["product_name"]."', ...";

It may look a bit uglier, but it means my syntax highlighter correctly
hightlights everything.

--
David ( @priz.co.uk )


Me too, but I do it by constructing arrays and using join(",",$values).

Garp

Jul 17 '05 #8
I noticed that Message-ID:
<40**********************@news.optusnet.com.au> from Robert Smith
contained the following:
I'm doing a website development course and during an exercise my teacher
gave me to do at home I was confronted with errors. Surprisingly, those
that did the exercise in class did not receive these errors. I told him
about the errors and we concluded that this was happening due to the
computers in class running php 4.3.2 and my computer is running php 4.3.6.
However I was told the way I solved the problem was uneligant code.


I don't think anyone has mentioned this but it looks like a different
level of error reporting. You can solve the problem at home by using
!isset($_POST['input']) instead of !$_POST['input'] and show your
teacher the error of his ways by putting error_reporting(E_ALL); at the
beginning of your class scripts.

In short, you were both wrong. For a small value of wrong.

--
Geoff Berrow (put thecat out to email)
It's only Usenet, no one dies.
My opinions, not the committee's, mine.
Simple RFDs http://www.ckdog.co.uk/rfdmaker/
Jul 17 '05 #9
"Philipp Kern" <tr***@philkern.de> wrote in message
news:sl******************@o2.net.philkern.de...
On 2004-05-31, Robert Smith <us***************@nospam.optusnet.com.au> wrote:
if ((!$_POST[product_no]) || (!$_POST[product_name]) || (!$_POST[unit]) || (!$_POST[unit_price]) || (!$_POST[enquiry])) {


Please remember that constants are invalid here, but...
$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES ('$_POST[product_no]',
'$_POST[product_name]', '$_POST[unit]', '$_POST[unit_price]',
'$_POST[enquiry]')";


They're perfectly valid in a string context, because...

$_POST values (I would prefer $_REQUEST, though) are hashes with string

keys. Fine that it's fixed in later versions of PHP.
In string contextes however you can't refer to keys with strings as you are in a string context itself. Thus you can omit the quotes.

Your code should use this version:
$product_no = isset($_POST['product_no'])?$_POST['product_no']:NULL;

This wouldn't even raise notices if fascist error reporting is on. It's then perfectly safe to use this. Probably he (the teacher) remembers
register_globals, which /is/ unsafe when the variables are not

initialised.

I wan't to thank everyone for their responses, they have been helpful. I
wonder if you could explain this part a little clearer, as it is the main
part of the problem. I did some research and I found this page
http://au2.php.net/manual/en/function.addslashes.php . It says "The PHP
directive magic_quotes_gpc is on by default, and it essentially runs
addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on
strings that have already been escaped with magic_quotes_gpc as you'll then
do double escaping. The function get_magic_quotes_gpc() may come in handy
for checking this." I have checked phpinfo() and at home and at the lab we
work in magic quotes gpc is on. So doing further testing showed that:

$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES ('$_POST[product_no]',
'$_POST[product_name]', '$_POST[unit]', '$_POST[unit_price]',
'$_POST[enquiry]')";

is perfectly legal but:

if (!$_POST[product_no] || !$_POST[product_name] || !$_POST[unit] ||
!$_POST[unit_price] || !$_POST[enquiry]) {

is not legal. I don't get it. I understand that in the if statement it
thinks that product_no is a constant, when it should be a string, and I
understand adding quotes here solves my problem, but I don't see the logic
in why it automatically quotes me in one part of the code, but not the
other.
--
-Robert Smith
----------------------------------------------------------------------------
---------------------------------
Remove 'nospam.' from my email address if you wish to reply via email.
Jul 17 '05 #10

"Pedro Graca" <he****@hotpop.com> wrote in message
news:sl*******************@ID-203069.user.uni-berlin.de...
## Use { } to delimit array variables inside double quotes

$sql_statement = "INSERT INTO product_table(product_no, product_name, unit, unit_price, enquiry) VALUES ('{$_POST['product_no']}',
'{$_POST['product_name']}', '{$_POST['unit']}', '{$_POST['unit_price']}',
'{$_POST['enquiry']}')";


I see how that works. I tried:
$sql_statement = "INSERT INTO product_table(product_no, product_name, unit,
unit_price, enquiry) VALUES (\'$_POST['product_no']\',
\'$_POST['product_name']\', \'$_POST['unit']\', \'$_POST['unit_price']\',
\'$_POST['enquiry']\')";

thinking that would work, but it seems I don't understand escape characters
because it fails miserably. Why doesn't that work?

--
-Robert Smith
----------------------------------------------------------------------------
---------------------------------
Remove 'nospam.' from my email address if you wish to reply via email.
Jul 17 '05 #11
Robert Smith wrote:
I did some research and I found this page
http://au2.php.net/manual/en/function.addslashes.php . It says "The PHP
directive magic_quotes_gpc is on by default, and it essentially runs
addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on
strings that have already been escaped with magic_quotes_gpc as you'll then
do double escaping. The function get_magic_quotes_gpc() may come in handy
for checking this." I have checked phpinfo() and at home and at the lab we
work in magic quotes gpc is on. So doing further testing showed that:

$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES ('$_POST[product_no]',
'$_POST[product_name]', '$_POST[unit]', '$_POST[unit_price]',
'$_POST[enquiry]')";

is perfectly legal but:

if (!$_POST[product_no] || !$_POST[product_name] || !$_POST[unit] ||
!$_POST[unit_price] || !$_POST[enquiry]) {

is not legal.
This has nothing to do with addslashes() or magic_quotes
I don't get it. I understand that in the if statement it
thinks that product_no is a constant, when it should be a string, and I
understand adding quotes here solves my problem, but I don't see the logic
in why it automatically quotes me in one part of the code, but not the
other.


This is the way PHP deals with quoted strings:
http://www.php.net/manual/en/language.types.string.php

$name = 'Pedro';
$temp = "My name is $name.";

This works ok and $temp is assigned the string "My name is Pedro."
With arrays it gets more complicated :-)

$names['myself'] = 'Pedro';
$temp = "My name is $names[myself]";

OK, too (though not the way I like to code it). PHP interprets the
$names[myself] as $names['myself'] because it is *inside* the double
quotes.

$temp = 'My name is ' . $names['myself'] . '.';

Now, $names['myself'] is not inside double quotes, so it needs to be
written in full.

$temp = "My name is {$names['myself']}.";

Use the full name inside double quotes by surrounding the variable with
the braces.

To avoid (or rather, minimize) all these complications, I only use
double quotes sparingly. Examples:

echo "</div>\n"; # newline
$sql = "select count(*) from dbuser where name='$name'";
echo 'Found ', $num, " records.<br/>\n";

HTH
--
USENET would be a better place if everybody read: : mail address :
http://www.catb.org/~esr/faqs/smart-questions.html : is valid for :
http://www.netmeister.org/news/learn2quote2.html : "text/plain" :
http://www.expita.com/nomime.html : to 10K bytes :
Jul 17 '05 #12
Regarding this well-known quote, often attributed to Garp's famous "Mon, 31
May 2004 10:48:46 GMT" speech:
"David Mackenzie" <me@privacy.net> wrote in message
news:qs********************************@4ax.com...
On Mon, 31 May 2004 18:47:59 +1000, "Robert Smith"
<us***************@nospam.optusnet.com.au> wrote:

<snip>

I personally prefer not to rely on PHP's interpolation and concatenate
the values:

$sql_statement = "INSERT INTO product_table(product_no, product_name,
unit, unit_price, enquiry) VALUES
('".addslashes($_POST["product_no"].',
'".addslashes($_POST["product_name"]."', ...";

It may look a bit uglier, but it means my syntax highlighter correctly
hightlights everything.

--
David ( @priz.co.uk )


Me too, but I do it by constructing arrays and using join(",",$values).

Garp


Hmm... I like that... that one's going in the ol' brain file for later.

--
-- Rudy Fleminger
-- sp@mmers.and.evil.ones.will.bow-down-to.us
(put "Hey!" in the Subject line for priority processing!)
-- http://www.pixelsaredead.com
Jul 17 '05 #13
Thankyou so much for your help. Everything is so much clearer now.

--
-Robert Smith
----------------------------------------------------------------------------
---------------------------------
Remove 'nospam.' from my email address if you wish to reply via email.
Jul 17 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Nick Coghlan | last post by:
Thought some folks here might find this one interesting. No great revelations, just a fairly sensible piece on writing readable code :) The whole article:...
1
by: violetgorman | last post by:
Hello..! My name is Violet.! I am new to this forum and I am really excited about this Discussion and would love any kind of guidance. I hope someone can help me with this question that I have..I...
40
by: nufuhsus | last post by:
Hello all, First let me appologise if this has been answered but I could not find an acurate answer to this interesting problem. If the following is true: C:\Python25\rg.py>python Python...
12
by: Daniel Earwicker | last post by:
I wrote two trivial test programs that do a billion iterations of a virtual method call, first in C# (Visual Studio 2005): Thing t = new DerivedThing(); for (System.Int64 n = 0; n < 10000000000;...
2
by: vikram.lakhotia | last post by:
Hi, Yesterday I was discussion with my colleagues about session and a few interesting things popped up. So I thought I would share the same with all. <a href=http://www.vikramlakhotia.com/...
66
by: prady | last post by:
hi all, could any one solve the following C program. If any one knows the answer please post it Ques: A C function that will print 1 to N one per each line on the stdout , where N is a int...
10
by: jacob navia | last post by:
There is a very interesting thread in comp.lang.c++ about garbage collection. It is very instructive to compare the level of the discussion there with the discussion we just had here in...
1
by: Ivan Illarionov | last post by:
On Mar 19, 2:17 pm, "BJörn Lindqvist" <bjou...@gmail.comwrote: I really want to revive this discussion. Arnaud's approach is definetly cool, but it turns out that in real-world situations it...
126
by: jacob navia | last post by:
Buffer overflows are a fact of life, and, more specifically, a fact of C. All is not lost however. In the book "Value Range Analysis of C programs" Axel Simon tries to establish a...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.