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)?>
}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)?>