douying6206 2014-10-18 00:53
浏览 22
已采纳

HTML表单到PHP如何返回值而不是显示文件?

I've made a HTML file containing only a form with a textbox and a submit button.

The form calls a php that will check if the text from the textbox represents a register in the database.

Html file:

<form action="index.php" method="post">
<input type="text" name="nome"/>
<input type="submit" value="Rodar"/>
</form>

PHP file:

<?php

$nome = $_POST['nome'];
$pdo = new PDO('mysql:host=myhost;dbname=mydb', 'user', 'pw');

if ($pdo->query("SELECT * from renatinho where nome='".$nome."'")->fetchColumn() > 0){
    foreach($pdo->query("SELECT * from renatinho where nome='".$nome."'") as $row) {
        echo $row['id'] . $row['nome'];
    }
    $pdo = null;
}
else{
    echo "Não há ninguém com esse nome.";
}
?>

The thing is: when I press the button it calls and displays the php file. The php file has no layout. I want the results to be displayed in the HTML file, cause i don't want to make a whole new page just to display the values.

I want the results to be in the same page where the form is.

I've being googling it for 2 days, but I don't know what exactly to search. All the results I got are tutorials that displays the php file, and that's what I'm doing now but that's not what I want.

  • 写回答

3条回答 默认 最新

  • douzhan8395 2014-10-18 01:07
    关注

    You have a few options:

    1. Combine the two files into one PHP file that has both HTML and PHP. Put your PHP code at the top of the script. Check if the form is being submitted like this: if ($_POST['submit'] == 'Rodar') { /* process form */ }. If the form was not submitted, your code that processes the form will be skipped and the form will just be displayed. If the form has been submitted, it will be processed and the form will be displayed again. This is probably the most common solution.
    2. After processing the form in your PHP file, redirect back to the HTML file using header('Location: html_file.html'); die();. Just make sure you don't output anything to the screen before doing this (ie. echo).
    3. You could submit your form using AJAX. This is a JavaScript call over HTTP to your server without reloading the page. Just google AJAX and you'll find a boatload of tutorials.

    For clarification, it seems like you may not realize that you can combine HTML and PHP in a .php file. you can do this. You just either echo the HTML to the screen, or break out of your <?php tag with a ?> tag and start writing your HTML.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序