Home >Database >Mysql Tutorial >mysql add, delete, modify, query--CURD operation
As a web programmer, everyone knows that data is indispensable for any website, so what is the data used for? Data is used to display website data in real time. Since it is data, something to store data is indispensable, and programmers all know that mysql is used a lot. Mysql is now acquired by Oracle. It belongs to the Oracle company, so what I will mainly talk about today is the PHP operation of MySQL to add, delete, modify and query, which is often called the curd operation. No one wants to program in a process-oriented manner, as it is too cumbersome and troublesome. Today I abstracted these operations and encapsulated a function to call. I will also encapsulate it into classes for everyone in the future. This works faster. Okay, look at the code.
<?php $conn=mysql_connect("localhost","root","root"); mysql_query("set names utf8"); mysql_select_db("test"); /** **insert 操作 */ function insert($table,$data){ if(!is_array($data))return false; $sql_key=""; $sql_values=""; foreach($data as $key=>$val){ $sql_key.=$key.","; $sql_values.="'".$val."'".","; } $news_key=trim($sql_key,","); $news_values=trim($sql_values,","); $sql="INSERT INTO `{$table}` ({$news_key}) VALUES ({$news_values})"; $re=query($sql);//执行sql语句 if($re){ return mysql_insert_id();//返回最后一次执行的id号 }else{ return false; } } //查询 function select($tableName,$field="*",$where="",$order="",$limit="",$group="",$having=""){ $sql="select $field from $tableName $where $group $having $order $limit"; $re=query($sql); if(is_resource($re)){ $arr=array(); while($result=mysql_fetch_assoc($re)){ $arr[]=$result; } return $arr; }else{ return false; } } //删除 function delete($tableName,$where=""){ $sql="delete from $tableName $where"; $re=query($sql); if($re){ return mysql_affected_rows (); }else{ return false; } } //修改 function update($tableName,$array,$where=""){ $fvList=""; foreach ($array as $k=>$v) { $fvList.=",".$k."='".$v."'"; } $fvList=substr($fvList,1); $sql="update $tableName set $fvList $where"; echo $sql; $re=query($sql); if($re){ return mysql_affected_rows(); }else{ return false; } } function query($sql){ if(!$sql)return false; return mysql_query($sql); } var_dump(delete('users','where id=1')); ?>
The above is the content of mysql addition, deletion, modification and query-CURD operation. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!