php脚本中的MySQL错误


MySQL errors in php script

我们正在工作场所(高中)开发一个服务台系统。我们将在网站上发布一些用户手册,并建立数据库。

$sql = "INSERT INTO usermanual (title, link, slug) VALUES ('$title', '$link', '$slug')";

这是我们从表单中获得的代码:

<form action="inc/publish-manual.php" method="post" accept-charset="ISO-8859-1">
    <p>
        <label for="Title">Tittel:</label>
        <br>
        <input type="text" name="title" id="title">
    </p>
    <p>
        <label for="Link">Link til brukerveiledning:</label>
        <br>
        <input type="text" name="link" id="link">
    </p>
    <p>
        <label for="Slug">Slug:</label>
        <br>
        <input type="text" name="slug" id="slug">
    </p>
    <input type="submit" value="Publiser">
</form>

当我们运行这个时,我们只会得到一个错误:

ERROR: Was not able to execute INSERT INTO usermanual (title, link, slug) VALUES ('test', 'http://gauldal.vgs.no/upload/Gauldal/Bilder/Brukerveiledninger-IKT/Bruke%20Larermentor.pdf', 'test')

当我们在数据库中运行SQL时,它可以工作,但不能从脚本中运行。我们已经研究了很长时间,现在我们需要一双新的眼睛来看看错误在哪里。

<?php
header('Content-type: text/html; charset=ISO-8859-1');
include '../config.php'; 
$link = mysqli_connect($servername, $username, $password, $dbname);
if ($link === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
$title = mysqli_real_escape_string($link, $_POST['title']);
$link = mysqli_real_escape_string($link, $_POST['link']);
function slugify($title)
{ 
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $title);
    return strtolower(preg_replace('/[^A-Za-z0-9-]+/', '-', $title));
}
$slug = slugify($title);
$sql = "INSERT INTO usermanual (title, link, slug) VALUES ('$title', '$link', '$slug')";
if (mysqli_query($link, $sql)) {
    header("location: ../admin.php");
} else {
    echo "ERROR: Was not able to execute $sql " . mysqli_error($link);
}
?>

我建议将数据库链接重命名为$connection:

$link = mysqli_connect($servername, $username, $password, $dbname);

因为看起来很混乱,您的代码中有两个不同的"链接"变量,这可能是

的问题
<?php
header('Content-type: text/html; charset=ISO-8859-1');
include '../config.php'; 
$link = mysqli_connect($servername, $username, $password, $dbname);
if ($link === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
$title = mysqli_real_escape_string($link, $_POST['title']);
$link = mysqli_real_escape_string($link, $_POST['link']);
function slugify($title)
{ 
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $title);
    return strtolower(preg_replace('/[^A-Za-z0-9-]+/', '-', $title));
}
$slug = slugify($title);
$sql = "INSERT INTO usermanual (title, link, slug) VALUES ('$title', '$link', '$slug')";
if (mysqli_query($link, $sql)) {
    header("location: ../admin.php");
} else {
    echo "ERROR: Was not able to execute $sql " . mysqli_error($link);
}
?>

这是publish-manual.php文件。我使用配置文件连接到数据库。

这是一个我们在许多文件上都有的系统,它适用于所有文件,但不是这个。