WordPress - Empty array from SELECT query - php

I have this query in my wordpress plugin. I need to check the database to get a value and compare it, but the sql seems not returning any result.
global $wpdb;
$table = $wpdb->prefix . 'order_codes';
$sql = $wpdb->prepare("SELECT * FROM $table WHERE order_code = '$order_code'");
$order_signature = $wpdb->get_results($sql, ARRAY_A);
I've done a var_dump($order_signature); but the resulting array will be always empty.
Is there something wrong in the statement?

The issue is with the use of the $order_code variable in the query. The $wpdb->prepare() method is used to prevent SQL injection by properly escaping input variables, but it seems that in this case, the variable is not being passed correctly.
Try to use this i hope problem will be solve:
global $wpdb;
$table = $wpdb->prefix . 'order_codes';
$order_code = 'your_order_code_value';
$sql = $wpdb->prepare("SELECT * FROM $table WHERE order_code = %s", $order_code);
$order_signature = $wpdb->get_results($sql, ARRAY_A);
By passing the variable correctly to the $wpdb->prepare() method, the query should return the expected results.

Related

String variable in SQL query within WordPress getting an error when not using single quotes

This code is in a custom WordPress plugin.
if (isset($_POST['send_user'])) {
$username = sanitize_text_field( $_POST['username'] );
global $wpdb;
$customer_id = $wpdb->get_var("SELECT user_id FROM wp_wc_customer_lookup WHERE username = $username");
This code does not work properly and it gets an error message with provides a NULL value within $customer_id.
When I manually change the code to:
$customer_id = $wpdb->get_var("SELECT user_id FROM wp_wc_customer_lookup WHERE username = 'username'");
This works perfectly and provides the user_id I am looking for. Why? What am I missing here?
You need to use placeholders for passing data to the query, instead of directly injecting variables in the query string.
Your query should look like this:
$customer_id = $wpdb->get_var(
$wpdb->prepare(
"SELECT user_id FROM wp_wc_customer_lookup WHERE username = %s",
$username
)
);
It's also best practice to pull the database prefix from class properties:
$customer_id = $wpdb->get_var(
$wpdb->prepare(
"SELECT user_id FROM {$wpdb->prefix}wc_customer_lookup WHERE username = %s",
$username
)
);
$customer_id = $wpdb->get_var("SELECT user_id FROM wp_wc_customer_lookup WHERE username = $username");
does not work because the string variable $username once added into this line of code will look like this:
$customer_id = $wpdb->get_var("SELECT user_id FROM wp_wc_customer_lookup WHERE username = username");
This breaks because the WHERE clause is looking for a string format such as "username". In order to make this work within the SQL statement, you cannot add "username" into the SQL because it will break it - once its runs it will look like this:
$customer_id = $wpdb->get_var("SELECT user_id FROM wp_wc_customer_lookup WHERE username = "$username"");
The first double quote exits the SQL statement and the $username is never added. In order to make this work you have to put single quotes around the string variable - like this:
$customer_id = $wpdb->get_var("SELECT user_id FROM wp_wc_customer_lookup WHERE username = '$username'");
This satisfies the parameters needed.
Many get confused (which happened to me) because this code works:
if (isset($_POST['send_user'])) {
$username = sanitize_text_field( $_POST['username'] );
$tablename = $wpdb->prefix."wc_customer_lookup";
global $wpdb;
$customer_id = $wpdb->get_var("SELECT user_id FROM $tablename WHERE username = 'username'");
and when using an int variable - it works as well. Like this:
if (isset($_POST['send_user'])) {
$username = sanitize_text_field( $_POST['username'] );
$tablename = $wpdb->prefix."wc_customer_lookup";
$number = 5;
global $wpdb;
$customer_id = $wpdb->get_var("SELECT user_id FROM $tablename WHERE int = $number");
So without thinking about it, you may conclude that using a string variable would work as well. Not the case, and it's because the string in the SQL argument must include quotes.
When using something like:
$wpdb->prepare(
"SELECT user_id FROM $tablename WHERE username = %s",
$username
this will work just fine because the prepare class adds the single quotes to the SQL statement so you don't have to worry about it.

Using a Variable in WHERE clause does not work

I'm running a simple query that is working, that is, without a PHP variable in the WHERE clause.
However, when I insert the variable, it does nothing.
<?php
$query = $this->db->query("SELECT `rem1` FROM `exam_group_exam_results` WHERE `exam_group_class_batch_exam_student_id`= $student_value->id and `exam_group_class_batch_exam_subject_id`=1");
$getrem = $query->row();
echo $getrem->rem1;?>
But when I insert just a value, everything works
<?php
$query = $this->db->query("SELECT `rem1` FROM `exam_group_exam_results` WHERE `exam_group_class_batch_exam_student_id`= 11 and `exam_group_class_batch_exam_subject_id`=1");
$getrem = $query->row();
var_dump($getrem);?>
I var_dump this variable student_value['id'] and it printed out the correct value which is 11.
I've been at this for hours. Please help
Try to assign the value of your object to another variable.
Example
$id_value = student_value['id'];
Then use the variable in your SQL code
$query = $this->db->query("SELECT `rem1` FROM `exam_group_exam_results` WHERE `exam_group_class_batch_exam_student_id`= $id_value and `exam_group_class_batch_exam_subject_id`=1");
It's probably a syntax problem
$query = $this->db->query("SELECT `rem1` FROM `exam_group_exam_results` WHERE `exam_group_class_batch_exam_student_id`= ".$student_value->id." and `exam_group_class_batch_exam_subject_id`=1");
Otherwise, check whether your variable is an object or an array
I think the query syntax is not read the Student ID, so the result will show as is WHERE CLAUSE.
// Try this
$studentId = $student_value->id;
$sql = "SELECT `rem1` FROM `exam_group_exam_results` WHERE `exam_group_class_batch_exam_student_id`=`$studentId` and `exam_group_class_batch_exam_subject_id`=1"
$query = $this->db->query($sql);

prepared statement returns an empty array

I cannot use %s in my prepared statement.
echo $get_where; // returns: edited = 1
$get_uncontacted_members = $wpdb->get_results(
$wpdb->prepare("SELECT * FROM yc_customers WHERE %s", $get_where)
);
This code returns an empty array. But when I use $get_where instead of %s (see code bellow), then it returns all the results from the database.
// This works
echo $get_where; // returns: edited = 1
$get_uncontacted_members = $wpdb->get_results(
$wpdb->prepare("SELECT * FROM yc_customers WHERE edited = 1", $get_where)
);
Why wouldn't it work with %s?
WordPress while uses the sprintf() syntax, it actually works like prepared statements. As such you can only pass the value of the column you are querying against, not entire column(s) and values.
$get_uncontacted_members = $wpdb->get_results(
$wpdb->prepare("SELECT * FROM yc_customers WHERE IFNULL(edited,'') = %s", 1)
);

Selecting row where field = value error

Can you explain me why my code isnt working? Ive been thinking about it for a while and I cant find it. obviously I want to print some columns from rows where column F1 is equal to user's username.
$db = JFactory::getDBO();
$user = JFactory::getUser();
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = ".$user->username;
$db->setQuery($query);
$result = $db->query();
while($row = mysqli_fetch_object($result))
{
print $row->F1;
}
It works when I remove condition from select command and I cant figure out how to make it work with it
$query = "SELECT * FROM qwozh_visforms_1";
Now Im getting this error:
UNKNOWN COLUMN 'ADMIN' IN 'WHERE CLAUSE' SQL=SELECT * FROM
QWOZH_VISFORMS_1 WHERE F1 = ADMIN RETURN TO PREVIOUS PAGE
Thanks
All it takes if a quick read of the Joomla documentation. The following is the same as your query but making full use of Joomla's up to date database class:
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$query->select(array('*'))
->from($db->quoteName('#__visforms_1'))
->where($db->quoteName('F1') . ' = '. $db->quote($user->username));
$db->setQuery($query);
$results = $db->loadObjectList();
// Display the results
foreach($results as $result){
// echo what you want here
}
Note, I've used the prefix #__ rather than manually defining qwozh, assuming your table belong to a Joomla extension.
I know PHP and MySQL, but not Joomla. But the problem is that your username needs to be quoted because it is probably a string.
Try this:
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = '{$user->username}'";
or
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = ".$db->quote($user->username);
You need to wrap the name in quotes:
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = '".$user->username . "'";
As pointed out in the comments my answer has a pretty bad quality, you may want to look at prepared statements, expecially using bindParam, which takes care of quotes for you and protects you agains SQL injection attacks.
Unfortunately I cannot suggest you Joomla based approach since I never used it, somebody else can suggest you a more appropriate solution.

how to build a sql query using the content of a variable

I'm trying to build a query using php and mysql,
$query = "select * from products where product_name = '$item_name'";
this works when $item_name holds only one name, but $item_name is an array and based on the user's interaction can contain multiple names, how can I make the query to run for multiple name and get the resulted rows.
Thanks in advance
Here's how you could build a safe list of names for inserting into an IN clause...
if (is_array($names) && count($names))
{
$filter="('".implode("','" array_map('mysql_real_escape_string', $names))."')";
$sql="select * from products where product_name in $filter";
//go fetch the results
}
else
{
//input was empty or not an array - you might want to throw an
//an error, or show 'no results'
}
array_map returns the input array of names after running each name through mysql_real_escape_string to sanitize it. We implode that array to make a nice list to use with an IN clause.
You should always ensure any data, particularly coming directly from the client side, is properly escaped in a query to prevent SQL injection attacks.
$vals = implode(',',$item_name);
$query = "select * from products where product_name in (".$vals.");";
Give that a try.
$query = "select * from products where product_name in(";
foreach($item_name as $name)
{
$query .= "'" . $item_name . "', ";
}
$query = substr($query, 0, strlen$query) - 2);
$query .= ");";
First answer (by inkedmn) is really the best one though
foreach($item_name as $name) {
$query = "select * from products where product_name = '$name'";
//whatever you want to do with the query here
}
something like that ought to do it.
Based on inkedmn's response (which didn't quote the item names):
$query = 'select * from products where product_name in ("' . implode('", "', $item_name ) . '")';
Although you may be better with a fulltext search.
http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html

Categories