如何在不输入用户ID的情况下用用户ID将用户的电话号码输入数据库?

时间:2019-07-24 13:36:54

标签: php mysql

我正在为我的移动应用程序创建一个添加朋友页面(网络视图),并且此页面上发生的事情是用户想要添加朋友时。他们要做的就是输入朋友的电话号码,但是,我还需要朋友user_id与电话号码一起使用,而无需用户输入用户的ID。

有什么办法可以做到这一点?

$connect = mysqli_connect("localhost", "xxxxx-xxxxx", "xxxxx-xxxxx", "xxxxx-xxxxx");
$sql = "INSERT INTO friends_requests(phone_number, user_requested_id, user_to_id) VALUES('".$_POST["phone_number"]."', '$id', 'uesr_to_id')";  
if(mysqli_query($connect, $sql))  
{  
     echo 'Request sent!';  
}

1 个答案:

答案 0 :(得分:0)

是的,可以。

您需要做的就是通过电话号码查找用户并获取其ID。

<?php
$connect = new mysqli("example.com", "user", "password", "database");

if ($connect->connect_errno) {
    echo "Failed to connect to MySQL: (" . $connect->connect_errno . ") " . $connect->connect_error;
}

/* prepare sql query to avoid SQL injection */
$sql = "SELECT user_id FROM users WHERE phone_number = '?'";

if (!($query = $connect->prepare($sql))) {
    echo "Prepare failed: (" . $connect->errno . ") " . $connect->error;
}

/* bind parameters to sql query */
$phone_number = $_POST['phone_number'];

if (!$query->bind_param("s", $phone_number)) {
    echo "Binding parameters failed: (" . $query->errno . ") " . $query->error;
}

if (!$query->execute()) {
    echo "Execute failed: (" . $query->errno . ") " . $query->error;
}

$result = $query->get_result();
$table_row= $result->fetch_assoc();
$user_id = $row['user_id']; // NOW YOU CAN USE THE USER ID

别忘了将此示例适应您自己的代码库;)