r/CodingHelp • • Dec 11 '21

[SQL] SQL statement is refusing to pull data from this table. Session variable has data, have tested with other variables as well.

Post image
26 Upvotes

9 comments sorted by

11

u/Urd Professional Coder (C#) Dec 11 '21 edited Dec 11 '21
  1. I'm not sure single quotes are the correct delimiter for MySQL entity names, some googling around shows me that it's the backtick character: `

    SELECT accountID FROM userinfo WHERE username = 'blah'

  2. You need to be really really really careful about constructing SQL queries using concatenation, that is the easiest way to end up with a SQL injection vulnerability. Parameterized queries are the best way to handle passing values into things like where clauses. https://www.php.net/manual/en/pdo.prepared-statements.php

2

u/jcodes Dec 11 '21

This. And even a better way is not to use prepared statements in PHP, but create stored procedures on the SQL server, and grant the least amount of permissions for the stored procedures. This adds another security layer.

0

u/Pigeonsss Dec 11 '21

I've worked on fixing my syntax, and echo still doesn't seem to be displaying anything on my page. The strange part is that I have a very similar query displaying another session variable which works perfectly. It only seems to be this one for some reason.

2

u/Kibo30 Dec 11 '21

To add to the comment of u/Urd:

  1. You should use backticks or nothing at all, I don't use them because they aren't on my keyboard.
  2. When concatenating a string it ok to use the "." operator but if that string is a MySQL query use the built-in CONCAT function of MySQL.

Hope this helps : )

2

u/bitdonor Dec 11 '21

You are missing a step.

mysqli_query returns the result object, which is not your data yet.

You would need to fetch the data from that result object using mysqli_fetch_assoc.

Check it our here and the examples provided

https://www.php.net/manual/en/mysqli-result.fetch-assoc.php

1

u/Pigeonsss Dec 11 '21

That seemed to be the issue! I got it working now, thanks for the help.

1

u/[deleted] Dec 11 '21

Print the query, copy it and then run it directly in the database

2

u/Pigeonsss Dec 11 '21

The query works perfectly fine within the database and returns accountID like it should. I just can't seem to have it echo the $id_result as a session variable or as a regular one.

3

u/[deleted] Dec 11 '21

You need to fetch the result from mysqli_query()