Jack Humphries
Jack Humphries

Reputation: 13267

PHP Checking for item in database

I'm new to PHP and I am trying to check if a user exists in a MySQL database over a MySQLi connection. The name of the user I'm trying to check for is stored in a variable called $code. What would I insert into the statement below to get it to check for $code?

$stmt = $this->db->prepare("SELECT id_user FROM members WHERE username = ??? ($code)");  

Thanks for your help.

Edit: Here is my code:

class RedeemAPI {

private $db;

// Constructor - open DB connection
function __construct() {
    $this->db = new mysqli('localhost:3306', 'username', 'password', 'db');
    $this->db->autocommit(FALSE);
}

// Destructor - close DB connection
function __destruct() {
    $this->db->close();
}

// Main method to redeem a code
function redeem() {

    // Check for required parameters
    if (isset($_POST["username"])) {

        // Put parameters into local variables
        $code = $_POST["username"];

        // Look up code in database
        $id_user= 0;

        $stmt = $this->db->prepare('SELECT id_user FROM members WHERE username = ?');  

        $stmt->bind_param("s", $code);

        $stmt->execute();

        $stmt->bind_result($id_user);

        while ($stmt->fetch()) {
            break;
        }
        $stmt->close();

        // Bail if code doesn't exist
        if ($id_user <= 0) {
            sendResponse(400, 'Invalid code');

            return false;
        }

        // Return username, encoded with JSON
        $result = array("username" => $code);
        sendResponse(200, json_encode($result));
        return true;
    }
    sendResponse(400, 'Invalid request');
    return false;

}

}

Upvotes: 0

Views: 123

Answers (2)

john
john

Reputation: 1354

Here's a good example of a prepared statement:

if ($stmt = $mysqli->prepare("SELECT id_user FROM members WHERE username = ?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $code);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($result);

    /* fetch values */
    while ($stmt->fetch()) {
        $result = $result;
    }

    /* fetch value */
    $stmt->fetch();

    /* close statement */
    $stmt->close();
}

Upvotes: 1

user142162
user142162

Reputation:

See mysqli_stmt::bind_param():

$stmt = $this->db->prepare("SELECT id_user FROM members WHERE username = ?");  
$stmt->bindParam('s', $code);
$stmt->exeucte();

Upvotes: 2

Related Questions