|
Posted by Rami Elomaa on 05/04/07 07:27
"john" <puopolo@gmail.com> wrote in message
news:1178237720.515170.273260@n76g2000hsh.googlegroups.com...
> On May 3, 8:08 pm, Aerik <asyl...@gmail.com> wrote:
>> On May 3, 5:02 pm, john <puop...@gmail.com> wrote:
>> <snip>
>>
>>
>>
>> > The problem with constructing a string comes in due to the fact that
>> > you often need to quote strings in the SQL statement, e.g, $sql =
>> > "insert...values('$_POST['email']..)" There doesn't seems to be a
>> > combination of single and double quotes that work.
>>
>> > Is there a standard way people tend to build SQL strings from $_POST
>> > (or $_GET) data in PHP?
>>
>> I'll be interested to see other answers to this too. I like to mangle
>> your post data first by looping through the $_POST and building your
>> $fields and $values string, all the while checking for valid field
>> names and escaping your strings appropriately. Then just do this:
>>
>> $sql = "INSERT INTO mytable ($fields) VALUES ($values)";
>>
>> Aerik
>
> Aerik et al:
>
> Interestingly, this seems to work...(I just tested this before I saw
> your (very quick - thanks!) reply:
>
> $fruit = array('a' => 'apricot', 'b' => 'banana');
> $s = "insert into food(x,y) values ('$fruit[a]', '$fruit[b]')";
> print $s;
> // prints: insert into food(x,y) values ('apricot', 'banana')
>
> This constructs the proper SQL statement. I was having a difficult
> time since I thought I needed to surround the index (a and b above)
> with some type of quotes. Apparently, PHP can use the non-quoted
> index, which solves the simple problem of using $_POST[index], even
> when index is a named index into the array. Cool....
It works, but it's wrong. This works as well but is also wrong: $_POST[a].
What php sees is a constant named a, then looks for that constant from
defined variables and does not find it. Then it assumes it was a "bare
string", a string without quotes. You'll find that this will work just as
well:
echo hello;
It's the same thing, it looks for constant hello, doesn't find it and
finally assumes you meant 'hello'.
The "proper" way might be like this:
$s = "insert into food(x,y) values ('{$fruit['a']}', '{$fruit['b']}')"; The
curly braces can be used to isolate variables inside a string and they help
php understand what you meant to write...
http://www.php.net/manual/en/language.types.string.php
Read the "Complex (curly) syntax" chapter.
--
Rami.Elomaa@gmail.com
"Good tea. Nice house." -- Worf
Navigation:
[Reply to this message]
|