Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into MySQL using a prepared statement with PHP [duplicate]

I am just learning about databases and I want to be able to store user inputs. What would be a basic example on how to get form data and save it to a database using PHP?

Also making the form secure from SQL attacks.

like image 647
bammab Avatar asked Oct 12 '11 23:10

bammab


People also ask

Can we use prepared statement for select query in PHP?

You must always use prepared statements for any SQL query that would contain a PHP variable. To do so, always follow the below steps: Create a correct SQL SELECT statement. Test it in mysql console/phpmyadmin if needed.

Do I need to use Mysqli_real_escape_string with prepared statements?

Do I still need to used mysqli_real_escape_string when used prepared statements in PHP? The simple answer is no. The way it used to work is that you would take form input data, put that into a variable, and inject that data into your MySQL query in order to add that data to the database.

How do you create a prepared statement in MySQL?

In order to use MySQL prepared statement, you use three following statements: PREPARE – prepare a statement for execution. EXECUTE – execute a prepared statement prepared by the PREPARE statement. DEALLOCATE PREPARE – release a prepared statement.

What is the use of $row in PHP?

Definition and Usage The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set and returns it as an enumerated array.


1 Answers

File sample.html

<form action="sample.php" method="POST">     <input name="sample" type="text">     <input name="submit" type="submit" value="Submit"> </form> 

File sample.php

<?php     if (isset($_POST['submit'])) {          $mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb');          /* Check connection */         if (mysqli_connect_errno()) {             printf("Connect failed: %s\n", mysqli_connect_error());             exit();         }          $stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)");         $stmt->bind_param('s', $sample);   // Bind $sample to the parameter          $sample = isset($_POST['sample'])                   ? $_POST['sample']                   : '';          /* Execute prepared statement */         $stmt->execute();          printf("%d Row inserted.\n", $stmt->affected_rows);          /* Close statement and connection */         $stmt->close();          /* Close connection */         $mysqli->close();     } ?> 

This is a very basic example. Many PHP developers today are turning to PDO. Mysqli isn’t obsolete, but PDO is much easier, IMHO.

like image 128
Herbert Avatar answered Oct 11 '22 12:10

Herbert