本文介紹了具有PHP和PDO的獨特配置文件插件的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在使用一個類生成要插入的字符串名稱配置文件,然后使用SQL命令告訴我要在INSERT命令中使用的唯一值是什么,問題是該命令不能正常工作,有時可能會返回已經(jīng)存在的值.
這就是我用來生成slug的類:(Composer需要channel aveer/slug)
這是示例代碼:
use ChannaveerSlugSlug;
$string = "john doe";
$slug = Slug::create($string);
$profile_count_stmt = $pdo->prepare("
SELECT
COUNT(`id`) slug_count
FROM
`advogados_e_escritorios`
WHERE
`slug_perfil` LIKE :slug
");
$profile_count_stmt->execute([
":slug" => "%".$slug."%"
]);
$profile_count = $profile_count_stmt->fetchObject();
if ($profile_count && $profile_count->slug_count > 0) {
$profile_increment = $profile_count->slug_count + 1;
$slug = $slug . '-' . $profile_increment;
}
echo 'Your unique slug: '. $slug;
// Your unique slug: john-doe-5
這是腳本運行時的表內(nèi)容:
您知道如何改進SELECT命令以防止它從數(shù)據(jù)庫返回現(xiàn)有的插件嗎?
推薦答案
您應該檢查數(shù)據(jù)庫中是否存在該輔助程序。如果它已經(jīng)存在,則可以附加一些隨機字符串,如下所示
$slug = Slug::create($string);
$slugExists = "DB query to check if the slug exists in your database then you may return the count of rows";
//If the count of rows is more than 0, then add some random string
if($slugExists) {
/** NOTE: you can use primary key - id to append after the slug, but that has to be done after you create the user record. This will help you to achieve the concurrency problem as @YourCommenSense was stating. */
$slug = $slug.time(); //time() function will return time in number of seconds
}
//DB query to insert into database
我的博客文章(StackCoder)也遵循了同樣的原則。即使是LinkedIn也遵循同樣的方式。
以下是LinkedIn URL的屏幕截圖
這篇關于具有PHP和PDO的獨特配置文件插件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,