简体   繁体   中英

Mysql Return all values of a table where column is equal to user input

I have some sql statements that accepts a number and if that number is equal to the value of a column in a database, it should return all rows in the database that has the same value. Unfortunately the rows only return blog_post_id that has a value 0.

This is my codes below:

<?php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$blog_post_id = !empty($_POST['blog_post_id']) ? $_POST['blog_post_id'] 
: '';

$pdo=new PDO("mysql:dbname=db;host=localhost","username","password", 
$options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id = 
'$blog_post_id'");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
if ($json)
    echo $json;
else
    echo json_last_error_msg();

?> 

You are actually missing the point of using the function prepare() and you need to check if the query does actually return any results..

<?php
$options      = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
);
$blog_post_id = !empty($_POST['blog_post_id']) ? $_POST['blog_post_id'] : '';

$pdo       = new PDO("mysql:dbname=db;host=localhost", "username", "password", $options);
$statement = $pdo->prepare("SELECT * FROM comment WHERE blog_post_id = ?");
$statement->execute([$blog_post_id]);
$results   = $statement->fetchAll(PDO::FETCH_ASSOC);

$json = array();

if (count($results) > 0) {
    foreach ($results as $row) {
        $json[] = array(
            'id' => $row['blog_post_id'],
            'Field' => $row['Column'],
            'AnotherField' => $row['AnotherColumn'],
            'AnotherField1' => $row['AnotherColumn1'],
            'ETC' => $row['AnotherColumnName']
        );
    }

    echo json_encode($json);
} else {

    echo "no data found";
}

?> 

You should do variable binding like so:

$pdo=new PDO("mysql:dbname=db;host=localhost","username","password", $options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id = :blog_post_id");
$statement->execute(['blog_post_id' => $blog_post_id]);

This will also prevent 1st level SQL-Injection as described here: Are PDO prepared statements sufficient to prevent SQL injection?

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