mysql增刪改查基本語句


數據庫的鏈接和選擇及編碼 
$link=mysql_connect("localhost","root","123456") or die("數據庫連接失敗".mysql_error());    // 連接數據庫
$sel=mysql_select_db("login",$link) or die("數據庫選擇失敗".mysql_error());                        // 選擇數據庫
mysql_query("set names 'utf8'");                                                                               // 設置數據庫編碼

添加數據
$link=mysql_connect("localhost","root","123456") or die("數據庫連接失敗".mysql_error());
$sel=mysql_select_db("login",$link) or die("數據庫選擇失敗".mysql_error());
mysql_query("set names 'utf8'",$sel);
$add="insert into title(title,content,username,time) values('$title','$content','$username',$time)";
$query=mysql_query($add);
if($query){
echo "add sucess";
echo "<meta http-equiv=\"refresh\" content=\"1;URL=show_message.php\" />";
}
else echo "add false";

刪除數據
$link=mysql_connect("localhost","root","123456") or die("數據庫連接失敗".mysql_error());
$sel=mysql_select_db("login",$link) or die("數據庫選擇失敗".mysql_error());
mysql_query("set names 'utf8'");
$id=$_GET['id'];
$delete="delete from title where id='$id'";
$query=mysql_query($delete);
if($query){
echo "delete sucess!";
echo "<meta http-equiv=\"refresh\" content=\"1;URL=show_message.php\" />";
}
else echo "delete false";

改數據
$link=mysql_connect("localhost","root","123456") or die("數據庫連接失敗".mysql_error());
$sel=mysql_select_db("login",$link) or die("數據庫選擇失敗".mysql_error());
mysql_query("set names 'utf8'",$sel);
$update="update title set title='".$title."',content='".$content."'
where id='$id'";
$query=mysql_query($update);
if($query){
echo "reset sucess!";
echo "<meta http-equiv=\"refresh\" content=\"1;URL=show_message.php\" />";
}
else echo "reset false";

查數據
$link=mysql_connect("localhost","root","123456") or die("數據庫連接失敗".mysql_error());
$sel=mysql_select_db("login",$link) or die("數據庫選擇失敗".mysql_error());
mysql_query("set names 'utf8'",$sel);
$sql="select * from 表名 limit 10";
$result=mysql_query($sql);
while($arr=mysql_fetch_array($result, MYSQL_ASSOC)) {
     $rs[] = $arr;               // 將所有數據放到二位數組中 
     或 $arr = mysql_fetch_array();         // 取一條


1. select查詢語句和條件語句
   select 查詢字段 from 表名 where 條件
   查詢字段:可以使用通配符*、字段名、字段別名(字段名 as ..
   表名:數據庫.表名,表名
   常用條件:=等於、<>不等於、in(值,值)包含、not in(值,值)不包含、like匹配
   between在范圍、not between不在范圍、<>
   條件預算:andor、()

2. select 查詢字段 from 表名 where 條件
  (group by字段 分組)
  (order by字段,字段asc/desc 排序)
  (limit初始值,結束值 指針查詢)
 

3. select 計算 from 表名 where 條件
    count*)統計函數
    max*)最大值函數
    min*)最小值函數
    avg*)平均值
    sum*)累加值函數

4.模糊查詢(%代表0個或多個字符,_代表1個字符。like比較耗時間,盡量少用) 

 

like用法:
SELECT * FROM 表名 WHERE username LIKE “$username%”;
SELECT * FROM 表名 WHERE username LIKE “%$username%”;

in用法:
SELECT * FROM 表名 WHERE id in(1, 2, 5, 9);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM