荟萃馆

位置:首页 > 计算机 > php语言

php连接mysql数据库代码

php语言3.26W
php连接mysql数据库代码
  书山有路勤为径,学海无涯苦作舟。学习PHP就要勤奋。下面是php连接mysql数据库代码,欢迎阅读参考!  <?php  $mysql_server_name="localhost"; //数据库服务器名称$mysql_username="root"; // 连接数据库用户名$mysql_password="111111"; // 连接数据库密码$mysql_database="phptest"; // 数据库的名字// 连接到数据库$conn=mysql_connect($mysql_server_name, $mysql_username,$mysql_password);// 从表中提取信息的sql语句$strsql="select * from test";  // 执行sql查询  $result=mysql_db_query($mysql_database, $strsql, $conn);// 获取查询结果$row=mysql_fetch_row($result);echo '<font face="verdana">';  echo '<table border="1" cellpadding="1" cellspacing="2">';// 显示字段名称echo "n<tr>n";for ($i=0; $i<mysql_num_fields($result); $i++){echo '<td bgcolor="#ff0F00"><b>'.  mysql_field_name($result, $i);  echo "</b></td>n";  }  echo "</tr>n";  // 定位到第一条记录  mysql_data_seek($result, 0);  // 循环取出记录  while ($row=mysql_fetch_row($result))  {  echo "<tr>n";  for ($i=0; $i<mysql_num_fields($result); $i++ ){echo '<td bgcolor="#00FF00">';echo "$row[$i]";  echo '</td>';  }  echo "</tr>n";  }  echo "</table>n";  echo "</font>";  // 释放资源  mysql_free_result($result);  // 关闭连接  mysql_close();  ?>  -------------------------------------------------------------------------------------  <?php$link = mysql_connect("mysql_host", "mysql_user", "mysql_password") or die("Could not connect");print "Connected successfully";mysql_select_db("my_database") or die("Could not select database");$query = "SELECT * FROM my_table";$result = mysql_query($query) or die("Query failed");print "<table>n";while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { print "t<tr>n"; foreach ($line as $col_value) { print "tt<td>$col_value</td>n"; } print "t</tr>n"; } print "</table>n";mysql_free_result($result);mysql_close($link);?>  -------------------------------------------------------------------------------------  代码单独存为一个文件,在以后要用到这些代码时只要include这个页面就可以了.如这个页面要要添加数据入数据库,那么在里include "";