Why is query failing when using order by - mysql

My query is failing everytime I run it. This error keeps showing
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 'BY b.bidId DESC' at line 1Database select query failed.
public static function getAuctionBids( $auctionId, $limit = null )
{
self::getDatabaseInstance();
// SQL query for retrieving all bids for a specific auction
$bidsQuery = "SELECT u.username AS bidderName, u.userId AS bidderId, b.bidTime, b.bidPrice ";
$bidsQuery .= "FROM auctions a, bids b, users u ";
$bidsQuery .= "WHERE a.auctionId = b.auctionId AND b.userId = u.userId AND a.auctionId = $auctionId ";
$bidsQuery .= "ORDER BY b.bidId DESC";
$bidsQuery .= ( is_null( $limit ) ) ? "" : " LIMIT " . $limit;
$result = self::$database -> issueQuery( $bidsQuery );
$bids = [];
while ( $row = $result -> fetch_assoc() )
{
$bid = new Bid( $row );
$bids[] = $bid;
}
return $bids;
}

Related

Wordpress search result postmeta and term

What´s the problem with this?
I´m trying to search in wp_postmeta and wp_terms but i getting just one or another, never both. I already tried change OR to AND in WHERE, but nothing happens and no result is printed.
Thanks!
$join .= "
LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id
LEFT JOIN $wpdb->term_relationships ON $wpdb->posts.ID = $wpdb->term_relationships.object_id
INNER JOIN $wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
INNER JOIN $wpdb->terms ON $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id
";
and this...
$where .= "
OR ( $wpdb->postmeta.meta_value LIKE '%".get_search_query()."%' AND $wpdb->posts.post_status = 'publish' )
OR ( $wpdb->terms.name LIKE '%".get_search_query()."%' AND $wpdb->posts.post_status = 'publish' )
";
UPDATE 1
After reading here https://support.advancedcustomfields.com/forums/topic/mistake-in-documentation-query-posts-by-custom-fields/ — I´ve changed the two "inner join" for "join" and it worked fine. I don´t know exactly why it works. But unfortunately still very slow to get the results.
Could you tell me if this is the best approach for what I'm looking for?
add_filter( 'posts_join', 'custom_search_join' );
add_filter( 'posts_where', 'custom_search_where' );
add_filter( 'posts_distinct', 'custom_search_distinct' );
function custom_search_join( $join ) {
global $wpdb;
if( !is_admin() ) {
if( is_search() ) {
$join .= "
LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id
LEFT JOIN $wpdb->term_relationships ON $wpdb->posts.ID = $wpdb->term_relationships.object_id
LEFT JOIN $wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
LEFT JOIN $wpdb->terms ON $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id
";
print_r( $join ) ;
}
}
return $join;
}
function custom_search_where( $where ) {
global $wpdb;
if( !is_admin() ) {
if( is_search() ) {
$where .= "
OR ( $wpdb->postmeta.meta_value LIKE '%".get_search_query()."%' )
OR ( $wpdb->terms.name LIKE '%".get_search_query()."%' )
AND $wpdb->posts.post_status = 'publish'
";
print_r( $where ) ;
}
}
return $where;
}
function custom_search_distinct( $where ) {
global $wpdb;
if( !is_admin() ) {
if( is_search() ) {
return "DISTINCT";
}
}
return $where;
}
UPDATE 2
After some research and study.
Define list of ACF fields that will be searched
Define taxonomies to be searched
Running fast so far.
If anyone knows of a way to improve this code I really appreciate it.
add_filter( 'posts_search', 'busca_acf', 500, 2 );
function lista_campos_acf() {
$lista_campos_acf = [ 'acf-field-example' ];
return $lista_campos_acf;
}
function lista_taxonomias() {
$lista_taxonomias = [ 'post_tag', 'category', 'example_taxonomy' ];
return $lista_taxonomias;
}
function busca_acf( $where, $wp_query ) {
if( !is_admin() ) {
global $wpdb;
$termos = remove_accents( $wp_query->query_vars[ 's' ] );
$exploded = array_map( 'strtolower', explode( ' ', $termos ) );
$lista_campos_acf = lista_campos_acf();
$lista_taxonomias = lista_taxonomias();
$where = '';
foreach( $exploded as $tag ) {
$where .= "
AND (
( wp_posts.post_title LIKE '%$tag%' )
OR ( wp_posts.post_content LIKE '%$tag%' )
OR EXISTS (
SELECT *
FROM wp_postmeta
WHERE post_id = wp_posts.ID
AND ( ";
foreach( $lista_campos_acf as $campo_acf ) {
if( $campo_acf == $lista_campos_acf[0] ) {
$where .= " ( meta_key LIKE '%" . $campo_acf . "%' AND meta_value LIKE '%$tag%' ) ";
}
else {
$where .= " OR ( meta_key LIKE '%" . $campo_acf . "%' AND meta_value LIKE '%$tag%' ) ";
}
}
$where .= ")
)
OR EXISTS (
SELECT *
FROM wp_terms
INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_id = wp_terms.term_id
INNER JOIN wp_term_relationships ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
WHERE ( ";
foreach ( $lista_taxonomias as $tax ) {
if( $tax == $lista_taxonomias[0] ) {
$where .= "taxonomy = '" . $tax . "'";
}
else {
$where .= "OR taxonomy = '" . $tax . "'";
}
}
$where .= ")
AND object_id = wp_posts.ID
AND wp_terms.name LIKE '%$tag%'
)
)
";
}
return $where;
}
}

PHP - How to group from multiple sql queries

I got
for($i = $start_date;$start_date <= $end_date;$i->modify('+1 day')) {
$i->format('Y-m-d').'<br />';
$dates = $i->format('Y-m-d');
echo $query = "
SELECT md.dish_id
, md.daydate
, d.id
, d.dish_name
, d.weight
, d.price
FROM dishes d
LEFT
JOIN menu_details md
ON d.id = md.dish_id
WHERE md.daydate = '$dates'
";
$result = mysql_query($query);
}
while($row = mysql_fetch_array($result)) {
echo 'Date: '.$row['daydate'].'Name: '.$row['dish_name'].'<br />';
}
how can i row 'dish_name' for every date on a new row.In the database there are more then 1 row with same date=
You should try to avoid running queries in loops...
Try:
$query = "SELECT md.dish_id, md.daydate, d.id, d.dish_name, d.weight, d.price
FROM dishes d
LEFT JOIN menu_details md ON (d.id = md.dish_id)
WHERE md.daydate BETWEEN '$start_date' AND '$end_date'
GROUP BY md.daydate ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo 'Date: '.$row['daydate'].'Name: '.$row['dish_name'].'<br />';
}
What is the group by for? I think it may cause you to lose some of the results...

Combination of two SQL queries

I have two separate SQL queries that I would like to combine to a single one if possible.
Query #1 yields all entries from a table in random order
Query #2 will afterwards check whether or not the result can be used
How can I achieve this in a single step directly in SQL?
Code:
// start with a query for all of the photos, returned in random order
$query = "
SELECT DISTINCT m.mediaID
, m.description
, m.path
, m.alwayson
, m.usecollfolder
, m.mediatypeID
FROM $media_table m
WHERE m.mediatypeID = 'photos'
ORDER BY RAND();
";
$result = mysql_query($query) or die ("$text[cannotexecutequery]: $query");
while( $imgrow = mysql_fetch_assoc( $result ) ) {
// if the picture is alwayson or we are allowing living to be displayed,
// we don't need to bother
// with any further checking
if ($imgrow[alwayson] || $allow_living_db ) {
break;
// otherwise, let's check for living
} else {
// this query will return rows of personIDs on the photo that are living
$query = "
SELECT l.personID
FROM $medialinks_table l
JOIN $people_table p ON l.personID = p.personID
WHERE l.mediaID = $imgrow[mediaID]
AND p.living = 1
";
$presult = mysql_query($query) or die ("$text[cannotexecutequery]: $query");
$rows = mysql_num_rows( $presult );
mysql_free_result( $presult );
// if no rows are returned, there are no living on the photo, so let's display it
if ($rows == 0) {
break;
}
}
SELECT DISTINCT m.mediaID
, m.description
, m.path
, m.alwayson
, m.usecollfolder
, m.mediatypeID
, l.personID
FROM $media_table m
JOIN $medialinks_table l
ON l.mediaID = m.mediaID
JOIN $people_table p
ON l.personID = p.personID
WHERE m.mediatypeID = 'photos'
AND p.living = 1
ORDER
BY RAND();

Add many-to-many select into existing query

I have a query set up to return comments given from one user to another.
Now we want to allow the ability to rate these comments.
I've added a new table that has 3 fields: comment_id, user_id, and score.
How can I grab an array of {user_id,score} for any comment fetched?
Will I need to loop through the comments after they are fetched and run a second query? This approach could result in adding several extra queries.
Can it be done with a single query?
Here's the function I have now:
function getAllComments($args) {
if(empty($_SESSION['user']['id'])) return false;
$limit = 5;
if(isset($args['limit'])) $limit = $args['limit'];
$page = 1;
if(isset($args['page'])) $page = $args['page'];
$data = array();
$offset = ($page-1)*$limit;
$sql = "SELECT c.*,CONCAT(u1.firstName,' ',u1.lastName) AS owner,u1.title AS ownerTitle,CONCAT_WS(' ',u2.firstName,u2.lastName) AS senderName,u2.title AS senderTitle,a.name AS actionName,a.behavior
FROM comment AS c
JOIN user AS u1 ON c.recipient = u1.id
JOIN user AS u2 ON c.sender = u2.id
JOIN action AS a ON c.action = a.id
WHERE c.type=1";
if(isset($args['location'])) $sql .= " AND u1.location=?";
$sql .= " ORDER BY date DESC";
$sql .= " LIMIT ?";
$sql .= " OFFSET ?";
try {
$db = DB::getInstance();
$stmt = $db->dbh->prepare($sql);
$n = 1;
//THESE MUST STAY IN THE SAME ORDER TO MATCH THE ? PLACEHOLDERS
if(isset($args['location'])) $stmt->bindValue(($n++), $args['location'], PDO::PARAM_INT);
$stmt->bindValue(($n++), $limit, PDO::PARAM_INT);
$stmt->bindValue(($n++), $offset, PDO::PARAM_INT);
$result = $stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = array();
if($result !== false) {
while($row = $stmt->fetch()) {
$rows[] = $row;
}
$data['comments'] = $rows;
return $data;
}else {
logit('Query Failed');
return false;
}
}catch(PDOException $e) {
logit($e->getMessage());
return false;
}
}
If you for example wanted all {comment_id, user_id, score} associated with the comments of user 5, your query would involve an INNER JOIN and look something like:
SELECT s.comment_id, s.user_id, s.score FROM CommentScore s
INNER JOIN Comment c
ON c.comment_id = s.comment_id
WHERE c.user_id = 5

Assistance required converting MySQL function to PDO

I'm currently converting MySQL to PDO, I'm unsure if I wrote this function correctly,I'm also unsure of how to use sqlfiddle, so I resort to Stackoverflow.
If correct, anything to better the current code?
MySQL example :
PUBLIC FUNCTION Insert_Update($_iD, $update, $uploads){
$update = mysql_real_escape_string($update);
$time = time();
$_iP = $_SERVER['REMOTE_ADDR'];
$query = mysql_query("SELECT post_iD,message FROM `Posts` WHERE uid_fk='$_iD' ORDER by post_iD DESC LIMIT 1") or die(mysql_error());
$result = mysql_fetch_array($query);
if ($update!=$result['message']) {
$uploads_array = explode(',',$uploads);
$uploads = implode(',',array_unique($uploads_array));
$query = mysql_query("INSERT INTO `Posts` (message, uid_fk, _iP,created,uploads) VALUES (N'$update', '$_iD', '$_iP','$time','$uploads')") or die(mysql_error());
$newquery = mysql_query("SELECT M.post_iD, M.uid_fk, M.message, M.created, U._iUsername FROM Posts M, users U where M.uid_fk=U._iD and M.uid_fk='$_iD' order by M.post_iD desc limit 1 ");
$result = mysql_fetch_array($newquery);
return $result;
} else {
return false;
}
}
PDO Example:
PUBLIC FUNCTION Insert_Update($_iD, $update, $uploads){
$sth = $this->db->prepare("SELECT post_iD,message FROM `Posts` WHERE uid_fk = :id ORDER by post_iD DESC LIMIT 1")
$sth->execute(array('id' => $_iD));
$result = $sth->FetchAll(PDO::FETCH_ASSOC);
if ( $update!=$result['message'] ){
$uploads_array = explode(',',$uploads);
$uploads = implode(',',array_unique($uploads_array));
$sth = $this->db->prepare("INSERT INTO Posts (message, uid_fk, _iP,created,uploads) VALUES ( :update, :id, :ip, :time, :uploads)")
$sth->bindValue(':update', $update);
$sth->bindValue(':id', $_iD);
$sth->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
$sth->bindValue(':time', time());
$sth->bindValue(':uploads', $uploads);
$sth->execute()
$sth = $this->db->prepare("
SELECT M.post_iD, M.uid_fk, M.message, M.created, U._iUsername
FROM Posts M, users U
WHERE M.uid_fk=U._iD
AND M.uid_fk = :id
ORDER by M.post_iD DESC LIMIT 1 ");
$sth->execute(array(':id' => $_iD));
$result = $sth->FetchAll(PDO::FETCH_ASSOC);
return $result;
} else {
return false;
}
}