-1

I have this code and it works perfectly well:

$res=mysql_query('SELECT ((SELECT SUM(mball_h) FROM pr) + (SELECT 
SUM(mball_i) FROM pr)) AS theSum'); 
while($row=mysql_fetch_array($res))

then i echo with this

<?php echo $row['theSum']; ?>

Now, I want to do this:

SUM(mball_h) from pr WHERE mball_0 = $_SESSION['SESS_mball_0']

Here is the code that does not work"

$res=mysql_query('SELECT ((SELECT SUM(mball_h) FROM pr WHERE mball_0 = 
$_SESSION["SESS_mball_0"]) + (SELECT SUM(mball_i) FROM pr WHERE mball_0 = 
$_SESSION["SESS_mball_0"])) AS theSum');    
while($row=mysql_fetch_array($res))

What am I not doing right?

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
  • The session value probably needs to be quoted with `'`. That second bit isn't a complete SQL statement, though, so it's hard to tell much. – Don't Panic Feb 16 '18 at 22:40
  • Providing the code that isn't working, along with the results you are receiving / error logs, will help the community to provide a solution. – Anthony L Feb 16 '18 at 22:41
  • Incidentally, you are using an outdated mysql extension and that code is vulnerable to SQL injection. – Don't Panic Feb 16 '18 at 22:41
  • @AnthonyL i just added the code. – Allisa Dante Feb 16 '18 at 22:48
  • now - with the new code - it's a different situation. Variables won't get parsed inside singe-quoted strings. So try `'SELECT ((SELECT ...WHERE mball_0 = '.$_SESSION["SESS_mball_0"]) .') + ...'`. For a starter. – Jeff Feb 16 '18 at 22:48
  • 5
    But still you should change to either mysqli_* or PDO _and_ use prepared statements (which would have avoided that error). – Jeff Feb 16 '18 at 22:50
  • 1
    There's no need for those nested selects. `SELECT SUM(mball_h + mball_i) FROM pr WHERE mball_0 = ..."` – Barmar Feb 16 '18 at 23:30

1 Answers1

0

Variables are only expanded inside double-quoted strings, not single-quoted strings. See What is the difference between single-quoted and double-quoted strings in PHP?

And if the variable is an array with a quoted index, you need to wrap it in {}. So it should be:

$res=mysql_query("SELECT ((SELECT SUM(mball_h) FROM pr WHERE mball_0 = 
    {$_SESSION["SESS_mball_0"]}) + (SELECT SUM(mball_i) FROM pr WHERE mball_0 = 
    {$_SESSION["SESS_mball_0"]})) AS theSum");

And if $_SESSION["SESS_mball_0"] is a string, you need to put quotes around it. There's also no need for nested selects.

If it's a string, you should also escape it in case there are special characters.

$mball_0 = mysql_real_escape_string($_SESSION["SESS_mball_0"]);
$res = mysql_query("SELECT SUM(mball_h) + SUM(mball_i) AS theSum
                    FROM pr
                    WHERE mball_0 = '$mball_0'");

It would be better if you upgraded to mysqli or PDO and used parametrized queries instead of substituting variables directly into SQL.

Barmar
  • 741,623
  • 53
  • 500
  • 612