0

I am fetching a data according to the table name, but I also need to send the table name to the front end along with the data. I have this code.

$sql_fetchItems = "select * from `$cat`";
        $result_fetchItems = mysqli_query($connection, $sql_fetchItems);
        for ($j; $j < mysqli_num_rows($result_fetchItems); $j++) {
            echo ($j > 0 ? ',' : '') . json_encode(mysqli_fetch_object($result_fetchItems));
        }

where the objects will be encoded and sent to the front-end. if I add ",{$cat}" within the for statement, it will become another object of course. But is there a way to send the table name along with the object? Like in the JS console, it should receive {"name": "1", "category", "something", "something": "something"}?

Kyi Zin
  • 823
  • 1
  • 6
  • 15
  • 1
    Why are you `echo`ing inside a loop? – Anurag Srivastava Mar 08 '20 at 16:23
  • Sending table names from front-end looks bad to me. It's insecure and not the right way to achieve things. – nice_dev Mar 08 '20 at 16:24
  • Of course, to send data to the react front-end @AnuragSrivastava – Kyi Zin Mar 08 '20 at 16:24
  • I am not showing the table name or doing anything with it, it will just be resent to the back-end in to serve another function. I am doing an e-commerce and since I have an "All" option in the `select tag` where all of the items will be shown, i cannot get the right category name. @vivek_23 – Kyi Zin Mar 08 '20 at 16:26
  • 1
    @KyiZin Well typically, you would use a PHP variable to add the results in the loop and echo that variable. You can add the table name easily to that variable using `$cat` – Anurag Srivastava Mar 08 '20 at 16:28
  • @KyiZin What is someone inspects the page and edits the value as `table_name; drop table tablename;`. You need to use bind params etc to prevent SQL injection, but even then why expose the table name to people? Also, a select dropdown will have values belonging to a table rather than deciding table names to fetch from. – nice_dev Mar 08 '20 at 16:29
  • @vivek_23 it is just my final school project, so I wouldn't so care about security issues right now although i do know exposing data is not a good practice – Kyi Zin Mar 08 '20 at 16:32
  • @AnuragSrivastava I do get your idea but, since `json_encode(mysqli_fetch_object($result_fetchItems))` returns a string and ends in }], is there a way to append that string ? – Kyi Zin Mar 08 '20 at 16:34
  • 1
    You don't need `json_encode` until you are ready to return data using `echo` – Anurag Srivastava Mar 08 '20 at 16:35
  • 1
    Oh, I just got it, thank you mr. @AnuragSrivastava – Kyi Zin Mar 08 '20 at 16:35

0 Answers0