我正在尝试创建一个 HTML 表单,我可以输入 MYSQL 查询并通过 PHP 运行它们。我现在使用此代码,我想在执行查询后显示错误/成功消息
<?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>
最佳答案
如果我理解正确的话,您希望能够通过用户输入运行 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>
关于php - 执行查询后显示错误/成功消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41762135/