<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>PHP连接MySQL</title>
</head>
<body style="padding-left:80px;">
<?php
$connect = mysql_connect("localhost","用户名","密码") or die(mysql_error());//建立连接
mysql_select_db("sample") or die(mysql_error());//选择数据库
mysql_set_charset("utf8");//设置MySQL连接字符集
echo "<br /><b>=======显示初始数据=======</b>";
showData();
//执行添加操作
$sql_add1 = "INSERT INTO userInfo(`usName`,`usPwd`,`usAddress`) VALUES('贾君鹏', 'jjpeng', '杭州') ";
$sql_add2 = "INSERT INTO userInfo(`usName`,`usPwd`,`usAddress`) VALUES('周星星', 'zxxing', 'hongkong') ";
$sql_add3 = "INSERT INTO userInfo(`usName`,`usPwd`,`usAddress`) VALUES('superman', 'super', '火星') ";
mysql_query($sql_add1) or die(mysql_error());
mysql_query($sql_add2) or die(mysql_error());
mysql_query($sql_add3) or die(mysql_error());
echo "<br /><b>=======执行添加后=======</b>";
showData();
//执行更新操作
$sql_update = "UPDATE userInfo SET `usAddress`='太空' WHERE `usName`='superman'";
mysql_query($sql_update) or die(mysql_error());
echo "<br /><b>=======执行更新后=======</b>";
showData();
//执行删除操作
$sql_delete = "DELETE FROM userInfo WHERE `usName`='贾君鹏'";
mysql_query($sql_delete) or die(mysql_error());
echo "<br /><b>=======执行删除后=======</b>";
showData();
//关闭连接
mysql_close($connect);
?>
<?php
//显示数据
function showData(){
$sql_query = "select * from userInfo";
$result= mysql_query($sql_query) or die(mysql_error());
echo "<table border='1' cellpadding='5' cellspacing='0'>";
/*
mysql_fetch_array 从结果集中取得一行,返回数组,若没有更多行则返回false
第二个参数,规定返回哪种结果:
•MYSQL_ASSOC(关联数组)
•MYSQL_NUM(数字数组)
•MYSQL_BOTH(默认,同时产生关联和数字数组)
*/
$count=0;
while($line=mysql_fetch_array($result,MYSQL_ASSOC)){
echo "<tr>";
foreach($line as $col_key => $col_value){
echo "<td height='30'>".$col_key.":".$col_value."</td>";
}
$count++;
echo "</tr>";
}
echo "</table>";
echo "--------总共".$count."行记录<br />";
mysql_free_result($result);//释放内存
}
?>
</body>
</html>
PHP连接MySQL
最新推荐文章于 2023-05-30 20:05:25 发布