【问题标题】:Check if string is already in database or not in Laravel 5.2检查字符串是否已经在数据库中或不在 Laravel 5.2 中
【发布时间】:2016-11-06 03:19:14
【问题描述】:

这是我的代码

$string = str_random(20);
$get_token = DB::table('users')->select('token')-> get();

现在我想比较 $string$get_token 。如果它不在数据库中,那么它应该使用 $string 的值添加到数据库中。

我已经写了这段代码。

if(strcmp($string , $get_token) !=0){
//add to DB
}

如何将我的字符串与数据库中已有的每个字符串进行比较。

谢谢

【问题讨论】:

标签: php string laravel


【解决方案1】:

如果$string没有退出,你可以检查数据库,然后你可以插入数据库。

看看下面的代码:

 $string = str_random(20);
 $get_token = DB::table('users')->where('token', '=', $string)->first();// get first record for that database.

 if(empty($get_token->token))
 {

 //if token not exit in database insert it into database.
  DB::table('users')->insert(
    array('token' =>$string )
  );

 }

【讨论】:

  • $email_id = Input::get('email_id'); $api_token = str_random(50); if (User::where('api_token', '=', $api_token)->exists()) { $get_api_token = User::select('api_token') -> where('email_id', '=', $email_id) -> get(); } else{ DB::table('users')-> insertGetId(array( // insert new user in database 'email_id' => $email_id, 'api_token' => $api_token )); }
  • 这是我想做的……如果我得到数据库中存在的令牌,则返回给定电子邮件 ID 的令牌,如果没有,则插入具有给定 email_id 的令牌
  • 你得到了什么错误,它对你有用吗?
  • '<' unexpected 在 JSON 中
【解决方案2】:

如果您使用的是模型,则可以运行以下代码:

$token = str_random(20); //makes an random string with 20 characters
//select all tokens in the User model where token = $token and count it
$get_token = User::where('token', $token)->count(); //laravel returns an integer

if($get_token == 0) {
    //the token doesn't exist
    //Run the create token code
} else {
    //Token exist
}

希望这行得通!


什么是模型?

Laravel 附带的 Eloquent ORM 提供了一个漂亮、简单的 用于处理数据库的 ActiveRecord 实现。每个 数据库表有一个对应的“模型”,用于交互 与那张桌子。模型允许您查询表中的数据,如 以及向表中插入新记录。

更多信息:https://laravel.com/docs/5.2/eloquent

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-26
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多