这是我的代码。但我有一个问题。
if ($kundevor!="" or $kundenach!="")
{
if ($kundevor=="")
{
$kundezusatz=" WHERE Nachname LIKE '$kundenach%'";
}
else if ($kundenach=="")
{
$kundezusatz=" WHERE Vorname LIKE '$kundevor%'";
}
else
{
$kundezusatz=" WHERE (Vorname LIKE '$kundevor%') OR (Nachname LIKE '$kundenach%')";
}
$sql = $dbh->prepare ("SELECT Nachname, Vorname FROM tblkunden $kundezusatz ");
$sql->execute() or die("SQL Fehler in: ".$sql->queryString." <br /> ".$sql->errorInfo()[2]);
echo "<table>";
echo '<p class="abfrage2">Abfrage 3:</p>';
echo"<tr><th>Nachname</th><th>Vorname</th></tr>";
while($ds = $sql->fetch())
{
echo "<tr><td>$ds[Nachname]</td><td>$ds[Vorname]</td></tr>";
}
}
例如,如果有人在我的表单中输入一个既不像&#34; Vorname&#34; (=名字)也不喜欢&#34; Nachname&#34; (=姓氏)它什么也没显示。但是我希望有一条消息,例如&#34;抱歉,但是你的信件都没有与数据库中的名字匹配&#34;。
如何在此代码中实现这一目标?
答案 0 :(得分:0)
评论:你的陈述准备被错误地应用并且失去了它的目的:避免sql injection。不应将任何值直接传递给sql语句。相反,parameter markers(已命名或未命名)应在声明中定义 - 作为占位符。对于这些标记中的每一个,必须通过调用bindValue方法或bindParam方法或将其定义为直接作为参数传递给{{{}的数组中的元素值来传递相应的值。 3}}方法。
一些建议:
while($ds = $sql->fetch()){...}
所做的那样)一部分)。下面是一个代码版本,我在其中实现了您的任务/问题的解决方案。我使用了自己的命名/编码约定(包括db表) - 所以,我会在我自己的项目中应用它们。
由于您没有指定您正在使用的库( PDO 或 mysqli ),并且因为只有PDO具有 PDOStatement :: errorInfo 方法,我扣除您使用 PDO 库。因此,我的代码使用 PDO 。
<?php
require 'connection.php';
if (isset($_POST['submit'])) {
$nachname = isset($_POST['nachname']) ? $_POST['nachname'] : '';
$vorname = isset($_POST['vorname']) ? $_POST['vorname'] : '';
if (empty($nachname) && empty($vorname)) {
$errors[] = 'Please provide either the first name, or the last name, or both.';
}
if (!isset($errors)) {
// Array used for creating the WHERE conditions in the sql statement.
$whereConditions = [];
/*
* Used for injecting the proper values for the named parameter markers found
* in the sql statement. It is passed as argument to the PDOStatement::execute method.
*/
$inputParameters = [];
if (!empty($nachname)) {
$whereConditions[] = 'nachname LIKE :nachname';
$inputParameters[] = '%' . $nachname . '%';
}
if (!empty($vorname)) {
$whereConditions[] = 'vorname LIKE :vorname';
$inputParameters[] = '%' . $vorname . '%';
}
$sql = sprintf(
'SELECT kunde_id, nachname, vorname FROM kunden WHERE %s'
, implode(' OR ', $whereConditions)
);
$statement = $connection->prepare($sql);
$statement->execute($inputParameters);
$kunden = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!$kunden) {
$errors[] = 'No clients found for your request.';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#nachname').focus();
});
</script>
<style type="text/css">
body {
padding: 30px;
}
label {
/*display: block;*/
font-weight: 400;
}
input[type="text"] {
display: block;
margin-bottom: 20px;
}
button {
display: block;
padding: 7px 10px;
background-color: #8daf15;
color: #fff;
border: none;
}
.messages {
margin-bottom: 20px;
}
.messages .error {
color: #c00;
}
.kunden-list {
margin-top: 20px;
border-collapse: separate;
}
.kunden-list thead th {
padding: 10px;
background-color: #ccc;
}
.kunden-list tbody td {
padding: 10px;
}
</style>
</head>
<body>
<div class="messages">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="error">
<?php echo $error; ?>
</div>
<?php
}
}
?>
</div>
<div class="form-container">
<form action="" method="post">
<label for="nachname">Nachname:</label>
<input type="text" id="nachname" name="nachname" value="<?php echo isset($nachname) ? $nachname : ''; ?>">
<label for="vorname">Vorname:</label>
<input type="text" id="vorname" name="vorname" value="<?php echo isset($vorname) ? $vorname : ''; ?>">
<button type="submit" name="submit" value="submit">
Senden
</button>
</form>
</div>
<?php
if (isset($kunden) && $kunden) {
?>
<table class="kunden-list">
<thead>
<tr>
<th>ID</th>
<th>Nachname</th>
<th>Vorname</th>
</tr>
</thead>
<tbody>
<?php
foreach ($kunden as $kunde) {
$kundeId = $kunde['kunde_id'];
$nachname = $kunde['nachname'];
$vorname = $kunde['vorname'];
?>
<tr>
<td><?php echo $kundeId; ?></td>
<td><?php echo $nachname; ?></td>
<td><?php echo $vorname; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</body>
</html>
<?php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'yourDb');
define('USERNAME', 'yourUser');
define('PASSWORD', 'yourPassword');
define('CHARSET', 'utf8');
/*
* Create a PDO instance as db connection to db.
*
* @link http://php.net/manual/en/class.pdo.php
* @link http://php.net/manual/en/pdo.constants.php
* @link http://php.net/manual/en/pdo.error-handling.php
* @link http://php.net/manual/en/pdo.connections.php
*/
$connection = new PDO(
sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', HOST, PORT, DATABASE, CHARSET)
, USERNAME
, PASSWORD
, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE,
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
CREATE TABLE `kunden` (
`kunde_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nachname` varchar(100) DEFAULT NULL,
`vorname` varchar(255) DEFAULT NULL,
PRIMARY KEY (`kunde_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
答案 1 :(得分:-1)
计算从数据库中获取的行(结果)。
如果计数为零,则显示“未找到结果”消息。
如果有结果,则在输出第一行之前注意显示表头。
$count = 0; // This keeps track of the rows fetched
while($ds = $sql->fetch())
{
// Before the first row let's put the table header
if( $count === 0 )
{
echo "<table>";
echo '<p class="abfrage2">Abfrage 3:</p>';
echo"<tr><th>Nachname</th><th>Vorname</th></tr>";
}
// Output the row
echo "<tr><td>$ds[Nachname]</td><td>$ds[Vorname]</td></tr>";
// Update the row count
$count++;
}
// No rows/results? display the message
// Otherwise close the table
if( $count === 0 )
{
// Display "no matches" message ex:
echo "<div class='some-class'>Sorry, but none of your letters match with the Names in the database</div>";
}
else
{
echo "</table>";
}
请注意,您的代码不安全,因为它容易出现sql注入。
使用Prepared Statements将用户数据注入查询。
当您在LIKE
语句后接受用户输入并将其放入查询中时,必须在输入字符串中转义%
通配符。请参阅this question已接受的答案。
最后,在使用它们之前,您应该trim() $kundevor
和$kundenach
;确保在某些时候关闭<table>
html,我将代码放在while循环之后。你有一些修复可以照顾......