Home » Php » php – Updating data with the same ID

php – Updating data with the same ID

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am trying to create some logic that creates a user when the id could not be found and updates the user if it already exists.

The following fails for the updating parts because it always tries to create the user. It isn’t clear why does not update because the data contains the same ID.

include('../conn.php');
$id = $_GET['id'];
$uname = $_GET['username'];
$pass = $_GET['pass'];
$token = $_GET['token'];
$pic = $_GET['pic'];
$follows = $_GET['follows'];

if (empty($follows) or empty($id) or empty($uname) or empty($pass) or empty($token) or empty($pic)) {
    echo "Error: Wrong input of values.";
} else {
    $stmt = $conn->prepare("SELECT username FROM usersinfo WHERE id = ?");
    $stmt->bind_param("s", $id);
    $result = $stmt->fetch();
    if (!empty($result)) {
        $stmt = $conn->prepare("UPDATE usersinfo SET follows=?, username=?, pass=?, token=?, pic=? WHERE id=?");
        $stmt->bind_param("ssssss", $follows, $uname, $pass, $token, $pic, $id);
        $stmt->execute();
    } else {
        $stmt = $conn->prepare("INSERT INTO usersinfo (follows, id, username, pass, token, pic) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssss", $follows, $id, $uname, $pass, $token, $pic);
        $stmt->execute();
        }
$stmt->close();
$conn->close();
    }
?>  
How to&Answers:

So, Thanks for all
especially for Dharman for his comment and this is the solution.

include('../conn.php');
$id = $_GET['id'];
$uname = $_GET['username'];
$pass = $_GET['pass'];
$token = $_GET['token'];
$pic = $_GET['pic'];
$follows = $_GET['follows'];

if (empty($follows) or empty($id) or empty($uname) or empty($pass) or empty($token) or empty($pic)) {
    echo "Error: Wrong input of values.";
} else {
    $stmt = $conn->prepare("SELECT username FROM usersinfo WHERE id = ?");
    $stmt->bind_param("s", $id);
    $stmt->execute();
    $result = $stmt->fetch();
    $stmt->close();
        if (!empty($result)) {
        $stmt = $conn->prepare("UPDATE usersinfo SET follows=?, username=?, pass=?, token=?, pic=? WHERE id=?");
        $stmt->bind_param("ssssss", $follows, $uname, $pass, $token, $pic, $id);
        $stmt->execute();
    } else {
        $stmt = $conn->prepare("INSERT INTO usersinfo (follows, id, username, pass, token, pic) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssss", $follows, $id, $uname, $pass, $token, $pic);
        $stmt->execute();
        }
$stmt->close();
$conn->close();
    }
?>