Insert elements into MySQL with PHP

In this example we are going to see how we can insert an element in MySQL using PHP. The first thing will be to connect to the MySQL database. To do this we are going to create a mysqli class.

@ $db = new mysqli(localhost, "root", "password", "library");

We see that we have connected with the user “root” and the password “password”. Furthermore, the database that we are going to use is “library”.

The next thing will be to prepare the insertion statement in SQL using the INSERT statement.

$query = "INSERT INTO authors (authorid, authorname) VALUES (NULL, 'Larry Ullman');";

We can complete this statement with values ​​that come from the web page. But in these cases you have to be careful and do it with a PreparedStatement to avoid code injection problems SQL.

Now we execute the INSERT statement. For this we use the query method.

$result = $db->query($query);

We will have to evaluate if there is content within the result to see if the INSERT statement has been executed correctly. In that case we can validate using the affected_rows of the database the number of rows that have been inserted.

if ($result)
  echo $db->affected_rows." affected row(s). Information inserted correctly"
else
 echo "A problem occurred inserting the data";

We will only have to close the database.

$db->close();

Leave a Comment