javascript - 如果值已经存在,如何将字符添加到值的末尾?

标签 javascript php jquery

在这里,当我点击发布按钮时,它会在数据库中插入一个随机值。
如果数据库中已存在一个值,则显示错误。它工作正常。

但是如果它已经存在于数据库中,我想在值的末尾添加 2/3 个字符。如果 $check == 1 那么我想在值的末尾添加一些字符而不是显示警报。如何做到这一点?

<?php 

$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");

if(isset($_POST['submit']))
{
    $slug = $_POST['rand'];
    $get_slug = "select * from slug where post_slug='$slug' ";
    $run_slug = mysqli_query($con,$get_slug );
    $check = mysqli_num_rows($run_slug );

    // if $check==1   then i want to add 2  characters at the end  of $slug .  

    if($check == 1)
    {
        //  instead of showing alert i want to add 2 more characters at the end of that value and and insert it on database

        echo "<script> alert('something is wrong') </script> ";
        exit ();
    }
    else
    {
        $insert ="insert into slug (post_slug) values ('$slug') "; 

        $run = mysqli_query($con,$insert);

        if($run)
        {
            echo "<p style='float:right;'> Posted  successfully </p>";
        }
    }
}
?>

<form method="POST" >
<?php
    $result = "";

    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $chararray = str_split($chars);
    for($i = 0; $i < 7 ; $i++)
    {
$randitem = array_rand($chararray);
        $result .= "".$chararray[$randitem];
    }
    echo $result ;
?>

    <input type="hidden" value="<?php echo $result;?>" name="rand" />

    <span class="input-group-btn">
        <button class="btn btn-info"  type="submit" name="submit">POST</button>
    </span>
</form>   

最佳答案

如果 $check == 1 就运行更新查询

if($check == 1){
$newSlug = $slug."xy";    
$update = "update slug set post_slug = '".$newSlug."' where post_slug = '".$slug."'";
        $run = mysqli_query($con,$update );
        echo "<script> alert('Updated Successfully') </script> ";
        exit ();

}

关于javascript - 如果值已经存在,如何将字符添加到值的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41438239/

相关文章:

jquery - 原型(prototype): Detect Chrome and Add Class

javascript - 将本地 HTML 加载到 Div(Chrome 扩展)

javascript - 如果默认情况下 JavaScript 既不是异步的也不是多线程的,为什么新手通常认为它是(尤其是与其他语言相比)?

javascript - 无法显示 html 表中的所有值

javascript - jQuery ajax跨域调用及权限问题

PHP exit() 与 if - else 语句

php - stream_notification_callback 似乎不起作用

php - 将 PHP 转换为 JavaScript。将键/值存储到数组中

jquery - 将背景图像滑动到图像链接后面

javascript - 在元素上悬停显示描述