A
A
Alexey Golovin2020-02-07 17:16:47
PHP
Alexey Golovin, 2020-02-07 17:16:47

Why do I get a connection error when querying SQL through the body of a PHP function?

I am suffering with such a problem: I need to get the value of this radio when clicking on the radio and pass it to the SQL query. In JS, I am getting a value.

$("input[name='select_account']").on('click', function () {
    var x = $("input[name='select_account']:checked").val();
})


Then, as I understand it, it must be transferred to PHP and made a request via SQL. Accordingly, I make a function that passes this value, but when I receive a request, I get an error (Query failed). However, if I run the request code outside of the function body, no error occurs.

function sql_query($user_id) {
    $query = 'select * from users WHERE id='.$user_id.';';
    $query_result = mysqli_query($connection, $query);
        if(!$query_result) {
            die('Query failed'.mysqli_error());
        } else {
            echo ('Complete');
        }
        return $query_result;
}


$connection I get earlier in the code with no error.

And in general, maybe I'm suffering in vain with this function, maybe there is a simpler solution?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2019-05-25
@ZefiRus

You have something <?=inside the php code.

F
FanatPHP, 2020-02-07
@dadduUrsa

PHP's main problem is that all online textbooks contain horror from the last century. And the saddest thing is that users of the AUser0 type repeat it mindlessly.
Here is the correct way:

function get_user($connection, $user_id) {
    $stmt = $connection->prepare('select * from users WHERE id=?');
    $stmt->bind_param("s", $user_id); 
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question