codingtcher.com
Theme Night
Home
Login

update data in database using php function

Home » Tutorial Post » update 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 update data in database
function query($sql,$exec=""){
	global $conn;
	$result = $conn->prepare($sql);
  if($exec){
	$result->execute($exec);}
  else{
	$result->execute();
  }
}

function updatedata($table, $data, $whereset='', $s=''){
  $query = "UPDATE $table SET";
  $dataset = array();
  foreach ($data as $key => $value) {
	if($s){
	 $dataset[] = "$value=$s";
	}
	elseif($value=="?"){
	 $dataset[] = "$key=$value";
	}
	else{
	  $dataset[] = "$key=:$value";
	}
  }
  if(count($dataset) > 1) {
	  $query .= " ".implode(", ", $dataset);
  } else {
	  $query .= " ".$dataset[0];
  }
  if($whereset){
  $query .= " WHERE ".$whereset;
  }
  return $query;
}

//update data in database
dbconnect();
$sql = updatedata("yourtableName",array("firstcolumnName","secondcolumnName"),"id=?","?");
query($sql,["firstcolumnValue",'secondcolumnValue','4']);
//4 is 'where id'
closeconn();

Related Post