Home » Php » php – Mysql query join tables is unable to use where condition

php – Mysql query join tables is unable to use where condition

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am developing a WordPress website, I need to get join table values using where condition.Now I can able to get values with out using where but its showing multiple values, I didn’t get correspond values for particular id. If i use where i am getting error. I have given below my code.

$result = $wpdb->get_results("SELECT 
    wp_candiform.numFormCand,
    wp_candiform.questionCand,
    wp_candiform.civilCand,

    wp_diplom.annee,
    wp_diplom.titre,
    wp_diplom.nive,

    wp_formation.CandFDQ,
    wp_formation.titreCandFDQ,
    wp_formation.mention,

    wp_confirmation.etatand,
    wp_confirmation.comment,
    wp_confirmation.etat1Cand

    FROM wp_candiform
    INNER JOIN wp_diplom ON wp_candiform.user_id = wp_diplom .user_id
    JOIN wp_formation ON wp_candiform.user_id = wp_formation .user_id
    JOIN wp_confirmation ON wp_candiform.user_id = wp_confirmation .user_id
    WHERE user_id='$user_id'"
    );
How to&Answers:

Since you are joining tables, you need to mention which table’s userid is compared in the Where condition.

While using the where condition, you need to add the table alias to the Where condition.

Refer to the below code.

$result = $wpdb->get_results("SELECT 
    wp_candiform.numFormCand,
    wp_candiform.questionCand,
    wp_candiform.civilCand,

    wp_diplom.annee,
    wp_diplom.titre,
    wp_diplom.nive,

    wp_formation.CandFDQ,
    wp_formation.titreCandFDQ,
    wp_formation.mention,

    wp_confirmation.etatand,
    wp_confirmation.comment,
    wp_confirmation.etat1Cand

    FROM wp_candiform
    INNER JOIN wp_diplom ON wp_candiform.user_id = wp_diplom .user_id
    JOIN wp_formation ON wp_candiform.user_id = wp_formation .user_id
    JOIN wp_confirmation ON wp_candiform.user_id = wp_confirmation .user_id
    WHERE wp_candiform.user_id='$user_id'"
    );

Answer:

Everything is fine in your code just a minor mistake in query. At the end

WHERE user_id='$user_id'

to

WHERE wp_candiform.user_id='$user_id'