Course: Web Technology
University: Pokhara University
Check The Internet and The Web – Introduction
Here is a connect.php file. We need Server, Database Name, Username and Password for that database.
new mysqli(server, username,password,database)
Will establish a database connection.
1
2
3
4
5
6
7
8
9
10
11
12
| <?php
$server = "localhost";
$username ="test2";
$password ="test2";
$dbname ="test2";
$conn =new mysqli($server,$username,$password,$dbname);
if ($conn->connect_error)
{
die("connection error " .$conn->connect_error);
}
?>
|
Here is createdb.php Which will create a table Named info with element name and email.
Here we save the SQL query in variable sql then run it in the Connection made above as
$conn -> query($sql)
1
2
3
4
5
6
7
8
| <?php
include "connect.php";
$sql ="CREATE TABLE info(
id INT(6) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(60) NOT NULL,
email VARCHAR(40) NOT NULL)";
$conn-> query($sql);
?>
|
Finally we are here in index.html, Here is a form with action test2.php. Whatever we send through this form will be send to test2.php (that is what action for)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form class="" action="test2.php" method="post">
Name: <input type="text" name="name" value="name"/><br>
Email: <input type="email" name="email" value="email"/><br>
<input type="submit" name="" value="send">
</form>
</body>
</html>
|
And here is test2.php which will get the values passed from the form and store them in the Database.
$_POST["name"] will get the value from the form with name name. The SQL query
INSERT INTO info(name, email) VALUES ('$name','$email')
Will insert the value of name and email to the table info and element name and email.
1
2
3
4
5
6
7
8
| <?php
include "connect.php";
$name= $_POST["name"];
echo $_POST["name"];
$email = $_POST["email"];
$sql = "INSERT INTO info(name, email) VALUES ('$name','$email')";
$conn-> query($sql);
?>
|
This is all. You can find the code in Github https://github.com/InfoDevkota/phpformmysql/tree/master (Master Branch) Issuers and pull requested are accepted.
If something is wrong or Need more clarification Please contact me: info[at]devkotasagar.com.np.
0 comments:
Post a Comment