PHP: Where clause will not execute when using a variable - php

For the user I am testing with, their org_id column value is "student_life"
I am trying to have this function display whatever rows have the student_life column = 1. (so yes there is a column student_life which is a boolean, and then I also have a separate column named org_id and in this case has the value student_life)
I am pretty sure there is a syntax error but I cannot figure it out.
function org_id_users_table()
{
$org_id = mysql_real_escape_string($_POST["org_id"]);
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE '$org_id' = '1'");
$result = $sql['sql'];
$num_rows = $sql['num_rows'];
$this->create_table($result, $num_rows);
}
(when I replace $org_id in the "$sql=..." line with student_life the code works.

You're quoting the column name, which makes MySQL think it's a string.
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE $org_id = '1'");
Edit:
Based on your comments, I think what you actually want is this:
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE org_id = '$org_id'");

Change quotes.
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE `$org_id` = '1'");
P.S. Why shouldn't I use mysql_* functions in PHP?

Where is this coming from? $_POST["org_id"]
Do you have a form on the page posting that? Or are you just trying to get that from the database? If so, wouldn't you need another query to obtain that first?
$row_MyFirstQuery['org_id']
Otherwise if it is $_POST["org_id"], wouldn't it be single quotes not double? $_POST['org_id']

Related

How do I use a variable in the WHERE condition of a MySQL query using a php variable? [duplicate]

This question already has answers here:
How to insert values in a PHP array to a MySQL table?
(2 answers)
Closed 5 years ago.
I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.
The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.
For testing I selected a user I knew had a rapsheet and used
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.`key` = 'RapSheet'
AND character_data_store.character_id = '216'";
Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.
I've tried using:
$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = '$correctPlayer'";
I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = {$_SESSION['selpid']}";
Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?
It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".
How do I use a variable in the WHERE condition of a MySQL query using a php variable?
You have obvious error in your code. You are missing quotes in {$_SESSION['selpid']} and you are using quotes in column name. Your query should be
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.`key` = 'RapSheet' AND character_data_store.character_id = '{$_SESSION['selpid']}'";
You should not use quotes in column name, instead use backquotes(`) if you really need. I recommend prepared statements.
There are multiple ways to do this. A naive way to do this would be-
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ".$correctPlayer;
But to avoid sql injections I would recommend you use bindparam function to bind paramaters in a statement.
$sql="SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ?";
if($stmt = $dbh->prepare($sql)){
$stmt->bindParam(1, $correctPlayer, PDO::PARAM_STR);
$ql = $stmt->execute() or die("ERROR: " . implode(":", $dbh->errorInfo()));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result['data'] = $row;

SQL SELECT Function In Wordpress Not Working

I'm working on a basic selection function that grabs the row with the lowest id. Then just to make sure it works I have it dump the array, but something is wrong and it keeps returning null. I'm not sure where I went wrong.
function select_min_id(){
global $wpdb;
$table = 'my_table';
$query = '"SELECT * FROM '.$table.' WHERE id=(select min(id) from '.$table.')"';
$row = $wpdb->get_row($query, ARRAY_A);
var_dump($row);
}
Could you provide the error you get?
And I was curious about why you use single quotes and double quotes on your query? You could simply write
$query = "SELECT * FROM $table WHERE id=(select min(id) FROM $table)";
If you didn't know, when you are using double quotes, you can put PHP variables in a string without breaking it.

Getting ID of Variable in database

I would like to get the id of an item in the database, set it to a variable, and use it. I'm quite new to all this coding stuff. I'm basing this on.
http://jameshamilton.eu/content/simple-php-shopping-cart-tutorial?PHPSESSID=99d373741727e3010a32319f1ebed001
cart.php?action=add&pdin=fbs
$product = $_GET[pdin];
I can't use an integer for 'pdin' so, id like to use its corresponding id which is an integer and plug it into this line of code which only takes integers?
$sql = sprintf("SELECT * FROM products WHERE pdin = %d;", $product);
so in i would take $product = 'pdin' find it's id $id = 'id' and plug it in to the above code
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $id);
I tried reading up on this sql FROM SELECT WHERE... confused me some
I'd use a prepared statement which would also make yourself a bit safer from SQL injection. What database interface are you using from php to mysql?
Here's one option:
$product = $_GET['pdin'];
$stmt = $db->Prepare("select * from products where pdin = ?");
$res = $db->GetAssoc($stmt,$product);
btw,
if you acces array items via key, always use quotations (' or ") otherwise PHP (unnecessary) first check, if key is constant
Ok, I figured it out. I'm sorry i didn't explain it all that well last night. I have a limited brain battery per day, and last night it was depleted.
What i wanted was quite simple. I wanted to find an items associated id in the database.
$query = "SELECT * FROM products WHERE pdin = '$product'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$productID = $row['id'];
}
Now that parts done and returns the correct id. And the 'item exists' function fires correctly.
//function to check if a product exists
function productExists($productID) {
//use sprintf to make sure that $productID is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $productID);
return mysql_num_rows(mysql_query($sql)) > 0;
}
So, Mark and Michal Hatak; When you where talking about using quotations on keys, does that mean...
$sql = sprintf("SELECT * FROM products WHERE 'id' = %d;", $productID);
putting quotations around things like 'id'? And it's for security?
Forgive me, I'm a new graphic designer and not adept at code.

Use an array inside a query string

Im trying to pass an array that I already found by a query into another query. For example:
$first_query = "SELECT id FROM from Table WHERE user = '{$_SESSION['id'}'";
$result = mysql_query($first_query,$connection);
$ids = mysql_fetch_array($result);
This is where it gets tricky for me. I want to pass $ids into the next query.
$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id = '{$id_implode}';
The second query doesnt seem to be working. Any help is greatly appreciated!
your second query's syntax is wrong. Once evaluated it should read
select * from Table2 where id in (1,2,3)
ditch the curly braces and change the = to in. Don't use OR - that's a dumb way of ignoring good sql functionality
EDIT: Teneff's comment makes a very good point - why are you approaching the problem in this way? If there is a relationship between the tables they can be joined and all the data you want can be retrieved in a single query. If for some reason you can't / won't join the tables you could at least try a sub-query
select * from table2 where id in (select id from table where user = $_SESSION['id']);
To use a where statement with multiple entries to match on, use in ().
$id_implode = "'".implode("', '", $ids)."'"
$second_query = "SELECT * FROM Table2 WHERE id in ({$id_implode});
I think you should use IN
$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id IN '({$id_implode})';
This assumes that $ids is made of int of course, otherwise you have to enclose eache entry in quotes. that means
IN (6,7,8,9)//this doesn't need quotes
IN ('lemon', 'orange')//needs quotes
try to use the IN syntax:
$id_implode = implode("', '", $ids);
$second_query = "SELECT * FROM Table2 WHERE id in ('{$id_implode}');

Coding of parameter-value for SELECT in PHP-MySQL

Alt A below is a statement from a php-mysql tutorial. It works as it should.
I found the id-value rather obfuscated and tested alt B. This also worked!
What is the point with the id-value of alt A?
MySQL 5.0.51, PHP 5.2.6
// Alt A :
$sql = "SELECT * FROM example WHERE id = '".$q."'";
// Alt B :
$sql = "SELECT * FROM example WHERE id = $q";
This are just two different approaches to building a string from static and variable data.
Alternative A uses concatenation, or the joining of string and variable tokens using the concatenation operator.
Alternative B uses variable expansion, wherein the variables inside a double-quote-delimited string are expanded to their values at evaluation time.
Neither is necessarily better or preferred, but if you have to have single-quote-delimited strings, for example, then you would need to use alternative A.
Of course, neither of these is preferable to building SQL queries with bound parameters, as not doing so leaves you vulnerable to SQL injection attacks.
Theres two reasons to use the example in 'Alt A'. First is if the string is enclosed in single quotes '', the variable's name will be used in the string instead of it's value.
$id = 7;
'SELECT * FROM table WHERE id = $id' //works out to: WHERE id = $id
"SELECT * FROM table WHERE id = $id" //works out to: WHERE id = 7
Secondly, it's useful to combine strings with the results of a function call.
"SELECT * FROM table WHERE id = '".getPrimaryId()."'"
Outside of what has already been said I've found it best practice, if I'm writing a query, to write it as so:
$sql = "SELECT * FROM table WHERE uid=" . $uid . " LIMIT 1";
The reason for writing SQL like this is that 1. MySQL query doesn't have to parse the PHP variables in the Query and 2 you now easily read and manage the query.
When PHP communicates with MySQL, it is actually (in essence) two languages communicating with each other. This means that a string will be processed by the first language before being sent to the other. It also means that it is important to think in terms of the receiving language
In this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = $q";<br/>
you are telling MySQL to
"SELECT * FROM example1 WHERE id = some_name.
In this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = '$q'";<br/>
and this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = '".$q."'";<br/>
you are telling MySQL to
"SELECT * FROM example1 WHERE id = 'some_name'.
The first example should cause an error as some_name is not a valid part of a MySQL query (in that context). On the other hand, the next two will work fine, because MySQL will look for the String "some_name".
You can also do this:
$sql="SELECT * FROM exempel WHERE id = {$q}";
which is useful for setting off things like:
$sql="SELECT * FROM exempel WHERE id = {$row[id]}";
in 'alt B', $q must be an int or float or other numeric
in 'alt A', $q can be anything a string, int, etc.
The single quote makes that possible. It's just hard to see sometimes if you are looking at it for the first time.

Categories