473,598 Members | 3,266 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with variable interpolation in WHER clause

I am a MySQL and PHP newbie. I am having trouble getting the $w variable in
my code below passed to mysql. When I use the value of $w directly in the
Where clause, the correct rows are returned. However, when I try to use the
variable in the Where clause, either an error occurs or no rows are
returned. Any thoughts greatly appreciated!

I am using php-4.4.2 and MySQL-4.1.18-0 on Suse 9.1

Jerry

<html>
<body>
<?php
$link = mysql_connect(' localhost:3306' , 'mysql');
mysql_select_db ('test_ermd') or die('Could not select database');
$w = 'exec';
// I have tried all the variations below to get the value of $w to process
in the WHERE clause
//------------------------------------------------------------------------------------------
//$query = 'SELECT TITLE, NAME, INST, ADD1, ADDR2, ADDR3, PH, FAX, EMAIL
FROM officers WHERE GRP = "exec"';
//--This works: all rows with 'exec' in GRP column are selected

//$query = 'SELECT TITLE, NAME, INST, ADD1, ADDR2, ADDR3, PH, FAX, EMAIL
FROM officers WHERE GRP = $w';
//--Invalid query: Unknown column '$w' in 'where clause'
//--Whole query: SELECT TITLE, NAME, INST, ADD1, ADDR2, ADDR3, PH, FAX,
EMAIL FROM officers WHERE GRP = $w

//$query = 'SELECT TITLE, NAME, INST, ADD1, ADDR2, ADDR3, PH, FAX, EMAIL
FROM officers WHERE GRP = \"$w\"';
//--Invalid query: 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 '\"$w\"' at line 1
//--Whole query: SELECT TITLE, NAME, INST, ADD1, ADDR2, ADDR3, PH, FAX,
EMAIL FROM officers WHERE GRP = \"$w\"

//$query = 'SELECT TITLE, NAME, INST, ADD1, ADDR2, ADDR3, PH, FAX, EMAIL
FROM officers WHERE GRP = \$w';
//--Parse error: syntax error, unexpected T_STRING
in /usr/local/bin/apache2/htdocs/test_ermd.php on line 34

//$query = 'SELECT TITLE, NAME, INST, ADD1, ADDR2, ADDR3, PH, FAX, EMAIL
FROM officers WHERE GRP = "\$w"';
//--No rows are selected

//$query = 'SELECT TITLE, NAME, INST, ADD1, ADDR2, ADDR3, PH, FAX, EMAIL
FROM officers WHERE GRP = \'$w\'';
//--No rows are selected
//------------------------------------------------------------------------------------------

echo 'Raw query: ' . $query;
$result = mysql_query($qu ery);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "<br>";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysql_fetch_ass oc($result)) {
foreach ($row as $key => $value) {
if ($value) {
echo "$value";
echo "<br>";
}
}
echo "<p>";
}
mysql_free_resu lt($result);
mysql_close($li nk);
?>
</body>
</html>
//=============== =============== =============== =============== ========
May 18 '06 #1
8 2836
> //$query = 'SELECT TITLE, NAME, INST, ADD1, ADDR2, ADDR3, PH, FAX, EMAIL
FROM officers WHERE GRP = $w';


When a string is between 'single quotes', variables are not parsed.
This means that after
$query = 'SELECT $w'
The variable query literaly contains SELECT $w. To use the value of the
variable w instead, use double quotes:
$query = "SELECT $w"
This becomes SELECT and then the value of variable w.

Another option is to use the concatination operator, which is a dot.
$query = 'SELECT '.$w
This way, the string 'SELECT ' and the variable w are concatenated
together.

May 18 '06 #2
Carved in mystic runes upon the very living rock, the last words of
Sjoerd of comp.lang.php make plain:
//$query = 'SELECT TITLE, NAME, INST, ADD1, ADDR2, ADDR3, PH, FAX,
EMAIL FROM officers WHERE GRP = $w';


When a string is between 'single quotes', variables are not parsed.
This means that after
$query = 'SELECT $w'
The variable query literaly contains SELECT $w. To use the value of
the variable w instead, use double quotes:
$query = "SELECT $w"
This becomes SELECT and then the value of variable w.

Another option is to use the concatination operator, which is a dot.
$query = 'SELECT '.$w
This way, the string 'SELECT ' and the variable w are concatenated
together.


And don't forget to enclose the value in single quotes within the query:

"...WHERE GRP = '$w'";

--
Alan Little
Phorm PHP Form Processor
http://www.phorm.com/
May 18 '06 #3
Alan Little wrote:
Carved in mystic runes upon the very living rock, the last words of
Sjoerd of comp.lang.php make plain:

//$query = 'SELECT TITLE, NAME, INST, ADD1, ADDR2, ADDR3, PH, FAX,
EMAIL FROM officers WHERE GRP = $w';


When a string is between 'single quotes', variables are not parsed.
This means that after
$query = 'SELECT $w'
The variable query literaly contains SELECT $w. To use the value of
the variable w instead, use double quotes:
$query = "SELECT $w"
This becomes SELECT and then the value of variable w.

Another option is to use the concatination operator, which is a dot.
$query = 'SELECT '.$w
This way, the string 'SELECT ' and the variable w are concatenated
together.

And don't forget to enclose the value in single quotes within the query:

"...WHERE GRP = '$w'";


Only if it's non-numeric.

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
May 18 '06 #4
WHERE GRP = '$w' . Had the same problem, but tinkered it into
submission =)

May 18 '06 #5
TristaSD wrote:
WHERE GRP = '$w' . Had the same problem, but tinkered it into
submission =)


Thanks to all! The single-quoted variable (textual value) within a
double-quoted SQL statement returns all the desired rows.

Jerry
May 18 '06 #6
On Thu, 18 May 2006 15:01:31 -0400, Jerry Stuckle wrote:
And don't forget to enclose the value in single quotes within the query:

"...WHERE GRP = '$w'";

Only if it's non-numeric.


It's actually a good idea to do it even if the field is non-numeric. Say
you have a form that does:

DELETE FROM PrivateMessages
WHERE ID=$id AND OwnedByID=$_SES SION["memberid"];

You think you're being safe as you're ensuring a member can only delete
PrivateMessages that are owned by themselves.

However, what if a malicious user changed the value of $id from "2" to
"ID OR 1=1". Easy enough to do by saving the page, editing the field
value and hitting submit. You then get the SQL statement:

DELETE FROM PrivateMessages
WHERE ID=ID OR 1=1 AND OwnedByID=$_SES SION["memberid"];

This would delete all PrivateMessages (as the value of the ID column
always equals itself and the additional OR 1=1 gives a positive left hand
side to the following AND).

The next question could easily be "but how would the attacker know the
name of the field, I don't use ID as my field name". Easy, a)it could
have been revealed in an error message if they're displayed on the site
and b)this error message may have been fixed, but previously cached by
Google.

Even if the attacker doesn't know the field name, they could set the
variable contents to be something like "0 OR 1=1 OR 1=1" which then gives
the SQL statement:

DELETE FROM PrivateMessages
WHERE ID=0 OR 1=1 OR 1=1 AND OwnedByID=$_SES SION["memberid"];

Which then always works.

It's always a good idea to wrap field values in '', even if they're
numeric as it stops this kind of attack. If you did so, the SQL statement
would be:

DELETE FROM PrivateMessages
WHERE ID='ID OR 1=1' AND OwnedByID=$_SES SION["memberid"];

And the numeric ID column will never equal that string, no records deleted.

Of course, you also need to ensure the field is safe using
mysql_real_esca pe_string, but that's a separate conversation to this one
about wrapping numeric field values in ''.

Cheers,
Andy

--
Andy Jeffries MBCS CITP ZCE | gPHPEdit Lead Developer
http://www.gphpedit.org | PHP editor for Gnome 2
http://www.andyjeffries.co.uk | Personal site and photos

May 18 '06 #7
On Thu, 18 May 2006 20:20:14 +0000, Andy Jeffries wrote:
And don't forget to enclose the value in single quotes within the
query:

"...WHERE GRP = '$w'";

Only if it's non-numeric.


It's actually a good idea to do it even if the field is non-numeric.


I mean "is numeric" there, I guess it's obvious from the rest of the post,
but hey I'm a programmer I have to try and correct my mistakes... :-)

Cheers,
Andy
--
Andy Jeffries MBCS CITP ZCE | gPHPEdit Lead Developer
http://www.gphpedit.org | PHP editor for Gnome 2
http://www.andyjeffries.co.uk | Personal site and photos

May 18 '06 #8
Carved in mystic runes upon the very living rock, the last words of
Jerry Stuckle of comp.lang.php make plain:
Alan Little wrote:

And don't forget to enclose the value in single quotes within the
query:

"...WHERE GRP = '$w'";


Only if it's non-numeric.


In his example it was "exec".

Plus what Andy said.

--
Alan Little
Phorm PHP Form Processor
http://www.phorm.com/
May 19 '06 #9

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

Similar topics

1
4448
by: Peter Horst | last post by:
I have a tiny custom 404 script I'm working on; I'd like to imitate the standard Apache 404 page insofar as I'd like "Apache/1.3.29 Server at www.example.com Port 80" to appear below my 404 message. The problem is that when I try to interpolate $_SERVER into the html output of my script it produces a link of the following (incorrect) format: http://www.example.com/\"mailto:webmaster@example.com\"
3
1978
by: red | last post by:
within an object function, this code: $test2='test'; echo "$test"; $this->test2='test2'; echo "$this->test2\n"; produces this result: test2
7
1814
by: bartek | last post by:
Hello, I've been pondering with this for quite some time now, and finally decided to ask here for suggestions. I'm kind of confused, actually... Maybe I'm thinking too much... Brain dump follows... I need a class to represent a variable, with an associated data type and/or value. Though, I don't want it to be a variant type, and not a
14
5189
by: Charles Banas | last post by:
I'm not sure if this is the right place to ask about this, but I've seen several posts in the past regarding Akima's Bivariate Interpolations routines, and i'm wondering if someone can give me some ideas or PD code I can put to use right away. At the moment, I'm maintaining a contour calculation and plotting program for radio wave propagation studies. This program uses a number of routines written by and for the FCC in Fortran in 1976...
1
4084
by: msnews.microsoft.com | last post by:
I'm trying to fill an array of objects but when I add the first object I get a NullReferenceException. ---------------------------------------------------------------------------- ------------------------------------------- Public Class TestClass Public NextSubIndex As Integer = 1 Public arrTestSubClass() As TestSubClass
1
4617
by: crjunk | last post by:
I've got an aspx page that allows the user to select different options whenever they want to run a report. On this page, I have added an additional text box for the user to enter in comments about the report they are running. I would like to be able to have the comments that the user has entered to appear on the report that is generated. I thought that I might be able to pass this text to the report by using a session variable but I...
5
1894
by: swtstrawberry | last post by:
All the basic stuff I get like cin/cout...but the interpolation formula, the for/while loop, and reading in the desired altitude...i dont get it....please help...anybody here are the directions I got: The program is supposed to determine the pressure, temperature, and density, by linear interpolation of atmospheric conditions given in a data table(a text file). 1. Read in the data table and store these table values in a 4 one dimensional...
10
12787
by: John Passaniti | last post by:
(Note: This is not the same message I posted a week or so ago. The problem that prevented my previous attempt to work was a silly error in the template system I was using. This is a problem involving variable scope in JavaScript.) I have a lot of code that generates HTML on the fly. This code has tags with id attributes derived from variables. A small example: blah('<span id="' + dev + '_' + mod + '">...</span>');
5
4456
by: August Karlstrom | last post by:
Hi, Does anyone know the correct syntax to interpolate a class variable, $x say, inside a string? I tried "{self::$x}" but it produces the string {self::x}
0
7987
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8392
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8050
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8264
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6718
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5438
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3897
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3939
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1504
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.