V
V
Vitaly2017-04-23 17:26:49
PHP
Vitaly, 2017-04-23 17:26:49

How to check the existence of a record in a MySQL database using PHP?

So, the crux of the matter. I get the first name, last name and ID of the VK user who logs in on my site, and write them to the database, everything is written correctly :D, but if I log in to the site again, a new line is created, the same as the previous one (clone).

<?php
header('Content-Type: text/html; charset=utf-8');
$VK_APP_ID = "";
$VK_SECRET_CODE = "";

$user="";
$password="";
$db="";

mysql_connect($host, $user, $password) or die("MySQL сервер недоступен!".mysql_error());
mysql_select_db($db) or die("Нет соединения с БД".mysql_error());
mysql_set_charset('utf8');

if(!empty($_GET['code'])) {
 
  $vk_grand_url = "https://api.vk.com/oauth/access_token?client_id=".$VK_APP_ID."&client_secret=".$VK_SECRET_CODE."&code=".$_GET['code']."&redirect_uri=http://vhost25708.cpsite.ru/vklogin.php";
 
 // отправляем запрос на получения access token
  $resp = file_get_contents($vk_grand_url);
  $data = json_decode($resp, true);
  $vk_access_token = $data['access_token'];
  $vk_uid =  $data['user_id'];
  
// обращаемся к ВК Api, получаем имя, фамилию и ID пользователя вконтакте
// метод users.get
  $res = json_decode(file_get_contents("https://api.vk.com/method/users.get?uids={$vk_uid}&access_token={$vk_access_token}&fields=uid,first_name,last_name,photo"));
  $first_name = $res->response[0]->first_name;
  $last_name = $res->response[0]->last_name;
  $photo = $res->response[0]->photo;
  $uid = $res->response[0]->uid;
  echo "Имя : $first_name <br> Фамилия : $last_name <br> ID : $uid <br> Токен : $vk_access_token <br> <img src='$photo'>";
//  echo "<img src='$photo'>";

if (isset($first_name) && isset($last_name) && isset($uid)) {
  
    $result_add = mysql_query("INSERT INTO easy_clients (first_name, last_name, uid) VALUES ('$first_name', '$last_name', '$uid')");

    if ($result_add == 'true') {
        echo "<p>Успешно добавлено в базу</p>";
    } else {
        echo "<p>Не добавлено в базу</p>";
    echo mysql_errno() . ": " . mysql_error() . "\n";
    }
}

}
?>

The question is, how to check the existence of a record in the MySQL database through PHP, and if there is a record, then do nothing, and if not, then create it ???

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
entermix, 2017-04-23
@vitcorp

$result_add = mysql_query("INSERT IGNORE INTO easy_clients (first_name, last_name, uid) VALUES ('$first_name', '$last_name', '$uid')");

https://dev.mysql.com/doc/refman/5.5/en/insert.html
If there is a record, the insert will not be performed
Or like this:
https://dev.mysql.com/doc/refman/5.5/en /insert-on-...
In case the entry already exists, it will be updated
Or so, check (make a SELECT)
https://dev.mysql.com/doc/refman/5.5/en/select.html
How to do it in PHP? There is a huge amount of information on the Internet
UPD: Naturally, the first 2 points will only work if you have the correct indexes (UNIQUE uid) in the table

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question