简体   繁体   中英

Get parent id from child id SQL PHP

I have data in table, and want get top of ID (parent id from child ID).

id (primary_key)        item_id             secondary_item_id
464                     449                 449
465                     449                 464
467                     449                 465

From this table i want get id '464' from id '467' . I try:

$parent_id = $wpdb->get_var( "
    SELECT id
    FROM {$bp->activity->table_name}
    WHERE id = 467
" );

But return 465 , i want 464 . And i want use just one query., not multiple query. Please help.

use ORDER BY id DESC in mysql query

<?php
$parent_id = $wpdb->get_row( "
    SELECT ID
    FROM {$bp->activity->table_name}
    WHERE id = 467 ORDER BY `id` DESC 
" );
?>
$reply = 467; 
for ($x = 1; $x <= 2; $x++) { 
$reply = $wpdb->get_var( " 
SELECT secondary_item_id 
FROM {$bp->activity->table_name} 
WHERE id = $reply 
" ); 
} 

Change it to this like we discussed in the Chat. You used the wrong SELECT .

Documentation of wordpress functions: https://developer.wordpress.org/reference/classes/wpdb/

Perhaps you might change the for loop and use another function which wordpress provides. I've not used wordpress before, so I can not tell you which one should be used. If you (or anyone else) might know it, I can change this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM