Masukkan Data Ke MySQL Menggunakan PHP

Masukkan Data Ke MySQL Menggunakan PHP

Masukkan Data Ke MySQL Menggunakan PHP

Masukkan Data Ke MySQL Menggunakan PHP, Untuk memasukkan data di MySQL terlebih dahulu kita harus membuat tabel di basis data.

CREATE TABLE `employee` (

`userid` int(8) NOT NULL,

`first_name` varchar(55) NOT NULL,

`last_name` varchar(55) NOT NULL,

`city_name` varchar(55) NOT NULL,

`email` varchar(50) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

Di sini kami menggunakan 3 file untuk memasukkan data di MySQL:

database.php : Untuk menghubungkan basis data

insert.php : untuk mendapatkan nilai dari pengguna

process.php : File PHP yang memproses permintaan

database.php

<?php

$servername='localhost';

$username='root';

$password='';

$dbname = "crud";

$conn=mysqli_connect($servername,$username,$password,"$dbname");

if(!$conn){

die('Could not Connect My Sql:' .mysql_error());

}

?>

 

insert.php

<!DOCTYPE html>

<html>

<body>

<form method="post" action="process.php">

First name:<br>

<input type="text" name="first_name">

<br>

Last name:<br>

<input type="text" name="last_name">

<br>

City name:<br>

<input type="text" name="city_name">

<br>

Email Id:<br>

<input type="email" name="email">

<br><br>

<input type="submit" name="save" value="submit">

</form>

</body>

</html>

 

process.php

<?php

include_once 'database.php';

if(isset($_POST['save']))

{

$first_name = $_POST['first_name'];

$last_name = $_POST['last_name'];

$city_name = $_POST['city_name'];

$email = $_POST['email'];

$sql = "INSERT INTO employee (first_name,last_name,city_name,email)

VALUES ('$first_name','$last_name','$city_name','$email')";

if (mysqli_query($conn, $sql)) {

echo "New record created successfully !";

} else {

echo "Error: " . $sql . "

" . mysqli_error($conn);

}

mysqli_close($conn);

}

?>

 

Kode Alternatif dalam (PDO)

<?php

$servername='localhost';

$username='root';

$password='';

$dbname = "crud";

try {

$first_name = $_POST['first_name'];

$last_name = $_POST['last_name'];

$city_name = $_POST['city_name'];

$email = $_POST['email'];

date_default_timezone_set("Asia/Calcutta");

$insertdate = date("Y-m-d H:i:s");

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

/* set the PDO error mode to exception */

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "INSERT INTO employee (first_name,last_name,city_name,email,datetime)

VALUES ('$first_name', '$last_name','$city_name','$email','$insertdate')";

$conn->exec($sql);

echo "New record created successfully";

}

catch(PDOException $e)

{

echo $sql . "<br>" . $e->getMessage();

}

$conn = null;

?>

 

 

Baca Juga  Cara Menampilkan marker ke Peta Google dengan PHP dan MySQL

Tinggalkan Komentar

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *

Need Help? Chat with us