How to Insert PHP MySQL Prepared Statements

104 2
    • 1). Open your PHP file in a text editor, such as Windows Notepad.

    • 2). Connect to a MySQL database by adding the code "$db = new mysqli("localhost", "username", "password");", replacing "localhost", "username" and "password" with the login information for the MySQL database.

    • 3). Create a prepared statement by adding code in the format of "$my_statement = $db->prepare("INSERT INTO my_table (name, id) VALUES (?, ?)");" or "$my_statement = $db->prepare("INSERT INTO my_table (name, id) VALUES (:name, :id)");", replacing the query with your own. The "?" symbol, ":name" and ":id" mark where a parameter will be set later.

    • 4). Bind the parameters by adding code in the format of "$my_statement->bindParam(1, $name); $my_statement->bindParam(2, $id)" if you used question marks (?) in your prepared statement. The numbers start at 1 and increase by 1 for each additional "?" symbol. Add code in the format of "$my_statement->(':name', $name); $my_statement->(':id',$id);" if you used parameters like ":name" and ":id" in your prepared statement.

    • 5). Assign values to your variables by adding the code "$name = 'bob'; $id = 11;", replacing the variable names and values with the ones used in your query.

    • 6). Execute the prepared statement by adding the code "$my_statement->execute();".

    • 7). Save the PHP file and load it on your server.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.