0

我希望能够找到所有借用特定 CD 并且必须在特定日期之前归还的客户的姓名和电话号码。

我为 CD(标题、类型、年份)和租金(租金数据、持续时间)设置了表格。

我的尝试如下:

$query = "SELECT name, tel FROM customer WHERE '$_POST[cd_title]'  AND '$_POST[rent_date]'; ";
$result = mysqli_query($con, $query);

while($row = mysqli_fetch_array($result))
{
 echo "<tr>";
 echo "<td>" . $row['name'] . "</td>";
 echo "<td>" . $row['tel'] . "</td>";
 echo "</tr>";
 }
echo "</table>";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
 }
echo "1 record found and listed";

但是,什么都没有出现,除了 die 语句(错误:)之外,我没有收到任何错误。在这一点上,我无法判断出了什么问题。我假设这是我的查询,但它出了什么问题?

4

4 回答 4

1

您忘记了WHERE子句中的列名

尝试这个

$query = "SELECT name, tel FROM customer WHERE columnNameForTitle = '$_POST[cd_title]'  AND columnNameForRentDate = '$_POST[rent_date]'; ";

这是带有 WHERE 子句的 SQL 查询的语法

于 2013-05-23T12:19:32.630 回答
1

您在查询中缺少一个条件;您需要在WHERE谓词上添加一个条件。

当您使用mysqli时,您可以使用准备好的语句。以下内容改编自文档:

$q = "SELECT name, tel FROM customer WHERE title = ? AND rent_date = ?";

$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt =  $mysqli->stmt_init(); # Initialize a statement
$stmt->prepare($q); # prepare it with the query
$stmt->bind_param("ss", $_POST['title'],$_POST['rent_date']);
$stmt->execute();
$stmt->bind_result($name, $tel); # Set the return values

# Fetch results
while ($stmt->fetch()) {
    echo "<tr>";
    echo "<td>" . $name . "</td>";
    echo "<td>" . $tel . "</td>";
    echo "</tr>";
}

$stmt->close(); # close the statement

关键行是bind_param,它接受您的输入并将其绑定到准备好的语句;它还负责正确转义您的输入。

您的语句中的每个?都是一个占位符(称为参数)。您将在其中放置变量(这称为绑定)。因此,您必须知道bind_param每个变量的类型?,以便它可以正确转换/转义值。

类型有:

Character   Description
i           corresponding variable has type integer
d           corresponding variable has type double
s           corresponding variable has type string
b           corresponding variable is a blob and will be sent in packets

由于您的查询中有两个?s,并且它们都是字符串,这就是您s在调用中看到两个 s 的原因。然后在逗号之后,键入保存要发送到数据库的值的变量。类型的数量必须与数量相匹配?,当然您还需要传入相同数量的值。

于 2013-05-23T12:22:09.683 回答
0

您的查询应包含用于获取记录的列名。就像是:

"SELECT name, tel FROM customer WHERE field1 = 'value' AND field2 = 'value2'";
于 2013-05-23T12:21:46.663 回答
0

为了代码可读

// Change cd_title and rent_date with your columns names
$query = "SELECT name, tel FROM customer WHERE cd_title = '{$_POST["cd_title"]}' AND rent_date = '{$_POST["rent_date"]}';";

$result = mysqli_query($con, $query);

while($row = mysqli_fetch_array($result)){
    // HEREDOC for html readability, see http://www.php.net/manual/pt_BR/language.types.string.php#language.types.string.syntax.heredoc
    echo <<<HTML
    <tr>
        <td>{$row["name"]}</td>
        <td>{$row["tel"]}</td>
    </tr>
HTML;

}

echo "</table>";

if (!mysqli_query($con,$sql)){
    die('Error: ' . mysqli_error($con));
}

echo "1 record added";

我希望它有效。

于 2013-05-23T12:31:33.297 回答