梁一鑫吧 关注:17贴子:348
  • 1回复贴,共1

PHP数据库连接实例,请大家参考!

只看楼主收藏回复

PHP与MYSQL应用1.连接与断开服务器使用连接函数mysql_connect()参数:server:服务器地址,username:用户名,password:密码使用断开函数mysql_close()DEMO<?php $db_host = "localhost"; $db_user="root"; $db_psw=""; $connection=mysql_connect($db_host,$db_user,$db_psw); if(!$connection){ die('连接MySql服务器失败'); } echo '连接服务器成功'; mysql_close($connection)?>2.选择数据库 当连接数据库之后,接下来应该选择连接哪个具体数据库函数:mysql_select_db()参数:database_nameDEMO<?php $db_host = "localhost"; $db_user="root"; $db_psw=""; $db_name="study"; $connection=mysql_connect($db_host,$db_user,$db_psw); if(!$connection){ die('连接MySql服务器失败'); } mysql_select_db($db_name,$connection) or die("选择数据库错误"); mysql_close($connection)?>3.获取查询结果1.函数:mysql_query() 执行sql功能替代在mysql工具上执行的效果 参数:sql语言2.函数:mysql_fetch_array() 获取查询结果的一行记录参数:mysql_query()返回的$result3.函数:mysql_num_rows()返回查询结果的数目仅对select有效参数:mysql_query()返回的$result4:函数:mysql_free_result() 释放结果集在内存中资源参数:mysql_query()返回的$result<?php $db_host = "localhost"; $db_user="root"; $db_psw=""; $db_name="study"; $connection=mysql_connect($db_host,$db_user,$db_psw); if(!$connection){ die('连接MySql服务器失败'); } mysql_select_db($db_name,$connection) or die("选择数据库错误"); $query = "select * from user"; $result = mysql_query($query) or die("查询失败"); if(mysql_num_rows($query)>0){ while($row=mysql_fetch_array($result)){ echo ($row['user_id']); echo ($row['user_xm']); }
}else{ echo "未查询到任务和记录"; } mysql_free_result($query); mysql_close($connection)?>4。数据的插入,修改与删除使用函数mysql_query()<?php $db_host = "localhost"; $db_user="root"; $db_psw=""; $db_name="study"; $connection=mysql_connect($db_host,$db_user,$db_psw); if(!$connection){ die('连接MySql服务器失败'); } mysql_select_db($db_name,$connection) or die("选择数据库错误"); $query = "insert into employee(emp_number,emp_name,emp_age) values('1234','hello1',25)"; if(mysql_query($query)){ echo '保存成功'; }else{ echo '保存失败'; } mysql_close($connection)?>


1楼2013-05-02 07:34回复
    <?php $db_host = "localhost"; $db_user="root"; $db_psw=""; $db_name="study"; $connection=mysql_connect($db_host,$db_user,$db_psw); if(!$connection){ die('连接MySql服务器失败'); } echo '1.连接服务器成功'; echo '<br>'; mysql_select_db($db_name,$connection) or die("对不起,你选择的数据库可能不存在!"); echo '2.选择数据库study成功'; $query = "delete from t_user"; if(mysql_query($query)){ echo '保存成功'; }else{ echo '保存失败'; } mysql_close($connection);?>


    2楼2013-05-02 07:34
    回复