SQL SELECT Function In Wordpress Not Working - php

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.

Related

MySQL if exists syntax

Happy holidays, if you celebrate it.
I am trying to run the following query:
$query = SELECT WHERE EXISTS (SELECT * FROM table WHERE val1="someVal" and val2="someVal");
$result = mysql_query ($query)
print_r (mysql_fetch_assoc($result));
My goal is to create an associative array with only records from the matching row that have a value.
Am I using EXISTS in the wrong manner?
h2ooooooo is right, you don't need to use exits to select what you want here. Just a simple WHERE clause will do it. also I would single quote the values not double quote them for mysql syntax purposes. ie:
$query = "SELECT * FROM table WHERE val1='someVal' and val2='someVal'";
$result = mysql_query($query, $link);
print_r (mysql_fetch_assoc($result));

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.

PHP: Where clause will not execute when using a variable

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']

query "...WHERE $string"... $string='b5KlL4znM ' but query returns empty unless "...WHERE 'b5KlL4znM ' "

I am trying to get some information from my table, but the query returns empty when I call it this way:
$varchar_string = mysqli_real_escape_string($link, $_GET['code']); //the code is b5KlL4znM in this scenario
mysqli_query($link, "SELECT * FROM table WHERE code = $varchar_string");
The string is alphanumeric, and is submitted by users, so I've escaped it before doing the query.
Now if I do this query
mysqli_query($link, "SELECT * FROM table WHERE code = 'b5KlL4znM'");
It works fine, but that's not very dynamic.
I didn't get many results when I searched for this issue, and I didn't manage to find the answer amongst those that seem relevant.
Do you perhaps need to put quotes around your string?
mysqli_query($link, "SELECT * FROM table WHERE code = '$varchar_string'");
You'll need to include the variable in quotations.
mysqli_query($link, "SELECT * FROM table WHERE code = '$varchar_string'");

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}');

Categories