Update query in php using function
Posted Date:20-07-2017
In this we will explain mysql_query update using custom user created function
Step 1: Create table name as product using following code
CREATE TABLE `product` ( `pid` int(11) NOT NULL AUTO_INCREMENT, `pname` varchar(100) NOT NULL, `price` int(11) NOT NULL, `pimg` varchar(100) NOT NULL, `cat_id` int(11) NOT NULL, PRIMARY KEY (`pid`)) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=latin1
Stpp 2: Create html edit form
define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PSSWD", ""); define("DB_NAME", "demo"); $id = 1; $sql="SELECT * FROM `product` WHERE pid=$id"; $result=mysqli_query($conn,$sql); // Associative array $row=mysqli_fetch_assoc($result); // print_r($row);
Step 3:Create php connection string,query update function and form submit action
function qry_update($table='', $data='', $where='') { define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PSSWD", ""); define("DB_NAME", "demo"); $conn = mysqli_connect(DB_HOST,DB_USER,DB_PSSWD,DB_NAME); $cols = array(); foreach($data as $key=>$val) { $cols[] = "$key = '$val'"; } foreach($where as $key=>$val) { $cols[] = "$key = '$val'"; } $query = "UPDATE $table SET " . implode(', ', $cols); if (!empty($where)) { foreach ($where as $key => $value) { $where_array[] = $key.' = '.'"'.$value.'"'; } $query .= " WHERE ".implode(' AND ', $where_array); } // echo $query; $result=mysqli_query($conn,$query); if ($result) { echo 1; } else { echo 0; } } if(isset($_POST['save'])) { $data = array( 'cat_id' => $_POST['cat_id'], 'pname' => $_POST['product_name'], 'price' => $_POST['product_price'] ); $where = array('pid' => $_POST['id']); $qry = qry_update('product',$data,$where); }