mysql – How to solve undefined array key in php?

Question

I am facing a problem in my try to create a JSON API for wp_users table. The error I am facing in register.php file is this:

Warning: Undefined array key "user_login" in C:xampphtdocsRentABoatregister.php on line 5

Warning: Undefined array key "user_email" in C:xampphtdocsRentABoatregister.php on line 6

Warning: Undefined array key "user_pass" in C:xampphtdocsRentABoatregister.php on line 7

And my code is here:

<?php
 
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $name = $_POST['user_login'];
    $email = $_POST['user_email'];
    $password = $_POST['user_pass'];

    $password = password_hash($password, PASSWORD_DEFAULT);

    require_once 'wp-connect.php';

    $sql = "INSERT INTO wp_users(user_email, user_pass) VALUES ('$email', '$password')";

    if(mysqli_query($conn, $sql)) {
        $result["success"] = "1";
        $result["message"] = "success";

        echo json_encode($result);
        mysqli_close($conn);
    } else {

        $result["success"] = "0";
        $result["message"] = "error";

        echo json_encode($result);
        mysqli_close($conn);
    }
    

}
?>

And in my login.php file I face the following error:

Fatal error: Uncaught TypeError: mysqli_num_rows(): Argument #1 ($result) must be of type mysqli_result, bool given in C:xampphtdocsRentABoatlogin.php:17 Stack trace: #0 C:xampphtdocsRentABoatlogin.php(17): mysqli_num_rows(false) #1 {main} thrown in C:xampphtdocsRentABoatlogin.php on line 17

And my code is this:

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST'){

    $email = $_POST['user_email'];
    $password = $_POST['user_pass'];

    require_once 'wp-connect.php';

    $sql = "SELECT * FROM wp_users WHERE user_email="$email";

    $response = mysqli_query($conn, $sql);

    $result = array();
    $result["login'] = array();

    if ( mysqli_num_rows($response) === 1 ) {

        $row = mysqli_fetch_assoc($response);

        if ( password_verify($password, $row['password']) ) {

            $index['name'] = $row['name'];
            $index['email'] = $row['email'];
            $index['id'] = $row['id'];

            array_push($result['login'], $index);

            $result['success'] = "1";
            $result['message'] = "success";
            echo json_encode($result);

            mysqli_close($conn);

        } else {

            $result['success'] = "0";
            $result['message'] = "error";
            echo json_encode($result);

            mysqli_close($conn);

        }

    }

}

?>

What could I do to solve the error?

0
Gus Rasmusen 1 year 2021-12-01T09:56:18-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse