WordPress database error with using wpdb->query - php

I have a query that is using $wpdb->query but every time I run it, it doesn't seem to work and is providing me with the following error message:
WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''4'' at line 1 for query SELECT * FROM wp_mytable OFFSET '4'
This is the code that is causing the error:
$query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . MY_TABLE . " OFFSET %s", $offset);
$fetch = $wpdb->get_results($query, 'ARRAY_A');
What am I doing wrong here? I've looked at some other questions but nothing seems to be similar to my issue so I don't know what I'm missing.

Offset should be integer not a string. Also offset comes along with limit
Replace
$query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . MY_TABLE . " OFFSET %s", $offset);
with
$query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . MY_TABLE . " LIMIT %d OFFSET %d", $limit,$offset);
Not tested.

Related

Why i am getting datatype mismatch error?

SQLSTATE[42804]: Datatype mismatch: 7 ERROR: argument of WHERE must be
type boolean, not type integer LINE 1
$sql = "SELECT mod_modulegroupcode, mod_modulegroupname FROM module "
. " WHERE 1 GROUP BY `mod_modulegroupcode` "
. " ORDER BY `mod_modulegrouporder` ASC, `mod_moduleorder` ASC ";
$stmt = $DB->prepare($sql);
$stmt->execute();
$commonModules = $stmt->fetchAll();
$sql = "SELECT mod_modulegroupcode, mod_modulegroupname, mod_modulepagename, mod_modulecode, mod_modulename FROM module "
. " WHERE 1 "
. " ORDER BY `mod_modulegrouporder` ASC, `mod_moduleorder` ASC ";
$stmt = $DB->prepare($sql);
$stmt->execute();
$allModules = $stmt->fetchAll();
$sql = "SELECT rr_modulecode, rr_create, rr_edit, rr_delete, rr_view FROM role_rights "
. " WHERE rr_rolecode = :rc "
. " ORDER BY `rr_modulecode` ASC ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":rc", $_SESSION["rolecode"]);
$stmt->execute();
$userRights = $stmt->fetchAll();
You are getting a datatype mismatch error because the where clause of a SQL statement expects you to provide conditions, not integer values. Your third query has a condition for its where clause, but your first two try to just give an integer value. There are some programming languages where 1 treated like "true", but SQL is not one of those languages.
Given that you're assembling the SQL with your code, if there's no condition to provide for the where clause, then just leave the where clause out, like this:
$sql = "SELECT mod_modulegroupcode, mod_modulegroupname FROM module "
. " GROUP BY `mod_modulegroupcode` "
. " ORDER BY `mod_modulegrouporder` ASC, `mod_moduleorder` ASC ";
But then you're going to have a problem because mod_modulegroupname is not aggregated. Since you're not doing any aggregation, I suggest just taking the GROUP BY clause out, too. You should also take the backticks out of your order by. This would leave you with:
$sql = "SELECT mod_modulegroupcode, mod_modulegroupname FROM module "
. " ORDER BY mod_modulegrouporder ASC, mod_moduleorder ASC ";
If I can kindly say so, it sounds like you should do a SQL tutorial.

sql left join not working

I want to get total transfered items from table inv_site_item where 'item_id' in inv_sie_item = 'item_code' in inv_items, I am getting packing also from packing table which works fine in this query only inv_site_item is giving problem.
error is: Unknown column 'inv_site_item.site_id' in 'field list'
$where .= " AND inv_items.item_code = $item_code";
$query = "SELECT inv_items.*,packing.name_en `packing_name`,"
. " COUNT(inv_site_item.site_id) `transfer_out`, COUNT(inv_site_item.location_site_id) `transfer_in` FROM inv_items"
. " left join "
. "inv_packing as packing on packing.id=inv_items.packing"
. " left join "
. "inv_site_item as transfer on transfer.item_id=inv_items.item_code"
. " WHERE item_code !='' " . $where . "";
you must use your table alias transfer instead, So:
change from
inv_site_item.site_id
to
transfer.site_id
also with inv_site_item.location_site_id to be transfer.location_site_id
For any query related errors you should always check to print the query if possible. Your "WHERE" clause is not getting populated correctly.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE item_code !=''' at line 1
This means that your query is giving error near your "WHERE" clause.
Print your $query variable to see the actual query that is built then you will be able to find the error and fix it.
<?php echo "<pre>"; print_r($query); echo "</pre>"; ?>
you must use your table alias transfer instead, So:
change from
inv_site_item.site_id
to
transfer.site_id
also with inv_site_item.location_site_id to be transfer.location_site_id
And also change $where .= " AND inv_items.item_code = $item_code"; to
$where .= "inv_items.item_code = $item_code";
and
change query statement to
$query = "SELECT inv_items.*,packing.name_en `packing_name`,"
. " COUNT(transfer.site_id) `transfer_out`, COUNT(transfer.location_site_id) `transfer_in` FROM inv_items"
. " left join "
. "inv_packing as packing on packing.id=inv_items.packing"
. " left join "
. "inv_site_item as transfer on transfer.item_id=inv_items.item_code"
. " WHERE " . $where . " AND item_code !=' '";
For let not empty clause come at last...

SQL syntax error, PHP MYSQL

$sql = "SELECT post_title, post_body, post_author FROM forum_post WHERE post_id='".$pid."' forum_id='".$id."' AND post_type='o'";
if($topicPost = $mysql->prepare($sql)) {
$topicPost->bind_param('ss',$pid,$id);
$topicPost->bind_result($post_title, $post_body, $post_author);
$topicPost->execute();
$topicPost->store_result();
} else {
echo "ErrorinSQLLL, ".$mysql->error;
exit();
}
So there is my SQL query statement.
I get this printed on my page :
ErrorinSQLLL, You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'forum_id='1'' at line 1
If needed I can post more of my code.
You are missing AND in your query, here post_id='$pid' forum_id='$id'.
You missed one AND, after post_id key:
"SELECT
post_title,
post_body,
post_author
FROM
forum_post
WHERE
post_id = " . $pid . "
AND
forum_id= " . $id . "
AND
post_type = 'o'";
Missing and in where condition
... WHERE post_id = " . (int)$pid . " AND forum_id = " . (int)$id . " ...
Ids are number, so without quotes.

Error "Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0"

This is my error:
Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 53 in C:\xampp\htdocs\includes\class.rooms.php on line 35
This is the line in the coding:
return mysql_result(
dbquery(
"SELECT " . $var . " FROM rooms WHERE id = '" . $roomId . "' LIMIT 1"
), 0);
Assuming that $var and $roomId are correctly populated , it might he useful to test your code excluding the dbquery function which seems to be a user defined function :
$query_temp = "SELECT " .$var ." FROM rooms WHERE id = '" .$roomId ."' LIMIT 1";
/*
* This is for test purpose and in production you would not want to display neither the query nor error to the user.
*/
$result_temp = mysql_query( $query_temp ) or die ("Error in query: $query_temp. " .mysql_error( ) );
// var_dump( mysql_fetch_array ( $result_temp ) );
return( $result_temp );
As already commented by shmuli it is worth to switch to mysqli or pdo in the beginning itself
Firstly, function dbquery is unfamiliar to me. I know mysql_query, but maybe it's your own method. The problem is, most possibly, that your query returns no rows.
Try debugging with
$result = ..query..
if (!mysql_num_rows($result))
echo "No rows.";

PDO LIKE query not returning results

Well, I've been at this for a few hours, and for the life of me I can't figure out what is wrong. The code is as follows:
$str = "%" . $_POST['str'] . "%";
$offset = (int) $_POST['offset'];
try {
$stmt = $dbh->prepare("SELECT * FROM Spells WHERE :col LIKE :str ORDER BY :sort LIMIT 10 OFFSET :offset");
$stmt->bindParam(":col",$_POST['col']);
$stmt->bindParam(":str",$str);
$stmt->bindParam(":offset",$offset, PDO::PARAM_INT);
$stmt->bindParam(":sort",$_POST['sort']);
$stmt->execute();
}
catch (PDOException $e) {
echo "MySQL error: " . $e->getMessage() . "<br/>";
die();
}
The connection to the database works fine, no errors occur. If I type in % into the search field(which would be output as %%% in the query), results return as expected.
I've attempted the same query in phpMyAdmin and it works fine. I've been updating this script from the deprecated mysql_* functions, which worked fine before.
Example of the previous, deprecated query:
$sql = "SELECT * FROM Spells WHERE " . $col . " LIKE '%" . $str . "%' ORDER BY " . $sort . " LIMIT 10 OFFSET " . $offset;
As I may have already stated, I've been searching on this site as well, trying to find a solution; nothing has worked, not even MySQL's CONCAT('%',:str,'%').
The server I'm testing this on is running off of php version 5.3.17.
My question, in case I did not make it clear, is what am I doing wrong here? For those wondering(I thought that I put this but apparently I did not), there are no error messages.
The issue is that you cannot use parameters in place of identifiers. This means you cannot parameterise column or table names.
What your query essentially looks like when it is executed is
SELECT * FROM Spells WHERE 'some_column_name' LIKE '%something%'...
I would establish a whitelist of search and sort column names and use those to construct your query. Here's a very simple example
$search = array('col1', 'col2', 'col3');
$defaultSearch = 'col1';
$sort = array('col1', 'col2');
$defaultSort = 'col1';
$col = in_array($_POST['col'], $search) ? $_POST['col'] : $defaultSearch;
$sort = in_array($_POST['sort'], $sort) ? $_POST['sort'] : $defaultSort;
$sql = sprintf('SELECT * FROM Spell WHERE %s LIKE :str ORDER BY %s LIMIT 10 OFFSET :offset',
$col, $sort);
$stmt = $dbh->prepare($sql);
// bind :str and :offset, and so on

Categories