-1

Example I have a code select data in sever

$sql = "SELECT * FROM ..."
$result = mysqli_query($conn,$sql)
$row = array()
if($result){
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}

I often use ajax to show data in html . But I see some people render in html by php like

index.html

<div> <?php echo $row ?> </div>

I think it not good but i dont know why . Please explain for me. Many thanks

  • Unless you instructed your system to treat `.html` files as php, you will need to change the extension to `.php`. That, or use ajax and making a call to a php file. – Funk Forty Niner Apr 16 '17 at 15:37
  • 1
    I think this question is *too broad*, as this obviously depends on the context. In general, nothing is wrong with either approach. – domsson Apr 16 '17 at 15:38
  • This question falls under too broad/unclear and opinion-based. Or even a possible duplicate of [Using .htaccess to make all .html pages to run as .php files?](http://stackoverflow.com/questions/4687208/using-htaccess-to-make-all-html-pages-to-run-as-php-files) – Funk Forty Niner Apr 16 '17 at 15:39
  • I just only want know write php in html page good or bad . And now I know my opinion is wrong – Nguyễn Bảo Dũng Apr 16 '17 at 15:46
  • 1
    that's entirely up to you; there is no good or bad, only pros and cons and what your server will support. Now the question IMHO, is opinion-based. *"Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise."* – Funk Forty Niner Apr 16 '17 at 15:48

1 Answers1

0

It's not a 'bad practice' but rather a choice of user experience. It depends on the fact that if or not you have the records to be shows while the page is being rendered by php or not. Let me give you two use use cases :

  1. You already know that user is on this page to see the records for row-39, you get this details from some other action like a form submit in the previous page or from url which reads example.php?showMe=row-39 In this case, you'll fetch the row 39 while the page is being rendered and add the result then and there like

    Your data:

  2. Your database has 10K records and you are not sure which one the user is looking for. In that case,for security reasons (row-39 is not meant to be seen by current user) or for simply speed issues (fetching 10K records take time and so does transferring them to the user) you can't put in those records on the page and later hide what user doesn't have to see. In such cases, you'd take the row number that user wants to see through some active like a input box, fetch that row with AJAX and show it to the user.

Now, note how 'case 2' takes more time to effectively show the data to user (first user interaction, ajax, network transfer etc) and this is why you'd want to use the 'case 1' whenever you already know what to show user

Mayank Raj
  • 1,574
  • 11
  • 13