CodesJava

Easy learning with example program codes

PHP MySQLi INSERT


To insert data in a MySQLi file or table in PHP, PHP mysqli_connect() function and PHP mysqli_query() function are used.

PHP mysqli_connect() function:

PHP mysqli_connect() function is used to open a new connection to the MySQL server. If the connection is established this function returns the resource, else it returns a null.

PHP mysqli_query() function:

PHP mysqli_query() function is used to perform a query against the MySQL database.

Syntax:

mysqli_query(connection,query,resultmode);

Connection: This is a required parameter which is used to specify the MySQL connection to use.

Query: This is an optional parameter which is used to specify the query string.

Resultmode: This is an optional parameter which is used to specify a constant either MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT.

MYSQLI_STORE_RESULT is the default value of the resultmode. MYSQLI_USE_RESULT is used when a large amount of data need to be retrieved.

Example:

<!DOCTYPE html>
<html>
<body>
 
<?php
$phpconnect = mysqli_connect("localhost","Ben","Ben_password");
 
if (mysqli_connect_errno())
{
echo "Connection Failed; " . mysqli_connect_error();
}
else
{
echo "Connection Established.<br>";
 
$phpdatabase = "INSERT INTO MyFriends (firstname, lastname, email)
VALUES ('BEN', 'DICHOSTA', 'dichosta@example.com')";
 
if(mysqli_query( $phpconnect,$phpdatabase))
{  
echo "Data Inserted successfully.<br>";  
}
else
{  
echo "Data Insertion Failed; ".mysqli_error($phpconnect);  
}  
}
 
mysqli_close($phpconnect);
echo “Connection Closed.”
?> 
 
</body>
</html>

Output:

Connection Established.
Data Inserted successfully.
Connection Closed.
Posted in PHP   
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki