0

I'm using URL hashes to request data from my database, such as "url.com/content/book.html#132" in this format:

$(document).ready(function(){
          var number = window.location.hash.substr(1);

        $.ajax({
            type:'POST',
            url:'./db/db.php',
            dataType: "json",
            data:{number:number},
            success:function(data){
 
                if(data.status == 'ok'){
                    $('#title').text(data.result.title);
                    $('#author').text(data.result.author);
                    $('#genre').text(data.result.genre);
                   etc...
                } 
            }
        });
    });

and in PHP:

<?php

if(!empty($_POST['number'])){
    $data = array();
    
    //database details
    $dbHost     = '******';
    $dbUsername = '******';
    $dbPassword = '******';
    $dbName     = '******';
    
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
    if($db->connect_error){
        die("Unable to connect database: " . $db->connect_error);
    }
    
    $query = $db->query("SELECT * FROM db WHERE id = {$_POST['number']}");
    
    if($query->num_rows > 0){
        $userData = $query->fetch_assoc();
        $data['status'] = 'ok';
        $data['result'] = $userData;
    }else{
        $data['status'] = 'err';
        $data['result'] = '';
    }
    
    echo json_encode($data);

}
?>

This works perfectly. However, I'd also like to pull up data on another page based on genre, which I would also like to set with the URL, as in

"url.com/content/genre.html#history"

In my ajax, I simply changed the variable to 'genre' and data:{genre:genre}. In my PHP I'm selecting like this:

$query = $db->query("SELECT * FROM db WHERE genre = {$_POST['genre']}");

but it doesn't work and I even get a blank when testing with print_r ($_POST['genre']); and a console.log(gengre); shows the hash is being read correctly. What am I missing?

Niwa
  • 67
  • 1
  • 5
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Jan 14 '22 at 11:19

1 Answers1

0

For those interested, I found the answer, and of course it was much simpler than I was expecting. JSON.stringify()

So:

var hash = window.location.hash.substr(1);
var genre = JSON.stringify(hash);

This turns the value into a json object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Niwa
  • 67
  • 1
  • 5