Doubt on MySQL Query

0

What code do I need to display all posts for a user? I did something like this in PHP:

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

But always returns 0 rows: (

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;
    
asked by anonymous 21.03.2018 / 18:45

1 answer

0

Understand what your SQL is doing:

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

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

I imagine you want something like this:

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

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

CAUTION: This code is subject to attacks SQL Injection

    
21.03.2018 / 19:02