如何用PHP语句访问MySQL

<?php
//设置字符的编码是utf-8,解决url中的中文
header("content-Type: text/html; charset=utf8"); 
//获取浏览器url中的变量
$dbdatabase=$_GET[dbdatabase];
$tablename=$_GET[tablename];
//MySQL账号密码
$dbhost="localhost";
$username="root";
$userpass="123456";
//连接mysql
$link = mysql_connect($dbhost,$username,$userpass); 
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
echo "<br>";
mysql_select_db($dbdatabase, $link) or die('Could not select database.');
//MySQL查询语句
$sql="SELECT * FROM ".$tablename;
//MySQL插入语句
$ins="insert into ".$tablename." values('5','thgf','中午','','','')";
//执行插入语句
mysql_query("set names utf8");
mysql_query($ins);
//执行执行语句,获取数据库中数据
mysql_query("set names utf8");
$result=mysql_query($sql,$link);
echo $result;
echo "<br>";
//输出查到的内容
while($row = mysql_fetch_row($result)){

        foreach($row as $val){
            echo '--'.$val;
        }        
        echo '<br/>';
    }
    //4、关闭资源
    $row->free();
   mysql_close();
?>

 

 

posted @ 2014-11-23 15:35  绚丽星空  阅读(289)  评论(0编辑  收藏  举报