anurag-singh
9/16/2015 - 12:32 PM

MySQLi way to insert data in database table

<?php 
	// Setup Connection
    $server = 'localhost'; $username = 'root'; $password = '';
	# Connect to server
	$conn = new MySQLi ($server, $username, $password);
	if($conn->connect_error) {
	die ('Connection Failed : ' . $conn->connect_error);
	}
	echo 'Connected to server.<br/>'; 
?>


<?php 
    // Create Database
	$sqlCreateDB = 'CREATE DATABASE IF NOT EXISTS demo';
	if ($conn->query($sqlCreateDB) === TRUE) {
	 echo 'Database demo Created successfully. <br/>';
	}
	else {
	 echo 'Error while creating database : ' . $conn->error . '<br/>';
	} 
?>


<?php 
	// Connect to Database
    $server = 'localhost'; $username = 'root'; $password = ''; $database = 'demo';
	$conn = new MySQLi ($server, $username, $password, $database);
	if($conn->connect_error) {
	die ('Connection Failed : ' . $conn->connect_error);
	}
	echo 'Connected to $database<br/>'; 
?>

<?php 
	// Create new table
    $sqlCreateTable = 'CREATE TABLE IF NOT EXISTS mytable (
							id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
							name VARCHAR(30) NOT NULL,
							email VARCHAR(50),
							msg VARCHAR(30) NOT NULL,
							gender VARCHAR(6) NOT NULL,
							opinion VARCHAR(6) NOT NULL,
							reg_date TIMESTAMP
						 )';

		if ($conn->query($sqlCreateTable) === TRUE) {
		 echo 'Table "mytable" created successfully.<br>';
		} 
		else {
		 echo 'Error while creating the table "mytable" : ' . $conn->error .'<br/>';
		} 
?>

<?php 
	// Insert data into table
    $add = 'INSERT INTO mytable (name, email, msg, gender, opinion) VALUES (?,?,?,?,?)';
	if ($stmt = $conn->prepare($add)) {
	$stmt->bind_param('sssss', $name, $email, $msg, $gender, $opinion);
	}
	else {
		die ('Error : ' . $conn->error);
	}

	$name = 'Anurag';
	$email = 'anuragsinghce@gmail.com';
	$msg = 'Dummy Msg';
	$gender = 'male';
	$opinion = 'yes';

	/* execute prepared statement */
	$stmt->execute();

	$stmt->close(); 

	$conn->close();
?>