0

I am having trouble with formatting php correctly. Specifically, when I need to use two sets of double quotes, how do I make it group them correctly?

eg:

query("INSERT INTO Holdings (id, symbol, shares) VALUES ($_SESSION["id"], "$_POST["symbol"]", $_POST["shares"]) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)")

When I run this line, it groups these quotes together: "INSERT...."$_POST[["symbol"] . So, now "$_POST["symbol"]" isn't surrounded by quotes when the query is ran.

1
  • Can I recommend you look into statements. It will make your code easier to read and much safer. They are not much more difficult then querys.
    – Nick Young
    Commented Jan 24, 2016 at 14:41

1 Answer 1

1

here are two solutions:

  1. you could use the string concatenation operator (i.e., .). example:

    echo "the session id is: " . $_SESSION["id"] . "!";
    
  2. you could surround the name of the variable with curly braces. example:

    echo "the session id is: {$_SESSION["id"]}!";
    

update: you shouldn't surround variable names with quotes. so you shouldn't have something like "$_POST["symbol"]". it should be just $_POST["symbol"].

also as mentioned above, you should probably use one of these ways when you're plugging variables into a string not get things mixed up.

in this particular case, it's highly recommended to use a parameterized query to protect your database from injection attacks. example:

query("INSERT INTO foo (a, b) VALUES (?, ?)", $varA, $varB);

where foo is a table, a and b are columns, and $varA and $varB are variables.

7
  • Thank you, but I worded my original question wrong. The problem I actually have is: query("INSERT INTO Holdings (id, symbol, shares) VALUES ($_SESSION["id"], "$_POST["symbol"]", $_POST["shares"]) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)") The specific problem is with the quotes around "$_POST["symbol"]" (which I completely left off in my original comment). The stock symbol needs to be surrounded by quotes, but it's being paired with the quote on "INSERT.....
    – Susan
    Commented Jun 28, 2015 at 1:13
  • hi, @Susan! you can still edit your question. feel free to update it and notify me in a comment here please! thank you!
    – kzidane
    Commented Jun 28, 2015 at 1:14
  • updated - sorry.
    – Susan
    Commented Jun 28, 2015 at 1:18
  • @Susan I meant that you could update the original post above!
    – kzidane
    Commented Jun 28, 2015 at 1:19
  • I figured that out 2 seconds too late :( Now it's updates. Thanks!
    – Susan
    Commented Jun 28, 2015 at 1:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .