Home > Backend Development > PHP Tutorial > php 操作mysql1

php 操作mysql1

WBOY
Release: 2016-06-23 13:17:09
Original
763 people have browsed it

代码:

<?phpheader('Content-Type:text/html;charset=utf-8');// 数据库地址define('DB_HOST','localhost');//数据库用户名define('DB_USER','root');//数据库密码define('DB_PASSWORD','root');//要连接的数据库名define('DB_NAME','mytest');// 获得连接$conn = @mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die('Could not connect: ' . mysql_error());// 设置字符集@mysql_query('set names utf8') or die('设置字符集失败!'.mysql_error());//选择数据库@mysql_select_db(DB_NAME,$conn) or die('数据库错误'.mysql_error());//构造一个sql语句,并执行这个SQL语句,获得结果集$sql_query = 'select * from student';$result = @mysql_query($sql_query) or die('sql 语句错误:'.mysql_error());// 输出一条记录print_r(mysql_fetch_array($result,MYSQL_ASSOC));echo '<br />';/*// insert$sql_insert = "insert into student values (1004,'行者',32,'男')";@mysql_query($sql_insert) or die('插入数据出错'.mysql_error());*/// 显示数据$sql_query = 'select id,name,age,sex from student';$result = @mysql_query($sql_query) or die('sql 语句错误:'.mysql_error());// 每次循环都将从结果集的数组中取出一行,再按字符串下标打印出此行中的数据,直到遍历完此结果集while( $row = mysql_fetch_array($result)){	echo $row['id'].'--'.$row['name'].'--'.$row['sex'].'--'.$row['age'];	echo '<br />';}// 释放结果资源mysql_free_result($result);// 关闭数据库mysql_close($conn);
Copy after login
运行结果:

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template