如何用PHP连接MySQL

匿名网友 匿名网友 发布于: 2015-08-30 00:00:00
阅读 155 收藏 0 点赞 0 评论 0

1)连接:&conn=mysql_connect(“localhost”, “joeuser”, “somepass”);

2)关闭连接:mysql_close($conn);

3) 数据库与连接建立联系:mysql_select_db(database name, connection index);

4) 将SQL语句给MySQL执行:$result = mysql_query($sql, $conn); //增删改查都是这句

5) 检索数据:返回记录数:$number_of_rows = mysql_num_rows($result);

   将记录放入数组:$newArray = mysql_fetch_array($result);

   例子:

  1: <?php
2: // open the connection
3: $conn = mysql_connect(“localhost”, “joeuser”, “somepass”);
4: // pick the database to use
5: mysql_select_db(“testDB”,$conn);
6: // create the SQL statement
7: $sql = “SELECT * FROM testTable”;
8: // execute the SQL statement
9: $result = mysql_query($sql, $conn) or die(mysql_error());
10: //go through each row in the result set and display data
11: while ($newArray = mysql_fetch_array($result)) {
12:     // give a name to the fields
13:     $id = $newArray[‘id’];
14:     $testField = $newArray[‘testField’];
15:     //echo the results onscreen
16:     echo “The ID is $id and the text is $testField <br>”;
17: }
18: ?>

评论列表