Doubt about Mysql Query

Asked

Viewed 41 times

0

What code is required to display all a user’s posts? I did something like this in PHP:

"SELECT * FROM postagens WHERE id='$p_id' AND u_id='$u_id';";

But always returns 0 lines :(

CREATE DATABASE IF NOT EXISTS social
DEFAULT CHARACTER SET utf8
DEFAULT COLLATE utf8_general_ci;
USE social;
CREATE TABLE IF NOT EXISTS usuarios(
    id INT NOT NULL AUTO_INCREMENT,
    nome VARCHAR(24) NOT NULL,
    sobrenome VARCHAR(64) NOT NULL,
    email VARCHAR(50) NOT NULL UNIQUE,
    senha VARCHAR(16) NOT NULL,
    sexo enum('M','F'),
    perfil VARCHAR(512) NOT NULL,
    capa VARCHAR(512) NOT NULL,
    recado VARCHAR(256) NOT NULL,
    CONSTRAINT u_id_pk PRIMARY KEY(id)
) DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS postagens(
    id INT NOT NULL AUTO_INCREMENT,
    u_id INT,
    titulo VARCHAR(128) NOT NULL,
    conteudo VARCHAR(4096),
    imagem VARCHAR(256),
    video VARCHAR(256),
    audio VARCHAR(256),
    CONSTRAINT id_pk PRIMARY KEY(id),
    CONSTRAINT u_id_fk FOREIGN KEY(u_id) REFERENCES postagens(id)
) DEFAULT CHARSET=utf8;
  • 1

    already checked if the ids that are coming (p_id and u_id) exist in the bank?

  • And using id='$p_id' will only return a record.

  • ids exist and about returning only 1 is purposeful because I have a function in php to pick one at a time

1 answer

0


Understand what your SQL is doing:

SELECT * FROM postagens WHERE id = '$p_id' AND u_id = '$u_id';

Selects all table columns posts if the post id is equal to $p_id and the user id is equal to $u_id, ie will return a record in which the id is equal to the assigned

I imagine you want something like this:

SELECT * FROM postagens WHERE u_id = '$u_id';

The same thing but without the condition id = '$p_id', this returns all the table posts records of a particular user

CARING: That code of yours is subject to attack SQL Injection

Browser other questions tagged

You are not signed in. Login or sign up in order to post.