执行查询后显示ERROR / Success消息

时间:2017-01-20 11:04:15

标签: php mysql

我正在尝试创建一个HTML表单,我可以输入MYSQL查询并通过PHP运行它们。我现在使用此代码我想在执行查询后显示ERROR / Success消息

 <?php   
    if(isset($_POST['submit']) && !empty($_POST['query'])){ 
$query =  $_POST['query'];      
 mysql_query($query);

}

    ?> 

<form action="" method="post"> 
    <div> 
        <textarea name="query"></textarea> 
        <input type="submit" name="submit" value="submit" /> 
    </div> 
</form>  

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望能够通过用户输入运行MySQL查询吗?只需将提交按钮重定向到抓取用户输入的PHP脚本(例如$ _REQUEST ['query']),然后连接并查询数据库。 代码示例:

PHP:

<?php

    /* query.php */
    $query = $_REQUEST['query']; //do SQLi prevention
    $conn  = new mysqli('localhost', 'root', '', 'db');
    if($conn->connect_error) throw new \Exception('Failed to connect to MySQL server.'); //have the script handle the exception elsewhere
    if($conn->query($query) !== false)
    {
        echo 'Query executed successfully.';
    }
    else
    {
        throw new \Exception('MySQL error: ' . $conn->error); //have the script handle the exception elsewhere
    }
    $conn->close();

HTML:

<!DOCTYPE html>
  <!-- index.html -->
  <html>
    <head>
    </head>
    <body>
      <form method='POST' action='query.php'>
        <input type='text' name='query' />
        <br />
        <input type='submit' />
      </form>
    </body>
  </html>