如果已经存在,如何向MySQL数据库条目添加数字? [关闭]

问题描述 投票:-2回答:1

我正在为我的网站创建博客输入系统,如果已经有输入URL,我希望它创建相同的URL加一个数字。

因此,以URL“ test”为例,如果URL测试已经存在,我希望它为“ test1”,如果URL“ test1”已经存在,我希望它为“ test2”。

这是我现在(不是真的)正在做的事情:

如您所见,它并不是按照我想要的方式工作。它只能从“ test”变为“ test1”-如何使其动态地无限重命名?

哦,这仅供我个人使用,不需要PDO。

编辑:好的,眉毛跳动后,我收到了将所有内容切换到PDO的信息:

$title = $_POST['title'];
$author = $_POST['author'];
$content = $_POST['content'];

$date = new DateTime('now');
$date = $date->format('Y-m-d');

$domainurl = 'https://test.com/entry.php?';
$maxlength = (75 - strlen($domainurl));

if (strlen($_POST['title']) > $maxlength) {

    $url = wordwrap($_POST['title'], $maxlength);
    $url = substr($url, 0, strpos($url, "\n"));
    $url = strtr(strtolower($url), ' ', '-');

}else{

    $url = strtr(strtolower($_POST['title']), ' ', '-');

}

$url = preg_replace('/[^A-Za-z0-9\-]/', '', $url);

try {
    $options = [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
    \PDO::ATTR_EMULATE_PREPARES => false,
    ];
    $conn = new PDO("mysql:charset=utf8mb4;host=$servername;dbname=$dbname", $username, $password);

    $sql = "SELECT count(*) FROM blog WHERE url = ?"; 

    $sql = $conn->prepare($sql); 
    $sql->execute([$url]); 

    $rowCount = $sql->fetchColumn();

    if ($rowCount >= 1) {

        $url = $url . $rowCount;

    }

    try {

        $sql = $conn->prepare("INSERT INTO blog (date, title, url, author, content) 
        VALUES (:date, :title, :url, :author, :content)");

        $sql->bindParam(':date', $date);
        $sql->bindParam(':title', $title);
        $sql->bindParam(':url', $url);
        $sql->bindParam(':author', $author);
        $sql->bindParam(':content', $content);

        $sql->execute();

        $rowCount = $sql->rowCount();
        $id = $conn->lastInsertId();

        if ($rowCount > 0) {

            echo json_encode(array ('type' => 'success', 'message' =>"Blog entry created successfully"));

        }else{

            echo json_encode(array ('type' => 'danger', 'message' =>"Blog entry <strong>not</strong> created successfully"));

        }

    }catch(PDOException $e){

        echo json_encode(array ('type' => 'danger', 'message'=>$e->getMessage()));

    }

}catch(PDOException $e){

    echo json_encode(array ('response'=>'error','errorMessage'=>$e->getMessage()));
}
    $conn = null;
php mysql url dynamic
1个回答
0
投票

尝试一下:

© www.soinside.com 2019 - 2024. All rights reserved.