codingtcher.com
Theme Night
Home
Login

insert data in database using php function

Home » Tutorial Post » insert data in database using php function
PDO connection and disconnection example
//use this two function for database connection and disconnection
function dbconnect() {
	global $conn;
	try {
		if (! $conn) {
			$conn = new PDO("mysql:host='localhost';dbname='yourdbname';charset=utf8", 'yourdbuser', 'yourdbpass', [
				PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
			]);
		}
	} catch (PDOException $e) {
		$conn = null;
	}
}

function closeconn(){
  global $conn;
  $conn = null;
}

//use this two function for insert data in database
function query($sql,$exec=""){
	global $conn;
	$result = $conn->prepare($sql);
  if($exec){
	$result->execute($exec);}
  else{
	$result->execute();
  }
}

function insertdata($table, $inserts, $s='',$v=false){
	$query = "INSERT INTO $table (";
	$column = array();
	$values = array();
	foreach ($inserts as $key => $value) {
	  $column[] = $v==true ? $value : $key;
	if($s){
	  $values[] = "$s";
	}
	else{
	  $values[] = ":$value";
	}
	}
	if(count($column) > 1) {
	  $query .= implode(", ", $column).") VALUES (".implode(", ", $values).")";
	 } else {
	  $query .= $column[0].") VALUES (".$values[0].")";
	}
	return $query;
}

//insert data in database
dbconnect();
$sql = insertdata("yourtableName",array("firstcolumnName","secondcolumnName"),"?",true);
query($sql,["firstcolumnValue",'secondcolumnValue']);
closeconn();

Related Post