萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php操作mysql數據庫的基本類

php操作mysql數據庫的基本類

 

代碼如下  
<?php
$dbhost='localhost';
$dbuser='root';
$dbpass='123456';
$dbname='products';
$connect=mysql_connect($dbhost,$dbuser,$dbpass);
if(!$connect) exit('數據庫連接失敗!');
mysql_select_db($dbname,$connect);
mysql_query('set names utf8');
//查詢
$sql="SELECT * FROM `category`";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
 echo $row['id'];
}
//插入
$sql="INSERT INTO `category` (`id`,`name`) VALUES (NULL,'".$name."')";
$result=mysql_query($sql);
if(mysql_affected_rows()){
 echo '插入成功,插入ID為:',mysql_insert_id();
}else{
 echo '插入失敗:',mysql_error();
}
//修改
$sql="UPDATE `category` SET `name`='".$name."' WHERE `id`='".$id."'";
$result=mysql_query($sql);
if(mysql_affected_rows()){
 echo '修改成功!';
}
//刪除
$sql="DELETE FROM `category` WHERE `id`='".$id."'";
$result=mysql_query($sql);
if(mysql_affected_rows()){
 echo '刪除成功!';
}
//關閉連接
mysql_close($connect);
copyright © 萬盛學電腦網 all rights reserved